Example usage for java.lang Float NaN

List of usage examples for java.lang Float NaN

Introduction

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

Prototype

float NaN

To view the source code for java.lang Float NaN.

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type float .

Usage

From source file:nars.truth.Truth.java

default float getComponent(@NotNull TruthComponent c) {
    switch (c) {//  w w  w. j  a  v a 2  s  .  com
    case Frequency:
        return freq();
    case Confidence:
        return conf();
    case Expectation:
        return expectation();
    }
    return Float.NaN;
}

From source file:edu.cornell.med.icb.goby.methylation.MethylSimilarityScan.java

private Query findQuery(MethylationData data, String chromosomeSelected, char strandSelected, int windowWidth,
        int minSites) {

    MethylationSiteIterator iterator = data.iterator(strandSelected);
    iterator.skipTo(chromosomeSelected);

    Int2IntMap startTally = new Int2IntOpenHashMap();
    Int2IntMap endTally = new Int2IntOpenHashMap();
    int lastStartPosition = 0;
    int lastEndPosition = 0;

    while (iterator.hasNextSite()) {

        MethylationSite site = iterator.nextSite();

        startTally.put(site.position, startTally.get(lastStartPosition) + 1);
        endTally.put(site.position + 1, endTally.get(lastEndPosition) + 1);
        lastStartPosition = site.position;
        lastEndPosition = site.position + 1;
    }//from w  w w .jav a2  s . c o  m

    IntArrayList indices = new IntArrayList();
    indices.addAll(startTally.keySet());
    indices.addAll(endTally.keySet());
    Collections.sort(indices);
    Query query = null;
    for (int index : indices) {

        final int start = index;
        int end = start + windowWidth;
        while (!endTally.containsKey(end)) {
            // reduce window size until we find a position where a site ended.
            end--;
        }

        if (endTally.get(end) - startTally.get(start) >= minSites) {
            System.out.printf("queryStart=%d queryEnd=%d%n", start, end);
            // return the first window of size windowSize with at least minSites in the window
            query = new Query();
            query.positionEnd = end;
            query.positionStart = start;
            query.chromosomeIndex = data.getChromosomeIndex(chromosomeSelected);
            query.strand = strandSelected;
            break;
        }
    }
    if (query != null) {
        iterator = data.iterator(strandSelected);
        iterator.skipTo(chromosomeSelected);
        iterator.skipToPosition(query.positionStart);
        query.methylationRates = new FloatArrayList();
        int lastPosition = query.positionStart;
        while (iterator.hasNextSite()) {

            MethylationSite site = iterator.nextSite();

            query.methylationRates.add(site.getMethylationRate());
            for (int p = lastPosition; p < Math.min(site.position - 1, query.positionEnd); p++) {
                query.methylationRates.add(Float.NaN);
            }
            lastPosition = site.position;
            if (site.position > query.positionEnd)
                break;
            query.sites.add(site);
        }
    }
    return query;
}

From source file:com.alibaba.citrus.util.internal.apache.lang.EqualsBuilderTests.java

public void testFloat() {
    float o1 = 1;
    float o2 = 2;
    assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
    assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
    assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals());
    assertTrue(new EqualsBuilder().append(Float.NaN, Float.NaN).isEquals());
    assertTrue(new EqualsBuilder().append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY).isEquals());
}

From source file:net.iponweb.hadoop.streaming.avro.IOWJsonDecoder.java

@Override
public float readFloat() throws IOException {
    advance(Symbol.FLOAT);//w w  w . j  a va 2  s.  c o m
    if (in.getCurrentToken().isNumeric()) {
        float result = in.getFloatValue();
        in.nextToken();
        return result;
    } else {
        try {
            String s = in.getText();
            in.nextToken();
            if (s.equals("NaN")) {
                return Float.NaN;
            } else if (s.equals("-Inf")) {
                return Float.NEGATIVE_INFINITY;
            } else if (s.equals("+Inf")) {
                return Float.POSITIVE_INFINITY;
            } else {
                return Float.parseFloat(s);
            }
        } catch (Exception e) {
            throw error("float (" + e.getMessage() + ")");
        }
    }
}

From source file:uk.ac.babraham.SeqMonk.Pipelines.CodonBiasPipeline.java

protected void startPipeline() {

    // We first need to generate probes over all of the features listed in
    // the feature types.  The probes should cover the whole area of the
    // feature regardless of where it splices.

    Vector<Probe> probes = new Vector<Probe>();
    double pValue = optionsPanel.pValue();

    String libraryType = optionsPanel.libraryType();

    Chromosome[] chrs = collection().genome().getAllChromosomes();

    for (int c = 0; c < chrs.length; c++) {
        if (cancel) {
            progressCancelled();/*from  w  w  w .  j  a va 2s  .co  m*/
            return;
        }

        progressUpdated("Making probes for chr" + chrs[c].name(), c, chrs.length * 2);

        Feature[] features = collection().genome().annotationCollection().getFeaturesForType(chrs[c],
                optionsPanel.getSelectedFeatureType());

        for (int f = 0; f < features.length; f++) {
            if (cancel) {
                progressCancelled();
                return;
            }
            Probe p = new Probe(chrs[c], features[f].location().start(), features[f].location().end(),
                    features[f].location().strand(), features[f].name());
            probes.add(p);

        }
    }

    allProbes = probes.toArray(new Probe[0]);

    collection().setProbeSet(new ProbeSet("Features over " + optionsPanel.getSelectedFeatureType(), allProbes));

    // Now we can quantitate each individual feature and test for whether it is significantly 
    // showing codon bias      
    ArrayList<Vector<ProbeTTestValue>> significantProbes = new ArrayList<Vector<ProbeTTestValue>>();

    // data contains the data stores that this pipeline is going to use. We need to test each data store.
    for (int d = 0; d < data.length; d++) {
        significantProbes.add(new Vector<ProbeTTestValue>());
    }

    int probeCounter = 0;

    for (int c = 0; c < chrs.length; c++) {
        if (cancel) {
            progressCancelled();
            return;
        }

        progressUpdated("Quantitating features on chr" + chrs[c].name(), chrs.length + c, chrs.length * 2);

        Feature[] features = collection().genome().annotationCollection().getFeaturesForType(chrs[c],
                optionsPanel.getSelectedFeatureType());

        for (int p = 0; p < features.length; p++) {

            //Get the corresponding feature and work out the mapping between genomic position and codon sub position.   
            int[] mappingArray = createGenomeMappingArray(features[p]);

            DATASTORE_LOOP: for (int d = 0; d < data.length; d++) {

                if (cancel) {
                    progressCancelled();
                    return;
                }

                long[] reads = data[d].getReadsForProbe(allProbes[probeCounter]);

                //System.err.println("Number of reads = " + reads.length);               

                //TODO: make this configurable
                if (reads.length < 5) {

                    data[d].setValueForProbe(allProbes[probeCounter], Float.NaN);
                    continue DATASTORE_LOOP;
                }

                int pos1Count = 0;
                int pos2Count = 0;
                int pos3Count = 0;

                //System.out.println("quantitating " + data[d].name());
                //System.err.println("Number of reads = " + reads.length);   

                READ_LOOP: for (int r = 0; r < reads.length; r++) {

                    int genomicReadStart = SequenceRead.start(reads[r]);
                    int genomicReadEnd = SequenceRead.end(reads[r]);
                    int readStrand = SequenceRead.strand(reads[r]);
                    int relativeReadStart = -1;

                    // work out where the start of the read is relative to the feature, 
                    // depending on strandedness of read, probe and library type  

                    // forward reads
                    if (readStrand == 1) {

                        if (libraryType == "Same strand specific") {

                            if (features[p].location().strand() == Location.FORWARD) {

                                // The start of the read needs to be within the feature
                                if (genomicReadStart - features[p].location().start() < 0) {
                                    continue READ_LOOP;
                                }

                                else {
                                    // look up the read start pos in the mapping array
                                    relativeReadStart = mappingArray[genomicReadStart
                                            - features[p].location().start()];

                                }
                            }

                        }

                        else if (libraryType == "Opposing strand specific") {

                            if (features[p].location().strand() == Location.REVERSE) {

                                // The start of the read needs to be within the feature
                                // The "start" of a reverse read/probe is actually the end  
                                if (features[p].location().end() - genomicReadEnd < 0) {
                                    continue READ_LOOP;
                                }

                                else {
                                    relativeReadStart = mappingArray[features[p].location().end()
                                            - genomicReadEnd];
                                }
                            }
                        }
                    }

                    // reverse reads
                    if (readStrand == -1) {

                        if (libraryType == "Same strand specific") {

                            if (features[p].location().strand() == Location.REVERSE) {

                                if (features[p].location().end() - genomicReadEnd < 0) {
                                    continue READ_LOOP;
                                }

                                else {
                                    //System.out.println("features[p].location().end() is " + features[p].location().end() + ", genomicReadEnd is " + genomicReadEnd);
                                    //System.out.println("mapping array[0] is " + mappingArray[0]);
                                    relativeReadStart = mappingArray[features[p].location().end()
                                            - genomicReadEnd];
                                }
                            }
                        }

                        else if (libraryType == "Opposing strand specific") {

                            if (features[p].location().strand() == Location.FORWARD) {

                                // The start of the read needs to be within the feature
                                if (genomicReadStart - features[p].location().start() < 0) {
                                    continue READ_LOOP;
                                }

                                else {
                                    //    look up the read start position in the mapping array
                                    relativeReadStart = mappingArray[genomicReadStart
                                            - features[p].location().start()];
                                }
                            }
                        }

                    }

                    // find out which position the read is in
                    if (relativeReadStart == -1) {
                        continue READ_LOOP;
                    } else if (relativeReadStart % 3 == 0) {
                        pos3Count++;
                        continue READ_LOOP;
                    } else if ((relativeReadStart + 1) % 3 == 0) {
                        pos2Count++;
                        continue READ_LOOP;
                    } else if ((relativeReadStart + 2) % 3 == 0) {
                        pos1Count++;
                    }

                } // closing bracket for read loop

                //System.out.println("pos1Count for "+ features[p].name() + " is " + pos1Count);
                //System.out.println("pos2Count for "+ features[p].name() + " is " + pos2Count);
                //System.out.println("pos3Count for "+ features[p].name() + " is " + pos3Count);

                int interestingCodonCount = 0;
                int otherCodonCount = 0;

                if (optionsPanel.codonSubPosition() == 1) {
                    interestingCodonCount = pos1Count;
                    otherCodonCount = pos2Count + pos3Count;
                }

                else if (optionsPanel.codonSubPosition() == 2) {
                    interestingCodonCount = pos2Count;
                    otherCodonCount = pos1Count + pos3Count;
                }

                else if (optionsPanel.codonSubPosition() == 3) {
                    interestingCodonCount = pos3Count;
                    otherCodonCount = pos1Count + pos2Count;
                }

                int totalCount = interestingCodonCount + otherCodonCount;

                //BinomialDistribution bd = new BinomialDistribution(interestingCodonCount+otherCodonCount, 1/3d);

                BinomialDistribution bd = new BinomialDistribution(totalCount, 1 / 3d);

                // Since the binomial distribution gives the probability of getting a value higher than
                // this we need to subtract one so we get the probability of this or higher.
                double thisPValue = 1 - bd.cumulativeProbability(interestingCodonCount - 1);

                if (interestingCodonCount == 0)
                    thisPValue = 1;

                // We have to add all results at this stage so we don't mess up the multiple 
                // testing correction later on.
                significantProbes.get(d).add(new ProbeTTestValue(allProbes[probeCounter], thisPValue));

                float percentageCount;

                if (totalCount == 0) {
                    percentageCount = 0;
                } else {
                    percentageCount = ((float) interestingCodonCount / (float) totalCount) * 100;
                }

                data[d].setValueForProbe(allProbes[probeCounter], percentageCount);

                //System.out.println("totalCount = " + totalCount);
                //System.out.println("interestingCodonCount " + interestingCodonCount);
                //System.out.println("pValue = " + thisPValue);
                //System.out.println("percentageCount = " + percentageCount);
                //System.out.println("");

            }
            probeCounter++;
        }
    }

    // Now we can go through the set of significant probes, applying a correction and then
    // filtering those which pass our p-value cutoff
    for (int d = 0; d < data.length; d++) {

        ProbeTTestValue[] ttestResults = significantProbes.get(d).toArray(new ProbeTTestValue[0]);

        BenjHochFDR.calculateQValues(ttestResults);

        ProbeList newList = new ProbeList(collection().probeSet(),
                "Codon bias < " + pValue + " in " + data[d].name(),
                "Probes showing significant codon bias for position " + optionsPanel.codonSubPosition()
                        + " with a cutoff of " + pValue,
                "FDR");

        for (int i = 0; i < ttestResults.length; i++) {

            //System.out.println("p value is " + ttestResults[i].p + ", q value is " + ttestResults[i].q);

            if (ttestResults[i].q < pValue) {
                newList.addProbe(ttestResults[i].probe, (float) ttestResults[i].q);
            }
        }
    }

    StringBuffer quantitationDescription = new StringBuffer();
    quantitationDescription.append("Codon bias pipeline using codon position " + optionsPanel.codonSubPosition()
            + " for " + optionsPanel.libraryType() + " library.");

    collection().probeSet().setCurrentQuantitation(quantitationDescription.toString());

    quantitatonComplete();

}

From source file:uk.co.modularaudio.mads.base.oscillator.mu.OscillatorMadInstance.java

@Override
public RealtimeMethodReturnCodeEnum process(final ThreadSpecificTemporaryEventStorage tempQueueEntryStorage,
        final MadTimingParameters timingParameters, final long periodStartFrameTime,
        final MadChannelConnectedFlags channelConnectedFlags, final MadChannelBuffer[] channelBuffers,
        final int frameOffset, final int numFrames) {
    final boolean cvFreqConnected = channelConnectedFlags.get(OscillatorMadDefinition.CONSUMER_CV_FREQ);
    final MadChannelBuffer cvFreqBuf = channelBuffers[OscillatorMadDefinition.CONSUMER_CV_FREQ];
    final boolean audioOutConnected = channelConnectedFlags.get(OscillatorMadDefinition.PRODUCER_AUDIO_OUT);
    final MadChannelBuffer audioOutBuf = channelBuffers[OscillatorMadDefinition.PRODUCER_AUDIO_OUT];
    final boolean cvOutConnected = channelConnectedFlags.get(OscillatorMadDefinition.PRODUCER_CV_OUT);
    final MadChannelBuffer cvOutBuf = channelBuffers[OscillatorMadDefinition.PRODUCER_CV_OUT];
    if (!audioOutConnected && !cvOutConnected) {
        // Do nothing, we have no output anyway
    } else {/*www  . j  ava 2 s . c o m*/
        float[] cvFreqFloats = null;
        if (cvFreqConnected) {
            cvFreqFloats = cvFreqBuf.floatBuffer;
        }

        // Need one of the buffers to render into
        final float[] genFloats = (audioOutConnected ? audioOutBuf.floatBuffer : cvOutBuf.floatBuffer);

        if (usedWaveShape != curWaveShape) {
            usedWaveShape = curWaveShape;
            oscillator = oscillatorTables.getOscillator(usedWaveShape);
        }

        if (cvFreqConnected) {
            oscillator.oscillate(cvFreqFloats, frameOffset, 0.0f, 1.0f, genFloats, frameOffset, numFrames,
                    sampleRate);
        } else {
            runtimeOscillationFrequency = (runtimeOscillationFrequency * curValueRatio)
                    + (oscillationFrequency * newValueRatio);
            oscillator.oscillate(runtimeOscillationFrequency, 0.0f, 1.0f, genFloats, frameOffset, numFrames,
                    sampleRate);
        }

        if (audioOutConnected && cvOutConnected) {
            // We rendered into audio out, copy it over into the cv out
            final float[] cvOutFloats = cvOutBuf.floatBuffer;
            System.arraycopy(genFloats, frameOffset, cvOutFloats, frameOffset, numFrames);
        }
    }
    if (CHECK_NAN) {
        final float[] audioOutFloats = audioOutBuf.floatBuffer;
        final float[] cvOutFloats = cvOutBuf.floatBuffer;

        for (int i = 0; i < numFrames; i++) {
            if (audioOutConnected) {
                if (audioOutFloats[frameOffset + i] == Float.NaN) {
                    log.error("Generated an audio NaN");
                }

                if (cvOutFloats[frameOffset + i] == Float.NaN) {
                    log.error("Generated a cv NaN");
                }
            }
        }
    }
    return RealtimeMethodReturnCodeEnum.SUCCESS;
}

From source file:pcgen.cdom.facet.analysis.ChallengeRatingFacet.java

private Float calcClassesForRaceCR(CharID id) {
    Float CR = new Float(0);
    int levelsKey = 0;
    int levelsNonKey = 0;
    int levelsConverted = 0;
    int threshold = 0;

    List<String> raceRoleList = raceFacet.get(id).getListFor(ListKey.MONSTER_ROLES);
    if (raceRoleList == null || raceRoleList.isEmpty()) {
        raceRoleList = SettingsHandler.getGame().getMonsterRoleDefaultList();
    }/*from w w  w.ja  v a  2 s  .  c o  m*/

    // Calculate and add the CR from the PC Classes
    for (PCClass pcClass : classFacet.getClassSet(id)) {
        Float levels = calcClassCR(id, pcClass);
        if (levels.isNaN()) {
            return Float.NaN;
        }

        List<String> classRoleList = pcClass.getListFor(ListKey.MONSTER_ROLES);
        if (classRoleList != null) {
            classRoleList.retainAll(raceRoleList);
            if (classRoleList.size() > 0) {
                levelsKey += (int) levels.floatValue();
            } else {
                levelsNonKey += (int) levels.floatValue();
            }
        } else {
            if (raceRoleList != null) {
                levelsNonKey += (int) levels.floatValue();
            } else {
                levelsKey += (int) levels.floatValue();
            }
        }

    }
    String sThreshold = SettingsHandler.getGame().getCRThreshold();
    if (sThreshold != null) {
        threshold = formulaResolvingFacet.resolve(id, FormulaFactory.getFormulaFor(sThreshold), "").intValue();
    }

    while (levelsNonKey > 1) {
        CR++;
        // TODO: maybe the divisor 2 should be be made configurable, 
        // or the whole calculation put into a formula
        levelsNonKey -= 2;
        levelsConverted += 2;
        if (levelsConverted >= threshold) {
            break;
        }
    }
    if (levelsConverted > 0) {
        CR += levelsNonKey;
    }
    CR += levelsKey;

    return CR;
}

From source file:com.jjoe64.graphview.series.LineGraphSeries.java

/**
 * plots the series//  w  w w  .jav a 2  s .  co m
 * draws the line and the background
 *
 * @param graphView graphview
 * @param canvas canvas
 * @param isSecondScale flag if it is the second scale
 */
@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
    resetDataPoints();

    // get data
    double maxX = graphView.getViewport().getMaxX(false);
    double minX = graphView.getViewport().getMinX(false);

    double maxY;
    double minY;
    if (isSecondScale) {
        maxY = graphView.getSecondScale().getMaxY(false);
        minY = graphView.getSecondScale().getMinY(false);
    } else {
        maxY = graphView.getViewport().getMaxY(false);
        minY = graphView.getViewport().getMinY(false);
    }

    Iterator<E> values = getValues(minX, maxX);

    // draw background
    double lastEndY = 0;
    double lastEndX = 0;

    // draw data
    mPaint.setStrokeWidth(mStyles.thickness);
    mPaint.setColor(getColor());
    mPaintBackground.setColor(mStyles.backgroundColor);

    Paint paint;
    if (mCustomPaint != null) {
        paint = mCustomPaint;
    } else {
        paint = mPaint;
    }

    mPath.reset();

    if (mStyles.drawBackground) {
        mPathBackground.reset();
    }

    double diffY = maxY - minY;
    double diffX = maxX - minX;

    float graphHeight = graphView.getGraphContentHeight();
    float graphWidth = graphView.getGraphContentWidth();
    float graphLeft = graphView.getGraphContentLeft();
    float graphTop = graphView.getGraphContentTop();

    lastEndY = 0;
    lastEndX = 0;

    // needed to end the path for background
    double lastUsedEndX = 0;
    double lastUsedEndY = 0;
    float firstX = -1;
    float firstY = -1;
    float lastRenderedX = Float.NaN;
    int i = 0;
    float lastAnimationReferenceX = graphLeft;

    boolean sameXSkip = false;
    float minYOnSameX = 0f;
    float maxYOnSameX = 0f;

    while (values.hasNext()) {
        E value = values.next();

        double valY = value.getY() - minY;
        double ratY = valY / diffY;
        double y = graphHeight * ratY;

        double valueX = value.getX();
        double valX = valueX - minX;
        double ratX = valX / diffX;
        double x = graphWidth * ratX;

        double orgX = x;
        double orgY = y;

        if (i > 0) {
            // overdraw
            boolean isOverdrawY = false;
            boolean isOverdrawEndPoint = false;
            boolean skipDraw = false;

            if (x > graphWidth) { // end right
                double b = ((graphWidth - lastEndX) * (y - lastEndY) / (x - lastEndX));
                y = lastEndY + b;
                x = graphWidth;
                isOverdrawEndPoint = true;
            }
            if (y < 0) { // end bottom
                // skip when previous and this point is out of bound
                if (lastEndY < 0) {
                    skipDraw = true;
                } else {
                    double b = ((0 - lastEndY) * (x - lastEndX) / (y - lastEndY));
                    x = lastEndX + b;
                }
                y = 0;
                isOverdrawY = isOverdrawEndPoint = true;
            }
            if (y > graphHeight) { // end top
                // skip when previous and this point is out of bound
                if (lastEndY > graphHeight) {
                    skipDraw = true;
                } else {
                    double b = ((graphHeight - lastEndY) * (x - lastEndX) / (y - lastEndY));
                    x = lastEndX + b;
                }
                y = graphHeight;
                isOverdrawY = isOverdrawEndPoint = true;
            }
            if (lastEndX < 0) { // start left
                double b = ((0 - x) * (y - lastEndY) / (lastEndX - x));
                lastEndY = y - b;
                lastEndX = 0;
            }

            // we need to save the X before it will be corrected when overdraw y
            float orgStartX = (float) lastEndX + (graphLeft + 1);

            if (lastEndY < 0) { // start bottom
                if (!skipDraw) {
                    double b = ((0 - y) * (x - lastEndX) / (lastEndY - y));
                    lastEndX = x - b;
                }
                lastEndY = 0;
                isOverdrawY = true;
            }
            if (lastEndY > graphHeight) { // start top
                // skip when previous and this point is out of bound
                if (!skipDraw) {
                    double b = ((graphHeight - y) * (x - lastEndX) / (lastEndY - y));
                    lastEndX = x - b;
                }
                lastEndY = graphHeight;
                isOverdrawY = true;
            }

            float startX = (float) lastEndX + (graphLeft + 1);
            float startY = (float) (graphTop - lastEndY) + graphHeight;
            float endX = (float) x + (graphLeft + 1);
            float endY = (float) (graphTop - y) + graphHeight;
            float startXAnimated = startX;
            float endXAnimated = endX;

            if (endX < startX) {
                // dont draw from right to left
                skipDraw = true;
            }

            // NaN can happen when previous and current value is out of y bounds
            if (!skipDraw && !Float.isNaN(startY) && !Float.isNaN(endY)) {
                // animation
                if (mAnimated) {
                    if ((Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) {
                        long currentTime = System.currentTimeMillis();
                        if (mAnimationStart == 0) {
                            // start animation
                            mAnimationStart = currentTime;
                            mAnimationStartFrameNo = 0;
                        } else {
                            // anti-lag: wait a few frames
                            if (mAnimationStartFrameNo < 15) {
                                // second time
                                mAnimationStart = currentTime;
                                mAnimationStartFrameNo++;
                            }
                        }
                        float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION;
                        float factor = mAnimationInterpolator.getInterpolation(timeFactor);
                        if (timeFactor <= 1.0) {
                            startXAnimated = (startX - lastAnimationReferenceX) * factor
                                    + lastAnimationReferenceX;
                            startXAnimated = Math.max(startXAnimated, lastAnimationReferenceX);
                            endXAnimated = (endX - lastAnimationReferenceX) * factor + lastAnimationReferenceX;
                            ViewCompat.postInvalidateOnAnimation(graphView);
                        } else {
                            // animation finished
                            mLastAnimatedValue = valueX;
                        }
                    } else {
                        lastAnimationReferenceX = endX;
                    }
                }

                // draw data point
                if (!isOverdrawEndPoint) {
                    if (mStyles.drawDataPoints) {
                        // draw first datapoint
                        Paint.Style prevStyle = paint.getStyle();
                        paint.setStyle(Paint.Style.FILL);
                        canvas.drawCircle(endXAnimated, endY, mStyles.dataPointsRadius, paint);
                        paint.setStyle(prevStyle);
                    }
                    registerDataPoint(endX, endY, value);
                }

                if (mDrawAsPath) {
                    mPath.moveTo(startXAnimated, startY);
                }
                // performance opt.
                if (Float.isNaN(lastRenderedX) || Math.abs(endX - lastRenderedX) > .3f) {
                    if (mDrawAsPath) {
                        mPath.lineTo(endXAnimated, endY);
                    } else {
                        // render vertical lines that were skipped
                        if (sameXSkip) {
                            sameXSkip = false;
                            renderLine(canvas,
                                    new float[] { lastRenderedX, minYOnSameX, lastRenderedX, maxYOnSameX },
                                    paint);
                        }
                        renderLine(canvas, new float[] { startXAnimated, startY, endXAnimated, endY }, paint);
                    }
                    lastRenderedX = endX;
                } else {
                    // rendering on same x position
                    // save min+max y position and render it as line
                    if (sameXSkip) {
                        minYOnSameX = Math.min(minYOnSameX, endY);
                        maxYOnSameX = Math.max(maxYOnSameX, endY);
                    } else {
                        // first
                        sameXSkip = true;
                        minYOnSameX = Math.min(startY, endY);
                        maxYOnSameX = Math.max(startY, endY);
                    }
                }

            }

            if (mStyles.drawBackground) {
                if (isOverdrawY) {
                    // start draw original x
                    if (firstX == -1) {
                        firstX = orgStartX;
                        firstY = startY;
                        mPathBackground.moveTo(orgStartX, startY);
                    }
                    // from original start to new start
                    mPathBackground.lineTo(startXAnimated, startY);
                }
                if (firstX == -1) {
                    firstX = startXAnimated;
                    firstY = startY;
                    mPathBackground.moveTo(startXAnimated, startY);
                }
                mPathBackground.lineTo(startXAnimated, startY);
                mPathBackground.lineTo(endXAnimated, endY);
            }

            lastUsedEndX = endXAnimated;
            lastUsedEndY = endY;
        } else if (mStyles.drawDataPoints) {
            //fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above)
            float first_X = (float) x + (graphLeft + 1);
            float first_Y = (float) (graphTop - y) + graphHeight;

            if (first_X >= graphLeft && first_Y <= (graphTop + graphHeight)) {
                if (mAnimated && (Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) {
                    long currentTime = System.currentTimeMillis();
                    if (mAnimationStart == 0) {
                        // start animation
                        mAnimationStart = currentTime;
                    }
                    float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION;
                    float factor = mAnimationInterpolator.getInterpolation(timeFactor);
                    if (timeFactor <= 1.0) {
                        first_X = (first_X - lastAnimationReferenceX) * factor + lastAnimationReferenceX;
                        ViewCompat.postInvalidateOnAnimation(graphView);
                    } else {
                        // animation finished
                        mLastAnimatedValue = valueX;
                    }
                }

                Paint.Style prevStyle = paint.getStyle();
                paint.setStyle(Paint.Style.FILL);
                canvas.drawCircle(first_X, first_Y, mStyles.dataPointsRadius, paint);
                paint.setStyle(prevStyle);
            }
        }
        lastEndY = orgY;
        lastEndX = orgX;
        i++;
    }

    if (mDrawAsPath) {
        // draw at the end
        canvas.drawPath(mPath, paint);
    }

    if (mStyles.drawBackground && firstX != -1) {
        // end / close path
        if (lastUsedEndY != graphHeight + graphTop) {
            // dont draw line to same point, otherwise the path is completely broken
            mPathBackground.lineTo((float) lastUsedEndX, graphHeight + graphTop);
        }
        mPathBackground.lineTo(firstX, graphHeight + graphTop);
        if (firstY != graphHeight + graphTop) {
            // dont draw line to same point, otherwise the path is completely broken
            mPathBackground.lineTo(firstX, firstY);
        }
        //mPathBackground.close();
        canvas.drawPath(mPathBackground, mPaintBackground);
    }
}

From source file:com.tmall.wireless.tangram3.util.Utils.java

public static Float getJsonFloatValue(JSONObject json, String key) {
    Float tmp = json.getFloat(key);
    if (tmp == null) {
        return Float.NaN;
    } else {//from  w  w  w.j av  a 2  s  . c om
        return tmp;
    }
}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial1.Algorithm.java

@Override
public Float predict(Model model, Query query) {
    RealVector itemVector = model.itemSimilarity.get(query.iid);
    RealVector userVector = model.userHistory.get(query.uid);
    if (itemVector == null) {
        // cold start item, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else if (userVector == null) {
        // new user, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else {//from w  w  w .  j av  a2  s . c  om
        //logger.info("(" + query.uid + "," + query.iid + ")");
        //logger.info(itemVector.toString());
        //logger.info(userVector.toString());
        double accum = 0.0;
        double accumSim = 0.0;
        for (int i = 0; i < itemVector.getDimension(); i++) {
            double weight = itemVector.getEntry(i);
            double rating = userVector.getEntry(i);
            if ((weight != 0) && (rating != 0)) {
                accum += weight * rating;
                accumSim += Math.abs(weight);
            }
        }

        if (accumSim == 0.0) {
            return Float.NaN;
        } else {
            return (float) (accum / accumSim);
        }
    }
}