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:Main.java

public static boolean isUndefined(float value) {
    return Float.isNaN(value);
}

From source file:com.frank.search.solr.core.query.Criteria.java

/**
 * Crates new {@link Criteria.Predicate} with trailing {@code ~} followed by
 * levensteinDistance//from w ww  .ja va  2 s  . c  o  m
 *
 * @param s
 * @param levenshteinDistance
 * @return
 */
public Criteria fuzzy(String s, float levenshteinDistance) {
    if (!Float.isNaN(levenshteinDistance) && (levenshteinDistance < 0 || levenshteinDistance > 1)) {
        throw new InvalidDataAccessApiUsageException(
                "Levenshtein Distance has to be within its bounds (0.0 - 1.0).");
    }
    predicates.add(new Predicate(OperationKey.FUZZY, new Object[] { s, Float.valueOf(levenshteinDistance) }));
    return this;
}

From source file:com.taobao.weex.ui.animation.TransformParser.java

public static Map<Property<View, Float>, Float> parseTransForm(@Nullable String rawTransform, final int width,
        final int height, final int viewportW) {
    if (!TextUtils.isEmpty(rawTransform)) {
        FunctionParser<Property<View, Float>, Float> parser = new FunctionParser<>(rawTransform,
                new FunctionParser.Mapper<Property<View, Float>, Float>() {
                    @Override/*from  w w w .ja  va2 s.  com*/
                    public Map<Property<View, Float>, Float> map(String functionName, List<String> raw) {
                        if (raw != null && !raw.isEmpty()) {
                            if (wxToAndroidMap.containsKey(functionName)) {
                                return convertParam(width, height, viewportW, wxToAndroidMap.get(functionName),
                                        raw);
                            }
                        }
                        return new HashMap<>();
                    }

                    private Map<Property<View, Float>, Float> convertParam(int width, int height, int viewportW,
                            @NonNull List<Property<View, Float>> propertyList, @NonNull List<String> rawValue) {

                        Map<Property<View, Float>, Float> result = WXDataStructureUtil
                                .newHashMapWithExpectedSize(propertyList.size());
                        List<Float> convertedList = new ArrayList<>(propertyList.size());
                        if (propertyList.contains(View.ROTATION) || propertyList.contains(View.ROTATION_X)
                                || propertyList.contains(View.ROTATION_Y)) {
                            convertedList.addAll(parseRotationZ(rawValue));
                        } else if (propertyList.contains(View.TRANSLATION_X)
                                || propertyList.contains(View.TRANSLATION_Y)) {
                            convertedList
                                    .addAll(parseTranslation(propertyList, width, height, rawValue, viewportW));
                        } else if (propertyList.contains(View.SCALE_X) || propertyList.contains(View.SCALE_Y)) {
                            convertedList.addAll(parseScale(propertyList.size(), rawValue));
                        } else if (propertyList.contains(CameraDistanceProperty.getInstance())) {
                            convertedList.add(parseCameraDistance(rawValue));
                        }
                        if (propertyList.size() == convertedList.size()) {
                            for (int i = 0; i < propertyList.size(); i++) {
                                result.put(propertyList.get(i), convertedList.get(i));
                            }
                        }
                        return result;
                    }

                    private List<Float> parseScale(int size, @NonNull List<String> rawValue) {
                        List<Float> convertedList = new ArrayList<>(rawValue.size() * 2);
                        List<Float> rawFloat = new ArrayList<>(rawValue.size());
                        for (String item : rawValue) {
                            rawFloat.add(WXUtils.fastGetFloat(item));
                        }
                        convertedList.addAll(rawFloat);
                        if (size != 1 && rawValue.size() == 1) {
                            convertedList.addAll(rawFloat);
                        }
                        return convertedList;
                    }

                    private @NonNull List<Float> parseRotationZ(@NonNull List<String> rawValue) {
                        List<Float> convertedList = new ArrayList<>(1);
                        int suffix;
                        for (String raw : rawValue) {
                            if ((suffix = raw.lastIndexOf(DEG)) != -1) {
                                convertedList.add(WXUtils.fastGetFloat(raw.substring(0, suffix)));
                            } else {
                                convertedList.add((float) Math.toDegrees(Double.parseDouble(raw)));
                            }
                        }
                        return convertedList;
                    }

                    /**
                     * As "translate(50%, 25%)" or "translate(25px, 30px)" both are valid,
                     * parsing translate is complicated than other method.
                     * Add your waste time here if you try to optimize this method like {@link #parseScale(int, List)}
                     * Time: 0.5h
                     */
                    private List<Float> parseTranslation(List<Property<View, Float>> propertyList, int width,
                            int height, @NonNull List<String> rawValue, int viewportW) {
                        List<Float> convertedList = new ArrayList<>(2);
                        String first = rawValue.get(0);
                        if (propertyList.size() == 1) {
                            parseSingleTranslation(propertyList, width, height, convertedList, first,
                                    viewportW);
                        } else {
                            parseDoubleTranslation(width, height, rawValue, convertedList, first, viewportW);
                        }
                        return convertedList;
                    }

                    private void parseSingleTranslation(List<Property<View, Float>> propertyList, int width,
                            int height, List<Float> convertedList, String first, int viewportW) {
                        if (propertyList.contains(View.TRANSLATION_X)) {
                            convertedList.add(parsePercentOrPx(first, width, viewportW));
                        } else if (propertyList.contains(View.TRANSLATION_Y)) {
                            convertedList.add(parsePercentOrPx(first, height, viewportW));
                        }
                    }

                    private void parseDoubleTranslation(int width, int height, @NonNull List<String> rawValue,
                            List<Float> convertedList, String first, int viewportW) {
                        String second;
                        if (rawValue.size() == 1) {
                            second = first;
                        } else {
                            second = rawValue.get(1);
                        }
                        convertedList.add(parsePercentOrPx(first, width, viewportW));
                        convertedList.add(parsePercentOrPx(second, height, viewportW));
                    }

                    private Float parseCameraDistance(List<String> rawValue) {
                        float ret = Float.MAX_VALUE;
                        if (rawValue.size() == 1) {
                            float value = WXViewUtils.getRealPxByWidth(WXUtils.getFloat(rawValue.get(0)),
                                    viewportW);
                            float scale = WXEnvironment.getApplication().getResources()
                                    .getDisplayMetrics().density;
                            if (!Float.isNaN(value) && value > 0) {
                                ret = value * scale;
                            }
                        }
                        return ret;
                    }
                });
        return parser.parse();
    }
    return new LinkedHashMap<>();
}

From source file:org.apache.tajo.worker.TaskAttemptContext.java

public void setFetcherProgress(float fetcherProgress) {
    if (Float.isNaN(fetcherProgress) || Float.isInfinite(fetcherProgress)) {
        fetcherProgress = 0.0f;/*from w ww.j a v  a 2  s. co m*/
    }
    float previousProgress = this.fetcherProgress;
    this.fetcherProgress = fetcherProgress;
    this.progressChanged = previousProgress != fetcherProgress;
}

From source file:com.hightail.metrics.rest.NewRelicHTTPv1Reporter.java

private void doGauge(String name, Gauge gauge) {
    Object gaugeValue = gauge.getValue();
    Map<String, Object> componentMetrics = new HashMap<String, Object>();

    if (gaugeValue instanceof Number) {
        float n = ((Number) gaugeValue).floatValue();
        if (!Float.isNaN(n) && !Float.isInfinite(n)) {
            componentMetrics.put(prefix(name) + "/gauge", n);
            postToNewRelic(componentMetrics);
        }//from   w w w.ja  va  2 s .c om
    }
}

From source file:com.facebook.litho.DebugComponent.java

/**
 * @return Key-value mapping of this components layout styles.
 *///  w  w w .  j ava  2s.c om
public Map<String, Object> getStyles() {
    final InternalNode node = mNode.get();
    if (node == null || !isLayoutNode()) {
        return Collections.EMPTY_MAP;
    }

    final Map<String, Object> styles = new ArrayMap<>();
    final YogaNode yogaNode = node.mYogaNode;
    final YogaNode defaults = ComponentsPools.acquireYogaNode(node.getContext());
    final ComponentContext context = node.getContext();

    styles.put("background", getReferenceColor(context, node.getBackground()));
    styles.put("foreground", getDrawableColor(node.getForeground()));

    styles.put("direction", yogaNode.getStyleDirection());
    styles.put("flex-direction", yogaNode.getFlexDirection());
    styles.put("justify-content", yogaNode.getJustifyContent());
    styles.put("align-items", yogaNode.getAlignItems());
    styles.put("align-self", yogaNode.getAlignSelf());
    styles.put("align-content", yogaNode.getAlignContent());
    styles.put("position", yogaNode.getPositionType());
    styles.put("flex-grow", yogaNode.getFlexGrow());
    styles.put("flex-shrink", yogaNode.getFlexShrink());
    styles.put("flex-basis", yogaNode.getFlexBasis());

    styles.put("width", yogaNode.getWidth());
    styles.put("min-width", yogaNode.getMinWidth());
    styles.put("max-width", yogaNode.getMaxWidth());
    styles.put("height", yogaNode.getHeight());
    styles.put("min-height", yogaNode.getMinHeight());
    styles.put("max-height", yogaNode.getMaxHeight());

    for (YogaEdge edge : edges) {
        final String key = "margin-" + edge.toString().toLowerCase();
        styles.put(key, yogaNode.getMargin(edge));
    }

    for (YogaEdge edge : edges) {
        final String key = "padding-" + edge.toString().toLowerCase();
        styles.put(key, yogaNode.getPadding(edge));
    }

    for (YogaEdge edge : edges) {
        final String key = "position-" + edge.toString().toLowerCase();
        styles.put(key, yogaNode.getPosition(edge));
    }

    for (YogaEdge edge : edges) {
        final String key = "border-" + edge.toString().toLowerCase();
        final float border = yogaNode.getBorder(edge);
        styles.put(key, Float.isNaN(border) ? 0 : border);
    }

    ComponentsPools.release(defaults);
    return styles;
}

From source file:uk.ac.babraham.SeqMonk.Filters.GeneSetFilter.GeneSetIntensityDifferenceFilter.java

protected void generateProbeList() {

    try {/*  www.  j  av a2 s  .  c o  m*/

        /* get selected probelists  */
        /*   if(optionsPanel.probeListRadioButton.isSelected()){
              ProbeList [] probeLists = ProbeListSelectorDialog.selectProbeLists();
              if (probeLists == null || probeLists.length == 0){
                         
                 JOptionPane.showMessageDialog(SeqMonkApplication.getInstance(), "No probelists were selected.",  "No probe lists selected", JOptionPane.INFORMATION_MESSAGE);
                 progressCancelled();
                 return;
              }         
              selectedProbeLists = probeLists;            
           }
                   
           else if(optionsPanel.geneSetsFileRadioButton.isSelected()){
              do stuff
                      
           }
           */

        applyMultipleTestingCorrection = optionsPanel.multipleTestingBox.isSelected();
        //calculateLinearRegression = optionsPanel.calculateLinearRegressionBox.isSelected();
        calculateCustomRegression = optionsPanel.calculateCustomRegressionBox.isSelected();

        if (calculateCustomRegression == false) {
            customRegressionValues = null;
        }

        if (calculateLinearRegression) {
            simpleRegression = new SimpleRegression();
        }

        Probe[] allProbes = startingList.getAllProbes();

        // We're not allowing multiple comparisons - this is a bit of a messy workaround so it's compatible with other methods.
        fromStore = fromStores[0];
        toStore = toStores[0];

        ArrayList<Probe> probeArrayList = new ArrayList<Probe>();

        int NaNcount = 0;
        // remove the invalid probes - the ones without a value
        for (int i = 0; i < allProbes.length; i++) {
            if ((Float.isNaN(fromStore.getValueForProbe(allProbes[i])))
                    || (Float.isNaN(toStore.getValueForProbe(allProbes[i])))) {
                NaNcount++;
            } else {
                probeArrayList.add(allProbes[i]);
            }
        }

        System.err.println("Found " + NaNcount + " probes that were invalid.");

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

        if (calculateCustomRegression == true) {
            customRegressionValues = new float[2][probes.length];
        }

        // We'll pull the number of probes to sample from the preferences if they've changed it
        Integer updatedProbesPerSet = optionsPanel.probesPerSet();
        if (updatedProbesPerSet != null)
            probesPerSet = updatedProbesPerSet;

        // we want a set of z-scores using the local distribution.         
        probeZScoreLookupTable = new Hashtable<Probe, Double>();

        // Put something in the progress whilst we're ordering the probe values to make the comparison.
        progressUpdated("Generating background model", 0, 1);

        Comparator<Integer> comp = new AverageIntensityComparator(fromStore, toStore, probes);

        // We need to generate a set of probe indices that can be ordered by their average intensity         
        Integer[] indices = new Integer[probes.length];

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

            indices[i] = i;

            /* add the data to the linear regression object */
            if (calculateLinearRegression) {
                simpleRegression.addData((double) fromStore.getValueForProbe(probes[i]),
                        (double) toStore.getValueForProbe(probes[i]));
            }
        }

        if (calculateLinearRegression) {

            System.out.println("intercept = " + simpleRegression.getIntercept() + ", slope = "
                    + simpleRegression.getSlope());
        }

        Arrays.sort(indices, comp);

        /* This holds the indices to get the deduplicated probe from the original list of probes */
        deduplicatedIndices = new Integer[probes.length];

        /* The number of probes with different values */
        int dedupProbeCounter = 0;

        // the probes deduplicated by value
        ArrayList<Probe> deduplicatedProbes = new ArrayList<Probe>();

        // populate the first one so that we have something to compare to in the loop         
        deduplicatedIndices[0] = 0;
        deduplicatedProbes.add(probes[indices[0]]);

        progressUpdated("Made 0 of 1 comparisons", 0, 1);

        for (int i = 1; i < indices.length; i++) {

            /* indices have been sorted, now we need to check whether adjacent pair values are identical */
            if ((fromStore.getValueForProbe(probes[indices[i]]) == fromStore
                    .getValueForProbe(probes[indices[i - 1]]))
                    && (toStore.getValueForProbe(probes[indices[i]]) == toStore
                            .getValueForProbe(probes[indices[i - 1]]))) {

                /* If they are identical, do not add the probe to the deduplicatedProbes object, but have a reference for it so we can look up which deduplicated probe and 
                 * therefore which distribution slice to use for the duplicated probe. */
                deduplicatedIndices[i] = dedupProbeCounter;

            } else {

                deduplicatedProbes.add(probes[indices[i]]);
                dedupProbeCounter++;
                deduplicatedIndices[i] = dedupProbeCounter;
            }
        }

        Probe[] dedupProbes = deduplicatedProbes.toArray(new Probe[0]);

        // make sure we're not trying to use more probes than we've got in the analysis
        if (probesPerSet > dedupProbes.length) {
            probesPerSet = dedupProbes.length;
        }

        System.out.println("total number of probe values = " + probes.length);
        System.out.println("number of deduplicated probe values = " + dedupProbes.length);
        System.out.println("probesPerSet = " + probesPerSet);

        // I want this to contain all the differences, then from that I'm going to get the z-scores.
        double[] currentDiffSet = new double[probesPerSet];

        for (int i = 0; i < indices.length; i++) {
            if (cancel) {
                cancel = false;
                progressCancelled();
                return;
            }

            if (i % 1000 == 0) {

                int progress = (i * 100) / indices.length;

                //progress += 100*comparisonIndex;               
                progressUpdated("Made 0 out of 1 comparisons", progress, 100);
            }

            //            boolean print;
            //            if(probes[indices[i]].name().startsWith("Apoa4")){
            //               print = true;
            //            }
            //            else{
            //               print = false;
            //            }

            /**
             * There are +1s in here because we skip over j when j == startingIndex.
             * 
             */
            // We need to make up the set of differences to represent this probe
            int startingIndex = deduplicatedIndices[i] - (probesPerSet / 2);
            if (startingIndex < 0)
                startingIndex = 0;
            if (startingIndex + (probesPerSet + 1) >= dedupProbes.length)
                startingIndex = dedupProbes.length - (probesPerSet + 1);

            /*System.err.println("i = " + i);
            System.err.println("deduplicatedIndices[i] = " + deduplicatedIndices[i]);
            System.err.println("starting index = " + startingIndex);
            System.err.println("starting index + probesPerSet = " + (startingIndex+probesPerSet));
            //System.out.println("currentDiffsetLength = " + currentDiffSet.length);
            */
            try {
                for (int j = startingIndex; j < startingIndex + (probesPerSet + 1); j++) {
                    //for (int j=startingIndex;j<startingIndex+(probesPerSet);j++) {   

                    if (j == startingIndex) {

                        continue; // Don't include the point being tested in the background model
                    }

                    double diff;

                    if (calculateLinearRegression == true) {

                        if (j > dedupProbes.length) {

                            System.err.println(" j is too big, it's " + j + " and dedupProbes.length = "
                                    + dedupProbes.length + ", starting index = " + startingIndex);
                        }
                        double x = fromStore.getValueForProbe(dedupProbes[j]);
                        double expectedY = (simpleRegression.getSlope() * x) + simpleRegression.getIntercept();
                        diff = toStore.getValueForProbe(dedupProbes[j]) - expectedY;

                    }

                    else {

                        diff = toStore.getValueForProbe(dedupProbes[j])
                                - fromStore.getValueForProbe(dedupProbes[j]);
                    }

                    if (j < startingIndex) {

                        currentDiffSet[j - startingIndex] = diff;

                    } else {

                        currentDiffSet[(j - startingIndex) - 1] = diff;

                    }
                }

                if (calculateCustomRegression == true) {
                    // the average/ kind of centre line
                    float z = ((fromStore.getValueForProbe(probes[indices[i]])
                            + toStore.getValueForProbe(probes[indices[i]])) / 2);
                    customRegressionValues[0][indices[i]] = z - ((float) SimpleStats.mean(currentDiffSet) / 2);
                    customRegressionValues[1][indices[i]] = z + ((float) SimpleStats.mean(currentDiffSet) / 2);

                    //if((i < 10) || (i % 1000 == 0)){
                    /*if((probes[indices[i]].name().startsWith("Nr2f6")) || probes[indices[i]].name().startsWith("Per1")){
                       System.err.println("");
                       System.err.println("For " + probes[indices[i]].name() + ", toValue = " + toStore.getValueForProbe(probes[indices[i]]) 
                             + ", from value = " + fromStore.getValueForProbe(probes[indices[i]])  + ", z = " + z + ", mean " + SimpleStats.mean(currentDiffSet) + ", new x = " + customRegressionValues[0][indices[i]] +
                       ", new y = " + customRegressionValues[1][indices[i]]  + ", i = " + i);
                    }
                    *///customRegressionValues[indices[i]] = (float)SimpleStats.median(currentSetX);
                }

                double mean = 0;

                // Get the difference for this point
                double diff;

                if (calculateLinearRegression == true) {

                    double x = fromStore.getValueForProbe(probes[indices[i]]);
                    double expectedY = (simpleRegression.getSlope() * x) + simpleRegression.getIntercept();
                    diff = toStore.getValueForProbe(probes[indices[i]]) - expectedY;

                }

                else if (calculateCustomRegression == true) {

                    // y-x
                    diff = toStore.getValueForProbe(probes[indices[i]])
                            - fromStore.getValueForProbe(probes[indices[i]]);

                    mean = SimpleStats.mean(currentDiffSet);

                    /*   if((probes[indices[i]].name().startsWith("Nr2f6")) || probes[indices[i]].name().startsWith("Per1")){
                          print = true;
                          System.err.println();
                          System.err.println("toStore = " + toStore.name());
                          System.err.println(probes[indices[i]].name()  + ", toStore = " + toStore.getValueForProbe(probes[indices[i]]) + ", fromStore = " + fromStore.getValueForProbe(probes[indices[i]]) 
                          + ", customRegressionValues[0] = " + customRegressionValues[0][indices[i]] + ", customRegressionValues[1] = " + customRegressionValues[1][indices[i]] + ", diff = " + diff + ", mean = " + mean);
                          System.err.println();
                       }
                       else{
                          print = false;
                       }                  
                    */
                }

                else {
                    diff = toStore.getValueForProbe(probes[indices[i]])
                            - fromStore.getValueForProbe(probes[indices[i]]);
                }

                double stdev = SimpleStats.stdev(currentDiffSet, mean);
                // if there are no reads in the probe for either of the datasets, should we set the zscore to 0??                   
                double zScore = (diff - mean) / stdev;

                // modified z score
                // median absolute deviation
                /*      double[] madArray = new double[currentDiffSet.length];
                      double median = SimpleStats.median(currentDiffSet);               
                              
                      for(int d=0; d<currentDiffSet.length; d++){
                                 
                         madArray[d] = Math.abs(currentDiffSet[d] - median);
                                 
                      }
                              
                      double mad = SimpleStats.median(madArray);
                                 
                      zScore = (0.6745 * (diff - median))/mad;
                   }
                */ probeZScoreLookupTable.put(probes[indices[i]], zScore);
            } catch (SeqMonkException sme) {
                progressExceptionReceived(sme);
                return;
            }

        }

        // make this an array list as we're kicking out the mapped gene sets that have zscores with variance of 0.
        ArrayList<MappedGeneSetTTestValue> pValueArrayList = new ArrayList<MappedGeneSetTTestValue>();

        MappedGeneSet[] mappedGeneSets = null;

        /* if we're using the gene set from a file, map the gene sets to the probes */
        if (optionsPanel.geneSetsFileRadioButton.isSelected()) {

            GeneSetCollectionParser geneSetCollectionParser = new GeneSetCollectionParser(minGenesInSet,
                    maxGenesInSet);
            GeneSetCollection geneSetCollection = geneSetCollectionParser
                    .parseGeneSetInformation(validGeneSetFilepath);
            MappedGeneSet[] allMappedGeneSets = geneSetCollection.getMappedGeneSets(probes);

            if (allMappedGeneSets == null) {
                throw new SeqMonkException(
                        "No sets of genes could be matched to probes.\nTo use gene sets from a file, probe names must contain the gene name.\nTry defining new probes over genes or use existing probes lists instead of a gene set file.");
                //JOptionPane.showMessageDialog(SeqMonkApplication.getInstance(), "No sets of genes could be matched to probes.\nTo use gene sets from a file, probe names must contain the gene name.\nTry defining new probes over genes or use existing probes lists instead of a gene set file.", "No gene sets matched", JOptionPane.ERROR_MESSAGE);
            }

            else {

                ArrayList<MappedGeneSet> mgsArrayList = new ArrayList<MappedGeneSet>();

                /* get rid of those that have fewer probes in the set than minGenesInSet. We shouldn't exceed maxGenesInSet unless probes have been made over something other than genes */
                for (int i = 0; i < allMappedGeneSets.length; i++) {
                    if (allMappedGeneSets[i].getProbes().length >= minGenesInSet) {
                        mgsArrayList.add(allMappedGeneSets[i]);
                    }
                }
                mappedGeneSets = mgsArrayList.toArray(new MappedGeneSet[0]);
            }
        }
        /* or if we're using existing probelists, create mappedGeneSets from them */
        else if (optionsPanel.probeListRadioButton.isSelected() && selectedProbeLists != null) {
            mappedGeneSets = new MappedGeneSet[selectedProbeLists.length];

            for (int i = 0; i < selectedProbeLists.length; i++) {
                mappedGeneSets[i] = new MappedGeneSet(selectedProbeLists[i]);
            }
        } else {
            throw new SeqMonkException(
                    "Haven't got any genesets to use, shouldn't have got here without having any selected.");
        }

        if (mappedGeneSets == null || mappedGeneSets.length == 0) {
            throw new SeqMonkException(
                    "Couldn't map gene sets to the probes, try again with a different probe set");
        }

        else {
            System.err.println("there are " + mappedGeneSets.length + " mappedGeneSets");
            System.err.println("size of zScore lookup table = " + probeZScoreLookupTable.size());
        }

        /* we need to go through the mapped gene set and get all the values for the matched probes */
        for (int i = 0; i < mappedGeneSets.length; i++) {

            Probe[] geneSetProbes = mappedGeneSets[i].getProbes();

            // to contain all the z-scores for the gene set
            double[] geneSetZscores = new double[geneSetProbes.length];

            // Find the z-scores for each of the probes in the mappedGeneSet            
            for (int gsp = 0; gsp < geneSetProbes.length; gsp++) {

                if (probeZScoreLookupTable.containsKey(geneSetProbes[gsp])) {

                    geneSetZscores[gsp] = probeZScoreLookupTable.get(geneSetProbes[gsp]);
                }
            }

            // this is just temporary to check the stats - there's some duplication with this.
            mappedGeneSets[i].zScores = geneSetZscores;

            if (geneSetZscores.length > 1) { // but the number of probes in the mappedGeneSet should always be > 1 anyway as the mappedGeneSet shouldn't be created if there are < 2 matched probes.               

                double pVal = TTest.calculatePValue(geneSetZscores, 0);

                mappedGeneSets[i].meanZScore = SimpleStats.mean(geneSetZscores);
                //mappedGeneSets[i].meanZScore = SimpleStats.median(geneSetZscores); 

                // check the variance - we don't want variances of 0.
                double stdev = SimpleStats.stdev(geneSetZscores);
                if ((stdev * stdev) < 0.00000000000001) {
                    continue;
                }
                // if all the differences between the datasets are 0 then just get rid of them
                else if (Double.isNaN(pVal)) {
                    continue;
                } else {
                    pValueArrayList.add(new MappedGeneSetTTestValue(mappedGeneSets[i], pVal));
                }
            } else {
                System.err.println(
                        "Fell through the net somewhere, why does the set of zscores contain fewer than 2 values?");
                continue;

            }
        }

        MappedGeneSetTTestValue[] filterResultpValues = pValueArrayList.toArray(new MappedGeneSetTTestValue[0]);

        ArrayList<MappedGeneSetTTestValue> filteredPValueArrayList = new ArrayList<MappedGeneSetTTestValue>();

        // Now we've got all the p values they need to be corrected.    
        if (applyMultipleTestingCorrection) {
            BenjHochFDR.calculateQValues(filterResultpValues);
        }
        System.err.println(filterResultpValues.length + " p-values calculated, multtest = "
                + applyMultipleTestingCorrection + ", pval limit = " + pValueLimit);
        for (int i = 0; i < filterResultpValues.length; i++) {

            double pOrQvalue;

            if (applyMultipleTestingCorrection) {

                pOrQvalue = filterResultpValues[i].q;
            } else {

                pOrQvalue = filterResultpValues[i].p;
            }

            if (i < 50 || filterResultpValues[i].mappedGeneSet.name().startsWith("MATURE B CELL")) {
                System.err.println("For " + filterResultpValues[i].mappedGeneSet.name() + ", pValue = "
                        + filterResultpValues[i].p);
                System.err.println("For " + filterResultpValues[i].mappedGeneSet.name() + ", qValue = "
                        + filterResultpValues[i].q);
            }

            if ((pOrQvalue < pValueLimit)
                    && (Math.abs(filterResultpValues[i].mappedGeneSet.meanZScore) > zScoreThreshold)) {

                filteredPValueArrayList.add(filterResultpValues[i]);
            }
        }

        filterResultpValues = filteredPValueArrayList.toArray(new MappedGeneSetTTestValue[0]);

        if (filterResultpValues.length == 0) {
            JOptionPane.showMessageDialog(SeqMonkApplication.getInstance(),
                    "No sets of genes were identified using the selected parameters, \ntry changing the gene sets or relaxing the p-value/z-score thresholds.",
                    "No gene sets identified", JOptionPane.INFORMATION_MESSAGE);

        }

        else {
            geneSetDisplay = new GeneSetDisplay(dataCollection, listDescription(), fromStore, toStore, probes,
                    probeZScoreLookupTable, filterResultpValues, startingList, customRegressionValues,
                    simpleRegression);
            geneSetDisplay.addWindowListener(this);
        }
        // We don't want to save the probe list here, we're bringing up the intermediate display from which probe lists can be saved. 
        progressCancelled();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:net.myrrix.online.ServerRecommender.java

@Override
public void ingest(Reader reader) throws TasteException {
    // See also InputFilesReader
    BufferedReader buffered = IOUtils.buffer(reader);
    try {/*  w  w w  . ja v a  2 s.  c om*/

        int lines = 0;
        int badLines = 0;
        String line;
        while ((line = buffered.readLine()) != null) {

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

            lines++;

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

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

            long userID = Long.MIN_VALUE;
            String itemTag = null;
            long itemID = Long.MIN_VALUE;
            String userTag = null;
            float value;
            try {

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

                String itemIDString = it.next();
                if (itemIDString.startsWith("\"")) {
                    userTag = 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;
            }

            boolean remove = Float.isNaN(value);

            if (itemTag != null) {

                if (userTag != null) {
                    log.warn("Two tags not allowed: '{}'", line);
                    badLines++;
                    continue;
                }

                if (!remove) {
                    setItemTag(itemTag, itemID, value, true);
                }
                // else ignore? no support for remove tag yet

            } else if (userTag != null) {

                if (!remove) {
                    setUserTag(userID, userTag, value, true);
                }
                // else ignore? no support for remove tag yet

            } else {

                if (remove) {
                    removePreference(userID, itemID, true);
                } else {
                    setPreference(userID, itemID, value, true);
                }

            }

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

    } catch (IOException ioe) {
        throw new TasteException(ioe);
    }
}

From source file:p5e610.graphview.series.LineGraphSeries.java

/**
 * plots the series/*www.  j  av  a  2 s.c om*/
 * 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 maxY = Double.NEGATIVE_INFINITY;
    double maxX = Double.NEGATIVE_INFINITY;
    double minY = Double.POSITIVE_INFINITY;
    double minX = Double.POSITIVE_INFINITY;

    boolean minXSet = graphView.getViewport().getMinX(false) != null;
    boolean maxXSet = graphView.getViewport().getMaxX(false) != null;
    boolean minYSet = graphView.getViewport().getMinY(false) != null;
    boolean maxYSet = graphView.getViewport().getMaxY(false) != null;

    if (minXSet)
        minX = graphView.getViewport().getMinX(false);
    if (maxXSet) {
        maxX = graphView.getViewport().getMaxX(false);
    }
    if (minYSet) {
        minY = graphView.getViewport().getMinY(false);
    }
    if (maxYSet) {
        maxY = graphView.getViewport().getMaxY(false);
    }

    for (E val : mData) {
        double currX = val.getX();
        double currY = val.getY();

        if (currX > maxX && !maxXSet)
            maxX = currX;
        if (currY > maxY && !maxYSet)
            maxY = currY;
        if (currX < minX && !minXSet)
            minX = currX;
        if (currY < minY && !minYSet)
            minY = currY;
    }

    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);
    }
}