Example usage for java.lang Float isNaN

List of usage examples for java.lang Float isNaN

Introduction

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

Prototype

public static boolean isNaN(float v) 

Source Link

Document

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

Usage

From source file:org.broad.igv.tdf.Accumulator.java

public void finish() {

    if (isFinished) {
        return;/*  ww  w  . ja  v  a2s  . c  o  m*/
    }

    if (windowFunction == WindowFunction.mean) {
        value = Float.isNaN(sum) ? Float.NaN : sum / basesCovered;
    } else if (values != null) {
        if (values.size() == 1) {
            value = (float) values.get(0);
        } else {
            if (values.size() > 1) {
                computePercentiles();
            }

            float v = Float.NaN; // <= Default,
            if (percentiles != null && percentiles.size() > 0) {
                double weightedSum = 0;
                double sumOfWeights = 0;
                for (PercentileValue pv : percentiles) {
                    double weight = (double) pv.nPoints / basesCovered;
                    sumOfWeights += weight;
                    weightedSum += weight * pv.value;
                }
                v = (float) (weightedSum / sumOfWeights);
            }
            value = v;

        }
    }
    values = null;
    isFinished = true;

}

From source file:savant.view.tracks.ContinuousTrackRenderer.java

@Override
public void render(Graphics2D g2, GraphPaneAdapter gp) throws RenderingException {

    renderPreCheck();/*w  ww  . j  a v  a 2  s  .  c  o  m*/

    AxisRange axisRange = (AxisRange) instructions.get(DrawingInstruction.AXIS_RANGE);
    gp.setXRange(axisRange.getXRange());
    gp.setYRange(axisRange.getYRange());

    if (gp.needsToResize())
        return;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);
    Color fillcolor = cs.getColor(ColourKey.CONTINUOUS_FILL);
    Color linecolor = cs.getColor(ColourKey.CONTINUOUS_LINE);

    GeneralPath path = new GeneralPath();
    double xFormXPos = Double.NaN, xFormYPos = Double.NaN;

    double yPixel0 = gp.transformYPos(0.0);
    LOG.debug("h=" + gp.getHeight() + ", yMin=" + gp.getYRange().getFrom() + ", unitHeight="
            + gp.getUnitHeight() + " \u27A4 yPixel0=" + yPixel0);

    double maxData = 0;
    boolean haveOpenPath = false;
    boolean haveData = false;
    if (data != null) {
        for (int i = 0; i < data.size(); i++) {
            ContinuousRecord continuousRecord = (ContinuousRecord) data.get(i);
            int xPos = continuousRecord.getPosition();
            float yPos = continuousRecord.getValue();
            if (Float.isNaN(yPos)) {
                // Hit a position with no data.  May need to close off the current path.
                if (haveOpenPath) {
                    path.lineTo(xFormXPos, yPixel0);
                    path.closePath();
                    haveOpenPath = false;
                }
            } else {
                haveData = true;
                xFormXPos = gp.transformXPos(xPos);//+gp.getUnitWidth()/2;
                xFormYPos = gp.transformYPos(yPos);
                if (!haveOpenPath) {
                    // Start our path off with a vertical line.
                    path.moveTo(xFormXPos, yPixel0);
                    haveOpenPath = true;
                }
                path.lineTo(xFormXPos, xFormYPos);
                Rectangle2D rec = new Rectangle2D.Double(
                        xFormXPos - ((xFormXPos - path.getCurrentPoint().getX()) / 2), 0,
                        Math.max(xFormXPos - path.getCurrentPoint().getX(), 1), gp.getHeight());
                recordToShapeMap.put(continuousRecord, rec);
                xFormXPos = gp.transformXPos(xPos + 1);
                path.lineTo(xFormXPos, xFormYPos);
            }
            if (yPos > maxData) {
                maxData = yPos;
            }
        }
    }
    if (!haveData) {
        throw new RenderingException("No data in range", RenderingException.INFO_PRIORITY);
    }
    if (haveOpenPath) {
        // Path needs to be closed.
        path.lineTo(xFormXPos, yPixel0);
        path.closePath();
    }

    g2.setColor(fillcolor);
    g2.fill(path);
    g2.setColor(linecolor);
    g2.draw(path);

    if (axisRange.getYRange().getFrom() < 0) {
        g2.setColor(Color.darkGray);
        g2.draw(new Line2D.Double(0.0, yPixel0, gp.getWidth(), yPixel0));
    }
}

From source file:org.caleydo.view.tourguide.impl.PAGEAlgorithm.java

@Override
protected float computePValueImpl(Set<Integer> geneSet, IProgressMonitor monitor) {
    float z = compute(geneSet, monitor);
    if (Float.isNaN(z))
        return Float.NaN;
    int m = Sets.intersection(foldChanges.keySet(), geneSet).size();
    if (m == 0)/*from   w w  w  .j av a  2s  .  c o m*/
        return Float.NaN;
    TDistributionImpl t = new TDistributionImpl(m);
    float pValue = (float) t.density(z);
    return pValue;
}

From source file:io.github.dsheirer.spectrum.SpectrumPanel.java

/**
 * DFTResultsListener interface for receiving the processed data
 * to display/*  ww  w.java2s  .  c o  m*/
 */
public void receive(float[] currentFFTBins) {
    //Prevent arrays of NaN values from being rendered.  The first few
    //DFT result sets on startup will contain NaN values
    if (Float.isInfinite(currentFFTBins[0]) || Float.isNaN(currentFFTBins[0])) {
        currentFFTBins = new float[currentFFTBins.length];
    }

    //Construct and/or resize our DFT results variables
    if (mDisplayFFTBins == null || mDisplayFFTBins.length != currentFFTBins.length) {
        mDisplayFFTBins = currentFFTBins;
    }

    //Apply smoothing across the bins of the DFT results
    float[] smoothedBins = mSmoothingFilter.filter(currentFFTBins);

    //Apply averaging over multiple DFT output frames
    if (mAveraging > 1) {
        float gain = 1.0f / (float) mAveraging;

        for (int x = 0; x < mDisplayFFTBins.length; x++) {
            mDisplayFFTBins[x] += (smoothedBins[x] - mDisplayFFTBins[x]) * gain;
        }
    } else {
        mDisplayFFTBins = smoothedBins;
    }

    repaint();
}

From source file:IntHashMap.java

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor./*from   ww w.j a va2 s  .c o  m*/
 * 
 * @param initialCapacity
 *            The initial capacity.
 * @param loadFactor
 *            The load factor.
 * @throws IllegalArgumentException
 *             if the initial capacity is negative or the load factor is
 *             nonpositive.
 */
public IntHashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0) {
        throw new IllegalArgumentException("Illegal initial capacity: " + //$NON-NLS-1$
                initialCapacity);
    }
    if (initialCapacity > MAXIMUM_CAPACITY) {
        initialCapacity = MAXIMUM_CAPACITY;
    }
    if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
        throw new IllegalArgumentException("Illegal load factor: " + //$NON-NLS-1$
                loadFactor);
    }

    // Find a power of 2 >= initialCapacity
    int capacity = 1;
    while (capacity < initialCapacity) {
        capacity <<= 1;
    }

    this.loadFactor = loadFactor;
    threshold = (int) (capacity * loadFactor);
    table = new Entry[capacity];
    init();
}

From source file:org.janusgraph.core.attribute.Geoshape.java

private Geoshape(final float[][] coordinates) {
    Preconditions.checkArgument(coordinates != null && coordinates.length == 2);
    Preconditions.checkArgument(coordinates[0].length == coordinates[1].length && coordinates[0].length > 0);
    for (int i = 0; i < coordinates[0].length; i++) {
        if (Float.isNaN(coordinates[0][i]))
            Preconditions.checkArgument(i == 1 && coordinates.length == 2 && coordinates[1][i] > 0);
        else/*from   w ww  .j av a 2  s  .c  o  m*/
            Preconditions.checkArgument(isValidCoordinate(coordinates[0][i], coordinates[1][i]));
    }
    this.coordinates = coordinates;
}

From source file:IntHashMap.java

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial capacity and load factor.
 * //  w ww .ja v a2s  . com
 * @param initialCapacity
 *            The initial capacity.
 * @param loadFactor
 *            The load factor.
 * @throws IllegalArgumentException
 *             if the initial capacity is negative or the load factor is nonpositive.
 */
@SuppressWarnings("unchecked")
public IntHashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0) {
        throw new IllegalArgumentException("Illegal initial capacity: " + //$NON-NLS-1$
                initialCapacity);
    }
    if (initialCapacity > MAXIMUM_CAPACITY) {
        initialCapacity = MAXIMUM_CAPACITY;
    }
    if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
        throw new IllegalArgumentException("Illegal load factor: " + //$NON-NLS-1$
                loadFactor);
    }

    // Find a power of 2 >= initialCapacity
    int capacity = 1;
    while (capacity < initialCapacity) {
        capacity <<= 1;
    }

    this.loadFactor = loadFactor;
    threshold = (int) (capacity * loadFactor);
    table = new Entry[capacity];
    init();
}

From source file:ml.shifu.shifu.core.dtrain.nn.NNParquetWorker.java

@Override
public void load(GuaguaWritableAdapter<LongWritable> currentKey, GuaguaWritableAdapter<Tuple> currentValue,
        WorkerContext<NNParams, NNParams> workerContext) {
    // init field list for later read
    this.initFieldList();

    LOG.info("subFeatureSet size: {} ; subFeatureSet: {}", subFeatureSet.size(), subFeatureSet);

    super.count += 1;
    if ((super.count) % 5000 == 0) {
        LOG.info("Read {} records.", super.count);
    }//from w ww  . ja  v  a  2s.c  o  m

    float[] inputs = new float[super.featureInputsCnt];
    float[] ideal = new float[super.outputNodeCount];

    if (super.isDry) {
        // dry train, use empty data.
        addDataPairToDataSet(0,
                new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal)));
        return;
    }

    long hashcode = 0;
    float significance = 1f;
    // use guava Splitter to iterate only once
    // use NNConstants.NN_DEFAULT_COLUMN_SEPARATOR to replace getModelConfig().getDataSetDelimiter(), super follows
    // the function in akka mode.
    int index = 0, inputsIndex = 0, outputIndex = 0;

    Tuple tuple = currentValue.getWritable();

    // back from foreach to for loop because of in earlier version, tuple cannot be iterable.
    for (int i = 0; i < tuple.size(); i++) {
        Object element = null;
        try {
            element = tuple.get(i);
        } catch (ExecException e) {
            throw new GuaguaRuntimeException(e);
        }
        float floatValue = 0f;
        if (element != null) {
            if (element instanceof Float) {
                floatValue = (Float) element;
            } else {
                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                floatValue = element.toString().length() == 0 ? 0f
                        : NumberFormatUtils.getFloat(element.toString(), 0f);
            }
        }
        // no idea about why NaN in input data, we should process it as missing value TODO , according to norm type
        floatValue = (Float.isNaN(floatValue) || Double.isNaN(floatValue)) ? 0f : floatValue;

        if (index == (super.inputNodeCount + super.outputNodeCount)) {
            // do we need to check if not weighted directly set to 1f; if such logic non-weight at first, then
            // weight, how to process???
            if (StringUtils.isBlank(modelConfig.getWeightColumnName())) {
                significance = 1f;
                // break here if we reach weight column which is last column
                break;
            }

            assert element != null;
            if (element != null && element instanceof Float) {
                significance = (Float) element;
            } else {
                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                significance = element.toString().length() == 0 ? 1f
                        : NumberFormatUtils.getFloat(element.toString(), 1f);
            }
            // if invalid weight, set it to 1f and warning in log
            if (Float.compare(significance, 0f) < 0) {
                LOG.warn(
                        "The {} record in current worker weight {} is less than 0f, it is invalid, set it to 1.",
                        count, significance);
                significance = 1f;
            }
            // break here if we reach weight column which is last column
            break;
        } else {
            int columnIndex = requiredFieldList.getFields().get(index).getIndex();
            if (columnIndex >= super.columnConfigList.size()) {
                assert element != null;
                if (element != null && element instanceof Float) {
                    significance = (Float) element;
                } else {
                    // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                    significance = element.toString().length() == 0 ? 1f
                            : NumberFormatUtils.getFloat(element.toString(), 1f);
                }
                break;
            } else {
                ColumnConfig columnConfig = super.columnConfigList.get(columnIndex);
                if (columnConfig != null && columnConfig.isTarget()) {
                    if (modelConfig.isRegression()) {
                        ideal[outputIndex++] = floatValue;
                    } else {
                        if (modelConfig.getTrain().isOneVsAll()) {
                            // if one vs all, set correlated idea value according to trainerId which means in
                            // trainer with id 0, target 0 is treated with 1, other are 0. Such target value are set
                            // to index of tags like [0, 1, 2, 3] compared with ["a", "b", "c", "d"]
                            ideal[outputIndex++] = Float.compare(floatValue, trainerId) == 0 ? 1f : 0f;
                        } else {
                            if (modelConfig.getTags().size() == 2) {
                                // if only 2 classes, output node is 1 node. if target = 0 means 0 is the index for
                                // positive prediction, set positive to 1 and negative to 0
                                int ideaIndex = (int) floatValue;
                                ideal[0] = ideaIndex == 0 ? 1f : 0f;
                            } else {
                                // for multiple classification
                                int ideaIndex = (int) floatValue;
                                ideal[ideaIndex] = 1f;
                            }
                        }
                    }
                } else {
                    if (subFeatureSet.contains(columnIndex)) {
                        inputs[inputsIndex++] = floatValue;
                        hashcode = hashcode * 31 + Double.valueOf(floatValue).hashCode();
                    }
                }
            }
        }
        index += 1;
    }

    // output delimiter in norm can be set by user now and if user set a special one later changed, this exception
    // is helped to quick find such issue.
    if (inputsIndex != inputs.length) {
        String delimiter = workerContext.getProps().getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER,
                Constants.DEFAULT_DELIMITER);
        throw new RuntimeException("Input length is inconsistent with parsing size. Input original size: "
                + inputs.length + ", parsing size:" + inputsIndex + ", delimiter:" + delimiter + ".");
    }

    // sample negative only logic here
    if (modelConfig.getTrain().getSampleNegOnly()) {
        if (this.modelConfig.isFixInitialInput()) {
            // if fixInitialInput, sample hashcode in 1-sampleRate range out if negative records
            int startHashCode = (100 / this.modelConfig.getBaggingNum()) * this.trainerId;
            // here BaggingSampleRate means how many data will be used in training and validation, if it is 0.8, we
            // should take 1-0.8 to check endHashCode
            int endHashCode = startHashCode
                    + Double.valueOf((1d - this.modelConfig.getBaggingSampleRate()) * 100).intValue();
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (ideal[0] + 0.01d) == 0 // negative record
                    && isInRange(hashcode, startHashCode, endHashCode)) {
                return;
            }
        } else {
            // if not fixed initial input, and for regression or onevsall multiple classification (regression also).
            // if negative record
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (ideal[0] + 0.01d) == 0 // negative record
                    && Double.compare(super.sampelNegOnlyRandom.nextDouble(),
                            this.modelConfig.getBaggingSampleRate()) >= 0) {
                return;
            }
        }
    }

    FloatMLDataPair pair = new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal));

    // up sampling logic
    if (modelConfig.isRegression() && isUpSampleEnabled() && Double.compare(ideal[0], 1d) == 0) {
        // Double.compare(ideal[0], 1d) == 0 means positive tags; sample + 1 to avoid sample count to 0
        pair.setSignificance(significance * (super.upSampleRng.sample() + 1));
    } else {
        pair.setSignificance(significance);
    }

    boolean isValidation = false;
    if (workerContext.getAttachment() != null && workerContext.getAttachment() instanceof Boolean) {
        isValidation = (Boolean) workerContext.getAttachment();
    }

    boolean isInTraining = addDataPairToDataSet(hashcode, pair, isValidation);

    // do bagging sampling only for training data
    if (isInTraining) {
        float subsampleWeights = sampleWeights(pair.getIdealArray()[0]);
        if (isPositive(pair.getIdealArray()[0])) {
            this.positiveSelectedTrainCount += subsampleWeights * 1L;
        } else {
            this.negativeSelectedTrainCount += subsampleWeights * 1L;
        }
        // set weights to significance, if 0, significance will be 0, that is bagging sampling
        pair.setSignificance(pair.getSignificance() * subsampleWeights);
    } else {
        // for validation data, according bagging sampling logic, we may need to sampling validation data set, while
        // validation data set are only used to compute validation error, not to do real sampling is ok.
    }
}

From source file:net.myrrix.online.generation.InputFilesReader.java

static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs, FastByIDMap<FastByIDFloatMap> rbyRow,
        FastByIDMap<FastByIDFloatMap> rbyColumn, FastIDSet itemTagIDs, FastIDSet userTagIDs, File inputDir)
        throws IOException {

    FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?");

    File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter));
    if (otherFiles != null) {
        for (File otherFile : otherFiles) {
            log.info("Skipping file {}", otherFile.getName());
        }//  w  w w.  j a v  a  2  s  .c o m
    }

    File[] inputFiles = inputDir.listFiles(csvFilter);
    if (inputFiles == null) {
        log.info("No input files in {}", inputDir);
        return;
    }
    Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE);

    IDMigrator hash = new OneWayMigrator();

    int lines = 0;
    int badLines = 0;
    for (File inputFile : inputFiles) {
        log.info("Reading {}", inputFile);
        for (String line : new FileLineIterable(inputFile)) {

            if (badLines > 100) { // Crude check
                throw new IOException("Too many bad lines; aborting");
            }

            lines++;

            if (line.isEmpty() || line.charAt(0) == '#') {
                continue;
            }

            Iterator<String> it = COMMA.split(line).iterator();

            long userID;
            boolean userIsTag;
            long itemID;
            boolean itemIsTag;
            float value;
            try {

                String userIDString = it.next();
                userIsTag = userIDString.startsWith("\"");
                if (userIsTag) {
                    userID = hash.toLongID(userIDString.substring(1, userIDString.length() - 1));
                } else {
                    userID = Long.parseLong(userIDString);
                }

                String itemIDString = it.next();
                itemIsTag = itemIDString.startsWith("\"");
                if (itemIsTag) {
                    itemID = hash.toLongID(itemIDString.substring(1, itemIDString.length() - 1));
                } else {
                    itemID = Long.parseLong(itemIDString);
                }

                if (it.hasNext()) {
                    String valueToken = it.next();
                    value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken);
                } else {
                    value = 1.0f;
                }

            } catch (NoSuchElementException ignored) {
                log.warn("Ignoring line with too few columns: '{}'", line);
                badLines++;
                continue;
            } catch (IllegalArgumentException iae) { // includes NumberFormatException
                if (lines == 1) {
                    log.info("Ignoring header line: '{}'", line);
                } else {
                    log.warn("Ignoring unparseable line: '{}'", line);
                    badLines++;
                }
                continue;
            }

            if (userIsTag && itemIsTag) {
                log.warn("Two tags not allowed: '{}'", line);
                badLines++;
                continue;
            }

            if (userIsTag) {
                itemTagIDs.add(userID);
            }

            if (itemIsTag) {
                userTagIDs.add(itemID);
            }

            if (Float.isNaN(value)) {
                // Remove, not set
                MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn);
            } else {
                MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn);
            }

            if (knownItemIDs != null) {
                FastIDSet itemIDs = knownItemIDs.get(userID);
                if (Float.isNaN(value)) {
                    // Remove, not set
                    if (itemIDs != null) {
                        itemIDs.remove(itemID);
                        if (itemIDs.isEmpty()) {
                            knownItemIDs.remove(userID);
                        }
                    }
                } else {
                    if (itemIDs == null) {
                        itemIDs = new FastIDSet();
                        knownItemIDs.put(userID, itemIDs);
                    }
                    itemIDs.add(itemID);
                }
            }

            if (lines % 1000000 == 0) {
                log.info("Finished {} lines", lines);
            }
        }
    }

    log.info("Pruning near-zero entries");
    removeSmall(rbyRow);
    removeSmall(rbyColumn);
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Returns true if both arguments are NaN or neither is NaN and they are
 * equal as defined by {@link #equals(float,float) equals(x, y, 1)}.
 *
 * @param x first value//from   w  ww  .j ava2  s .  com
 * @param y second value
 * @return {@code true} if the values are equal or both are NaN.
 * @since 2.2
 */
public static boolean equalsIncludingNaN(float x, float y) {
    return (Float.isNaN(x) && Float.isNaN(y)) || equals(x, y, 1);
}