Example usage for java.lang Double isNaN

List of usage examples for java.lang Double isNaN

Introduction

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

Prototype

public boolean isNaN() 

Source Link

Document

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Usage

From source file:org.openscience.cdk.applications.taverna.qsar.GetMolecularWeightDistributionFromQSARVectorActivity.java

@Override
@SuppressWarnings("unchecked")
public void work() throws Exception {
    // Get input//ww  w .j a v  a  2 s.  c  om
    Map<UUID, Map<String, Object>> vectorMap;
    try {
        vectorMap = (Map<UUID, Map<String, Object>>) this.getInputAsObject(this.INPUT_PORTS[0]);
    } catch (Exception e) {
        ErrorLogger.getInstance().writeError(CDKTavernaException.WRONG_INPUT_PORT_TYPE, this.getActivityName(),
                e);
        throw new CDKTavernaException(this.getConfiguration().getActivityName(), e.getMessage());
    }
    File targetFile = this.getInputAsFile(this.INPUT_PORTS[1]);
    String directory = Tools.getDirectory(targetFile);
    String name = Tools.getFileName(targetFile);
    // Do work
    ChartTool chartTool = new ChartTool();
    ArrayList<String> molIdSWeightCSV = new ArrayList<String>();
    ArrayList<String> weightDistributionCSV = new ArrayList<String>();
    try {
        QSARVectorUtility util = new QSARVectorUtility();
        List<UUID> uuids = util.getUUIDs(vectorMap);
        LinkedList<Double> weigths = new LinkedList<Double>();
        int maxWeight = 0;
        molIdSWeightCSV.add("ID;Molecular Weight (g/mol);");
        for (int i = 0; i < uuids.size(); i++) {
            UUID uuid = uuids.get(i);
            Map<String, Object> values = vectorMap.get(uuid);
            Double weight = (Double) values.get("weight");
            if (weight.isInfinite() || weight.isNaN()) {
                continue;
            }
            weigths.add(weight);
            if (weight.intValue() > maxWeight) {
                maxWeight = weight.intValue();
            }
            molIdSWeightCSV.add(uuid.toString() + ";" + String.format("%.2f", weight) + ";");
        }
        int[] weightDistribution = new int[maxWeight + 1];
        for (Double weight : weigths) {
            int value = weight.intValue();
            weightDistribution[value]++;
        }
        weightDistributionCSV.add("Molecular Weight (g/mol);Number Of Molecules;");
        for (int i = 1; i < weightDistribution.length; i++) {
            weightDistributionCSV.add(i + ";" + weightDistribution[i] + ";");
        }
        // Create chart
        XYSeries series = new XYSeries("Weight");
        for (int i = 0; i < weightDistribution.length; i++) {
            series.add(i, weightDistribution[i]);
        }
        XYSeriesCollection dataset = new XYSeriesCollection(series);
        JFreeChart chart = chartTool.createXYBarChart("Weight Distribution", "Weight (g/mol)",
                "Number of Compounds", dataset, true, false);
        File file = FileNameGenerator.getNewFile(directory, ".pdf", name);
        chartTool.writeChartAsPDF(file, Collections.singletonList((Object) chart));
    } catch (Exception e) {
        ErrorLogger.getInstance().writeError("Error during extraction of molecular weight from QSAR vector!",
                this.getActivityName(), e);
        throw new CDKTavernaException(this.getConfiguration().getActivityName(), e.getMessage());
    }
    // Set output
    this.setOutputAsStringList(weightDistributionCSV, this.OUTPUT_PORTS[0]);
    this.setOutputAsStringList(molIdSWeightCSV, this.OUTPUT_PORTS[1]);
}

From source file:com.espertech.esper.regression.resultset.TestGroupByMedianAndDeviation.java

public void testSumOneView() {
    String viewExpr = "select irstream symbol," + "median(all price) as myMedian,"
            + "median(distinct price) as myDistMedian," + "stddev(all price) as myStdev,"
            + "avedev(all price) as myAvedev " + "from " + SupportMarketDataBean.class.getName()
            + ".win:length(5) " + "where symbol='DELL' or symbol='IBM' or symbol='GE' " + "group by symbol";

    EPStatement selectTestView = epService.getEPAdministrator().createEPL(viewExpr);
    selectTestView.addListener(testListener);

    runAssertion(selectTestView);//  w  ww.  j  a v  a 2  s.c  o  m

    // Test NaN sensitivity
    selectTestView.destroy();
    selectTestView = epService.getEPAdministrator().createEPL(
            "select stddev(price) as val from " + SupportMarketDataBean.class.getName() + ".win:length(3)");
    selectTestView.addListener(testListener);

    sendEvent("A", Double.NaN);
    sendEvent("B", Double.NaN);
    sendEvent("C", Double.NaN);
    sendEvent("D", 1d);
    sendEvent("E", 2d);
    testListener.reset();
    sendEvent("F", 3d);
    Double result = (Double) testListener.assertOneGetNewAndReset().get("val");
    assertTrue(result.isNaN());
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.DRNormalizedController.java

/**
 * Create the table model for the top panel table. Table contains
 * log-transformed concentration and normalized slopes per condition
 *
 * @param dataToFit/*from w w w.  j  a  v a  2  s . c  o m*/
 * @return the model
 */
protected NonEditableTableModel createTableModel(List<DoseResponsePair> dataToFit) {
    int maxReplicates = 0;
    for (DoseResponsePair entry : dataToFit) {
        int replicates = entry.getResponses().size();
        if (replicates > maxReplicates) {
            maxReplicates = replicates;
        }
    }
    Object[][] data = new Object[dataToFit.size()][maxReplicates + 1];

    int rowIndex = 0;
    for (DoseResponsePair entry : dataToFit) {
        //log concentration is put on 1st column
        data[rowIndex][0] = AnalysisUtils.roundThreeDecimals(entry.getDose());

        for (int columnIndex = 1; columnIndex < entry.getResponses().size() + 1; columnIndex++) {
            try {
                Double slope = entry.getResponses().get(columnIndex - 1);
                if (slope != null && !slope.isNaN()) {
                    // round to three decimals slopes and coefficients
                    slope = AnalysisUtils.roundThreeDecimals(entry.getResponses().get(columnIndex - 1));
                    // show in table slope + (coefficient)
                    data[rowIndex][columnIndex] = slope;
                } else if (slope == null) {
                    data[rowIndex][columnIndex] = "excluded";
                } else if (slope.isNaN()) {
                    data[rowIndex][columnIndex] = "NaN";
                }
            } catch (IndexOutOfBoundsException e) {
                data[rowIndex][columnIndex] = "";
            }
        }
        rowIndex++;
    }
    // array of column names for table model
    String[] columnNames = new String[data[0].length];
    columnNames[0] = "Log-concentration";
    for (int x = 1; x < columnNames.length; x++) {
        columnNames[x] = "Repl " + (x);
    }

    NonEditableTableModel nonEditableTableModel = new NonEditableTableModel();
    nonEditableTableModel.setDataVector(data, columnNames);
    return nonEditableTableModel;
}

From source file:org.gofleet.openLS.ddbb.dao.postgis.PostGisHBRoutingDAO.java

private RouteSummaryType getRouteSummary(Double cost) {
    RouteSummaryType res = new RouteSummaryType();
    DistanceType coste = new DistanceType();
    if (cost.isInfinite() || cost.isNaN())
        coste.setValue(BigDecimal.valueOf(0d));
    else/*  w  w w .jav a 2  s  . co  m*/
        coste.setValue(BigDecimal.valueOf(cost));
    res.setTotalDistance(coste);
    return res;
}

From source file:it.uniroma2.sag.kelp.data.representation.vector.DenseVector.java

@Override
public void setDataFromText(String representationDescription) {
    // String [] stringFeatures =
    // representationDescription.split(SEPARATOR);
    // float [] features = new float [stringFeatures.length];
    ////from   w  w  w  .  j a  va  2s  . co m
    // for(int i=0; i<stringFeatures.length; i++){
    // features[i]= Float.parseFloat(stringFeatures[i]);
    // }
    // this.setFeatureValues(features);
    String[] stringFeatures = representationDescription.split(SEPARATOR);
    this.featuresValues = new DenseMatrix64F(1, stringFeatures.length);

    for (int i = 0; i < stringFeatures.length; i++) {
        Double val = Double.parseDouble(stringFeatures[i]);
        if (val.isNaN()) {
            logger.warn("NaN value in representation: " + representationDescription);
        }
        this.featuresValues.set(0, i, val);
    }
}

From source file:gda.device.detector.countertimer.TFGScalerWithRatio.java

@Override
public double[] readout() throws DeviceException {
    double[] output = super.readout();

    if (getDarkCurrent() != null) {
        output = adjustForDarkCurrent(output, getCollectionTime());
    }/*w  ww  .ja  va 2s . co  m*/

    if (outputRatio) {
        Double ratio = new Double(0);
        // find which col is which I0, It and Iref
        Double[] values = getI0It(output);

        ratio = values[1] / values[0];

        // always return a numerical value
        if (ratio.isInfinite() || ratio.isNaN()) {
            ratio = 0.0;
        }

        // append to output array
        output = correctCounts(output, values);
        output = ArrayUtils.add(output, ratio);
    }
    return output;
}

From source file:org.tsho.dmc2.core.chart.BasinRenderer.java

public boolean isPointInfinite(double[] p) {
    Double a0 = new Double(p[0]);
    Double a1 = new Double(p[1]);
    if (a0.isInfinite() || a1.isInfinite() || a0.isNaN() || a1.isNaN() || Math.abs(p[0]) > infinity
            || Math.abs(p[1]) > infinity)
        return true;
    else/*ww w.j  a v a2  s . com*/
        return false;
}

From source file:eu.edisonproject.rest.FolderWatcherRunnable.java

private void convertMRResultToCSV(File mrPartPath, String outputPath, boolean calculateAvg) throws IOException {
    Map<String, Map<String, Double>> map = new HashMap<>();
    Map<String, Double> catSimMap;
    Map<String, List<Double>> avgMap = new HashMap<>();
    try (BufferedReader br = new BufferedReader(new FileReader(mrPartPath))) {
        String line;//  www  .j  a v a 2  s  .  com
        int count = 0;
        while ((line = br.readLine()) != null) {
            String[] kv = line.split("\t");
            String fileName = kv[0];
            String cat = kv[1];
            String sim = kv[2];
            catSimMap = map.get(fileName);
            if (catSimMap == null) {
                catSimMap = new HashMap<>();
            }
            catSimMap.put(cat, Double.valueOf(sim));
            map.put(fileName, catSimMap);
            List<Double> list = avgMap.get(cat);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(Double.valueOf(sim));
            avgMap.put(cat, list);
        }
    }

    Set<String> fileNames = map.keySet();
    StringBuilder header = new StringBuilder();
    header.append("JobId").append(",");
    for (Map<String, Double> m : map.values()) {
        for (String c : m.keySet()) {
            header.append(c).append(",");
        }
        break;
    }
    header.deleteCharAt(header.length() - 1);
    header.setLength(header.length());

    File csvFile = new File(outputPath);
    try (PrintWriter out = new PrintWriter(csvFile)) {
        out.println(header);
        for (String fName : fileNames) {
            StringBuilder csvLine = new StringBuilder();

            csvLine.append(fName).append(",");
            catSimMap = map.get(fName);
            for (String cat : catSimMap.keySet()) {
                Double sim = catSimMap.get(cat);
                csvLine.append(sim).append(",");
            }
            csvLine.deleteCharAt(csvLine.length() - 1);
            csvLine.setLength(csvLine.length());
            out.println(csvLine.toString());
        }
    }
    if (calculateAvg) {
        csvFile = new File(mrPartPath.getParent() + File.separator + CSV_AVG_FILENAME);
        try (PrintWriter out = new PrintWriter(csvFile)) {
            Set<String> keys = avgMap.keySet();
            for (String k : keys) {
                List<Double> list = avgMap.get(k);
                Double sum = 0d;
                for (Double val : list) {
                    if (!val.isNaN()) {
                        sum += val;
                    }
                }
                Double avg = sum / (list.size());
                out.println(k + "," + String.valueOf(avg));
            }
        }
    }

}

From source file:com.hurence.logisland.botsearch.Trace.java

/**
 *
 * <strong>note</strong> computeStats shall be called first
 *
 *//*from  w  w w . java  2 s  . co m*/
public void compute() throws IllegalArgumentException {

    computeFlowStats();

    double[] samples = sampleFlows();
    double[] magnitudes = computePowerSpectralDensity(samples);
    setMostSignificantFrequency(StatUtils.max(magnitudes));

    // check for a NaN (occuring when all flows occurs at the same time)
    Double maxFreq = getMostSignificantFrequency();
    if (maxFreq.isNaN()) {
        setMostSignificantFrequency(0.0);
    }
}

From source file:fr.cph.stock.android.entity.EntityBuilder.java

private List<Equity> buildEquities(JSONArray array) throws JSONException {
    List<Equity> equities = new ArrayList<Equity>();
    boolean find = true;
    int i = 0;/*from w  ww  . j  a v  a2s  .  com*/
    JSONObject temp;

    while (find) {
        temp = array.optJSONObject(i);
        if (temp != null) {
            Equity e = new Equity();
            e.setName(temp.getString("name"));

            double unitCostPrice = temp.getDouble("unitCostPrice");
            e.setUnitCostPrice(formatLocaleTwo.format(unitCostPrice));

            e.setValue(formatLocaleZero.format(temp.getDouble("value")));
            double plusMinusValue = temp.getDouble("plusMinusValue");
            String plusMinusValueStr = formatLocaleOne.format(plusMinusValue) + "%";
            if (plusMinusValue > 0) {
                e.setPlusMinusValue("+" + plusMinusValueStr);
            } else {
                e.setPlusMinusValue(plusMinusValueStr);
            }
            e.setUp(plusMinusValue > 0 ? true : false);

            double quantity = temp.getDouble("quantity");
            e.setQuantity(formatLocaleOne.format(quantity));

            double yieldYear = temp.getDouble("yieldYear");
            e.setYieldYear(formatLocaleOne.format(yieldYear) + "%");

            double yieldUnitCostPrice = temp.getDouble("yieldUnitCostPrice");
            e.setYieldUnitCostPrice(formatLocaleOne.format(yieldUnitCostPrice) + "%");

            double quote = temp.getDouble("quote");
            e.setQuote(formatLocaleTwo.format(quote));

            double plusMinusUnitCostPriceValue = temp.getDouble("plusMinusUnitCostPriceValue");
            if (plusMinusValue > 0) {
                e.setPlusMinusUnitCostPriceValue("+" + formatLocaleZero.format(plusMinusUnitCostPriceValue));
            } else {
                e.setPlusMinusUnitCostPriceValue(formatLocaleZero.format(plusMinusUnitCostPriceValue));
            }
            Double variation = temp.optDouble("variation");
            if (!variation.isNaN()) {
                if (variation >= 0) {
                    e.setUpVariation(true);
                    e.setVariation("+" + formatLocaleTwo.format(variation) + "%");
                } else {
                    e.setUpVariation(false);
                    e.setVariation(formatLocaleTwo.format(variation) + "%");
                }
            } else {
                e.setUpVariation(true);
                e.setVariation("+0%");
            }
            equities.add(e);
            i++;
        } else {
            find = false;
        }
    }
    return equities;
}