Example usage for java.lang Double NEGATIVE_INFINITY

List of usage examples for java.lang Double NEGATIVE_INFINITY

Introduction

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

Prototype

double NEGATIVE_INFINITY

To view the source code for java.lang Double NEGATIVE_INFINITY.

Click Source Link

Document

A constant holding the negative infinity of type double .

Usage

From source file:org.jfree.data.general.DatasetUtils.java

/**
 * Iterates over the data item of the category dataset to find
 * the range bounds./*ww w. j a v a2s.  c om*/
 *
 * @param dataset  the dataset ({@code null} not permitted).
 * @param includeInterval  a flag that determines whether or not the
 *                         y-interval is taken into account.
 * @param visibleSeriesKeys  the visible series keys.
 *
 * @return The range (possibly {@code null}).
 *
 * @since 1.0.13
 */
public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys,
        boolean includeInterval) {

    Args.nullNotPermitted(dataset, "dataset");
    Args.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");

    double minimum = Double.POSITIVE_INFINITY;
    double maximum = Double.NEGATIVE_INFINITY;
    int columnCount = dataset.getColumnCount();
    if (includeInterval && dataset instanceof BoxAndWhiskerCategoryDataset) {
        // handle special case of BoxAndWhiskerDataset
        BoxAndWhiskerCategoryDataset bx = (BoxAndWhiskerCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            int itemCount = dataset.getColumnCount();
            for (int item = 0; item < itemCount; item++) {
                Number lvalue = bx.getMinRegularValue(series, item);
                if (lvalue == null) {
                    lvalue = bx.getValue(series, item);
                }
                Number uvalue = bx.getMaxRegularValue(series, item);
                if (uvalue == null) {
                    uvalue = bx.getValue(series, item);
                }
                if (lvalue != null) {
                    minimum = Math.min(minimum, lvalue.doubleValue());
                }
                if (uvalue != null) {
                    maximum = Math.max(maximum, uvalue.doubleValue());
                }
            }
        }
    } else if (includeInterval && dataset instanceof IntervalCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
        Number lvalue, uvalue;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                lvalue = icd.getStartValue(series, column);
                uvalue = icd.getEndValue(series, column);
                if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) {
                    minimum = Math.min(minimum, lvalue.doubleValue());
                }
                if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) {
                    maximum = Math.max(maximum, uvalue.doubleValue());
                }
            }
        }
    } else if (includeInterval && dataset instanceof MultiValueCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        MultiValueCategoryDataset mvcd = (MultiValueCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                List values = mvcd.getValues(series, column);
                Iterator valueIterator = values.iterator();
                while (valueIterator.hasNext()) {
                    Object o = valueIterator.next();
                    if (o instanceof Number) {
                        double v = ((Number) o).doubleValue();
                        if (!Double.isNaN(v)) {
                            minimum = Math.min(minimum, v);
                            maximum = Math.max(maximum, v);
                        }
                    }
                }
            }
        }
    } else if (includeInterval && dataset instanceof StatisticalCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        StatisticalCategoryDataset scd = (StatisticalCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                Number meanN = scd.getMeanValue(series, column);
                if (meanN != null) {
                    double std = 0.0;
                    Number stdN = scd.getStdDevValue(series, column);
                    if (stdN != null) {
                        std = stdN.doubleValue();
                        if (Double.isNaN(std)) {
                            std = 0.0;
                        }
                    }
                    double mean = meanN.doubleValue();
                    if (!Double.isNaN(mean)) {
                        minimum = Math.min(minimum, mean - std);
                        maximum = Math.max(maximum, mean + std);
                    }
                }
            }
        }
    } else {
        // handle the standard case (plain CategoryDataset)
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                Number value = dataset.getValue(series, column);
                if (value != null) {
                    double v = value.doubleValue();
                    if (!Double.isNaN(v)) {
                        minimum = Math.min(minimum, v);
                        maximum = Math.max(maximum, v);
                    }
                }
            }
        }
    }
    if (minimum == Double.POSITIVE_INFINITY) {
        return null;
    } else {
        return new Range(minimum, maximum);
    }
}

From source file:org.powertac.auctioneer.AuctionServiceTests.java

@Test
public void testQuantitytValidity() {
    Order buy1 = new Order(b2, ts2.getSerialNumber(), 0.75, -37.0);
    Order buy2 = new Order(b2, ts2.getSerialNumber(), Double.NaN, -35.0);
    Order buy3 = new Order(b2, ts2.getSerialNumber(), Double.POSITIVE_INFINITY, -35.0);
    Order buy4 = new Order(b2, ts2.getSerialNumber(), Double.NEGATIVE_INFINITY, -35.0);
    svc.handleMessage(buy1);/*w ww.j  a  v a  2  s.c  o m*/
    svc.handleMessage(buy2);
    svc.handleMessage(buy3);
    svc.handleMessage(buy4);

    assertEquals("one order validated", 1, svc.getIncoming().size());
}

From source file:org.jfree.data.general.DatasetUtilities.java

/**
 * Iterates over the data item of the category dataset to find
 * the range bounds./*from w  w  w  .ja v a 2  s  .  c o m*/
 *
 * @param dataset  the dataset (<code>null</code> not permitted).
 * @param includeInterval  a flag that determines whether or not the
 *                         y-interval is taken into account.
 * @param visibleSeriesKeys  the visible series keys.
 *
 * @return The range (possibly <code>null</code>).
 *
 * @since 1.0.13
 */
public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys,
        boolean includeInterval) {

    ParamChecks.nullNotPermitted(dataset, "dataset");
    ParamChecks.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");

    double minimum = Double.POSITIVE_INFINITY;
    double maximum = Double.NEGATIVE_INFINITY;
    int columnCount = dataset.getColumnCount();
    if (includeInterval && dataset instanceof BoxAndWhiskerCategoryDataset) {
        // handle special case of BoxAndWhiskerDataset
        BoxAndWhiskerCategoryDataset bx = (BoxAndWhiskerCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            int itemCount = dataset.getColumnCount();
            for (int item = 0; item < itemCount; item++) {
                Number lvalue = bx.getMinRegularValue(series, item);
                if (lvalue == null) {
                    lvalue = bx.getValue(series, item);
                }
                Number uvalue = bx.getMaxRegularValue(series, item);
                if (uvalue == null) {
                    uvalue = bx.getValue(series, item);
                }
                if (lvalue != null) {
                    minimum = Math.min(minimum, lvalue.doubleValue());
                }
                if (uvalue != null) {
                    maximum = Math.max(maximum, uvalue.doubleValue());
                }
            }
        }
    } else if (includeInterval && dataset instanceof IntervalCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
        Number lvalue, uvalue;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                lvalue = icd.getStartValue(series, column);
                uvalue = icd.getEndValue(series, column);
                if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) {
                    minimum = Math.min(minimum, lvalue.doubleValue());
                }
                if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) {
                    maximum = Math.max(maximum, uvalue.doubleValue());
                }
            }
        }
    } else if (includeInterval && dataset instanceof MultiValueCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        MultiValueCategoryDataset mvcd = (MultiValueCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                List values = mvcd.getValues(series, column);
                Iterator valueIterator = values.iterator();
                while (valueIterator.hasNext()) {
                    Object o = valueIterator.next();
                    if (o instanceof Number) {
                        double v = ((Number) o).doubleValue();
                        if (!Double.isNaN(v)) {
                            minimum = Math.min(minimum, v);
                            maximum = Math.max(maximum, v);
                        }
                    }
                }
            }
        }
    } else if (includeInterval && dataset instanceof StatisticalCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        StatisticalCategoryDataset scd = (StatisticalCategoryDataset) dataset;
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                Number meanN = scd.getMeanValue(series, column);
                if (meanN != null) {
                    double std = 0.0;
                    Number stdN = scd.getStdDevValue(series, column);
                    if (stdN != null) {
                        std = stdN.doubleValue();
                        if (Double.isNaN(std)) {
                            std = 0.0;
                        }
                    }
                    double mean = meanN.doubleValue();
                    if (!Double.isNaN(mean)) {
                        minimum = Math.min(minimum, mean - std);
                        maximum = Math.max(maximum, mean + std);
                    }
                }
            }
        }
    } else {
        // handle the standard case (plain CategoryDataset)
        Iterator iterator = visibleSeriesKeys.iterator();
        while (iterator.hasNext()) {
            Comparable seriesKey = (Comparable) iterator.next();
            int series = dataset.getRowIndex(seriesKey);
            for (int column = 0; column < columnCount; column++) {
                Number value = dataset.getValue(series, column);
                if (value != null) {
                    double v = value.doubleValue();
                    if (!Double.isNaN(v)) {
                        minimum = Math.min(minimum, v);
                        maximum = Math.max(maximum, v);
                    }
                }
            }
        }
    }
    if (minimum == Double.POSITIVE_INFINITY) {
        return null;
    } else {
        return new Range(minimum, maximum);
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#isInfinite(java.lang.Object)}.
 *///  w  w w .  j  a v a2s  . co  m
@Test
public void testIsInfiniteObject() {
    assertEquals("null", false, isInfinite(null));
    assertEquals("empty", false, isInfinite(""));
    assertEquals("invalidString", false, isInfinite("not a number"));
    assertEquals("notParsable", false, isInfinite(new int[] { 1, 2, 3 }));
    assertEquals("notParsable", false,
            isInfinite(new float[] { Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }));
    assertEquals("NaN", false, isInfinite(Double.NaN));
    assertEquals("Infinity: Float", true, isInfinite(Float.POSITIVE_INFINITY));
    assertEquals("Infinity: Double", true, isInfinite(Double.POSITIVE_INFINITY));
    assertEquals("Infinity: String", true, isInfinite("Infinity"));
    assertEquals("-Infinity: Float", true, isInfinite(Float.NEGATIVE_INFINITY));
    assertEquals("-Infinity: Double", true, isInfinite(Double.NEGATIVE_INFINITY));
    assertEquals("-Infinity: String", true, isInfinite("-Infinity"));
    assertEquals("Infinity: BIgDecimal", false, isInfinite(INFINITY_DOUBLE));

    assertEquals(true, isInfinite(INFINITY_DOUBLE.doubleValue()));
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@link org.apache.commons.lang3.math.NumberUtils#createNumber(String)}.
 *
 * @param o the object, number or string.
 * @return {@code (Number) o}. Return null if o could not convertible to number.
 *///w  w  w.java 2 s . c o m
@SuppressWarnings("unchecked")
public static <T extends Number> T valueOf(Object o) {
    if (o == null)
        return null;
    if (Number.class.isAssignableFrom(o.getClass()))
        return (T) o;
    if ("-Infinity".equals(o.toString()))
        return (T) (Double) Double.NEGATIVE_INFINITY;
    if ("Infinity".equals(o.toString()))
        return (T) (Double) Double.POSITIVE_INFINITY;
    if ("NaN".equals(o.toString()))
        return (T) (Double) Double.NaN;
    try {
        if (isNumber(o.toString()))
            return (T) createNumber(o.toString());
    } catch (NumberFormatException e) {
    }

    return null;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.rdata.RDATAFileReader.java

/**
  * Create UNF from Tabular File// ww w . ja v a 2 s .c o m
  * This methods iterates through each column of the supplied data table and
  * invoked the 
  * @param DataTable table a rectangular data table
  * @return void
  */
private void createUNF(DataTable table) throws IOException {
    List<Integer> variableTypeList = getVariableTypeList(mDataTypes);
    String[] dateFormats = new String[mCaseQuantity];
    String[] unfValues = new String[mVarQuantity];
    String fileUNFvalue = null;

    // Set variable types
    // smd.setVariableTypeMinimal(ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()])));

    int[] x = ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()]));

    for (int k = 0; k < mVarQuantity; k++) {
        String unfValue, name = variableNameList.get(k);
        int varType = variableTypeList.get(k);

        Object[] varData = table.getData()[k];

        LOG.fine(String.format("RDATAFileReader: Column \"%s\" = %s", name, Arrays.deepToString(varData)));

        try {
            switch (varType) {
            case 0:
                Long[] integerEntries = new Long[varData.length];

                LOG.fine(k + ": " + name + " is numeric (integer)");

                if (smd.isBooleanVariable()[k]) {
                    // This is not a regular integer - but a boolean!
                    LOG.fine(k + ": " + name + " is NOT a simple integer - it's a logical (boolean)!");
                    Boolean[] booleanEntries = new Boolean[varData.length];
                    for (int i = 0; i < varData.length; i++) {
                        if (varData[i] == null || varData[i].equals("")) {
                            // Missing Value: 
                            booleanEntries[i] = null;
                        } else if (((String) varData[i]).equals("0")) {
                            booleanEntries[i] = false;
                        } else if (((String) varData[i]).equals("1")) {
                            booleanEntries[i] = true;
                        } else {
                            // Treat it as a missing value? 
                            booleanEntries[i] = null;
                            // TODO: 
                            // Should we throw an exception here instead? 
                        }

                        // We'll also need the integer values, to calculate
                        // the summary statistics: 
                        try {
                            integerEntries[i] = new Long((String) varData[i]);
                        } catch (Exception ex) {
                            integerEntries[i] = null;
                        }
                    }

                    unfValue = UNF5Util.calculateUNF(booleanEntries);
                    // TODO: 
                    // we've never calculated UNFs for Booleans before - 
                    // need to QA and verify that the values produced are correct.
                    // -- L.A.

                } else {
                    // Regular integer;
                    // Treat it as an array of Longs:
                    LOG.fine(k + ": " + name + " is a simple integer.");

                    for (int i = 0; i < varData.length; i++) {
                        try {
                            integerEntries[i] = new Long((String) varData[i]);
                        } catch (Exception ex) {
                            integerEntries[i] = null;
                        }
                    }

                    unfValue = UNF5Util.calculateUNF(integerEntries);

                    // UNF5Util.cal
                }

                // Summary/category statistics
                smd.getSummaryStatisticsTable().put(k,
                        ArrayUtils.toObject(StatHelper.calculateSummaryStatistics(integerEntries)));
                Map<String, Integer> catStat = StatHelper.calculateCategoryStatistics(integerEntries);
                smd.getCategoryStatisticsTable().put(variableNameList.get(k), catStat);
                smd.getNullValueCounts().put(variableNameList.get(k),
                        StatHelper.countNullValues(integerEntries));

                break;

            // If double
            case 1:
                LOG.fine(k + ": " + name + " is numeric (double)");
                // Convert array of Strings to array of Doubles
                Double[] doubleEntries = new Double[varData.length];

                for (int i = 0; i < varData.length; i++) {
                    try {
                        // Check for the special case of "NaN" - this is the R and DVN
                        // notation for the "Not A Number" value:
                        if (varData[i] != null && ((String) varData[i]).equals("NaN")) {
                            doubleEntries[i] = Double.NaN;
                            // "Inf" is another special case, notation for infinity, 
                            // positive and negative:
                        } else if (varData[i] != null && (((String) varData[i]).equals("Inf")
                                || ((String) varData[i]).equals("+Inf"))) {

                            doubleEntries[i] = Double.POSITIVE_INFINITY;
                        } else if (varData[i] != null && ((String) varData[i]).equals("-Inf")) {

                            doubleEntries[i] = Double.NEGATIVE_INFINITY;
                        } else {
                            // Missing Values don't need to be treated separately; these 
                            // are represented as empty strings in the TAB file; so 
                            // attempting to create a Double object from one will 
                            // throw an exception - which we are going to intercept 
                            // below. For the UNF and Summary Stats purposes, missing
                            // values are represented as NULLs. 
                            doubleEntries[i] = new Double((String) varData[i]);
                        }
                    } catch (Exception ex) {
                        LOG.fine(k + ": " + name + " dropping value " + (String) varData[i] + " (" + i
                                + "); replacing with null");
                        doubleEntries[i] = null;
                    }
                }

                LOG.fine("sumstat:double case=" + Arrays.deepToString(ArrayUtils
                        .toObject(StatHelper.calculateSummaryStatisticsContDistSample(doubleEntries))));

                // Save summary statistics:
                smd.getSummaryStatisticsTable().put(k, ArrayUtils
                        .toObject(StatHelper.calculateSummaryStatisticsContDistSample(doubleEntries)));

                unfValue = UNF5Util.calculateUNF(doubleEntries);

                break;

            case -1:
                LOG.fine(k + ": " + name + " is string");

                String[] stringEntries = new String[varData.length];//Arrays.asList(varData).toArray(new String[varData.length]);

                LOG.fine("string array passed to calculateUNF: " + Arrays.deepToString(stringEntries));

                //
                if (mFormatTable[k] == FORMAT_DATE || mFormatTable[k] == FORMAT_DATETIME) {
                    DateFormatter dateFormatter = new DateFormatter();

                    dateFormatter.setDateFormats(DATE_FORMATS);
                    dateFormatter.setTimeFormats(TIME_FORMATS);

                    for (int i = 0; i < varData.length; i++) {
                        DateWithFormatter entryDateWithFormat;

                        // If data is missing, treat this entry as just that - 
                        // a missing value. Just like for all the other data types, 
                        // this is represented by a null:
                        if (dateFormats[i] != null && (varData[i].equals("") || varData[i].equals(" "))) {
                            stringEntries[i] = dateFormats[i] = null;
                        } else {
                            entryDateWithFormat = dateFormatter.getDateWithFormat((String) varData[i]);
                            if (entryDateWithFormat == null) {
                                LOG.fine("ATTENTION: the supplied date/time string could not be parsed ("
                                        + (String) varData[i]);
                                throw new IOException(
                                        "Could not parse supplied date/time string: " + (String) varData[i]);
                            }
                            // Otherwise get the pattern
                            // entryDateWithFormat = dateFormatter.getDateWithFormat(stringEntries[i]);
                            stringEntries[i] = (String) varData[i];
                            dateFormats[i] = entryDateWithFormat.getFormatter().toPattern();

                        }
                    }

                    // Compute UNF
                    try {
                        LOG.fine("RDATAFileReader: strdata = " + Arrays.deepToString(stringEntries));
                        LOG.fine("RDATAFileReader: dateFormats = " + Arrays.deepToString(dateFormats));

                        unfValue = UNF5Util.calculateUNF(stringEntries, dateFormats);
                    } catch (Exception ex) {
                        LOG.warning("RDATAFileReader: UNF for variable " + name + " could not be computed!");
                        //unfValue = UNF5Util.calculateUNF(stringEntries);
                        //ex.printStackTrace();
                        throw ex;
                    }
                } else {
                    for (int i = 0; i < varData.length; i++) {
                        if (varData[i] == null) {
                            // Missing Value
                            stringEntries[i] = null;
                        } else {
                            stringEntries[i] = (String) varData[i];
                        }
                    }

                    unfValue = UNF5Util.calculateUNF(stringEntries);
                }

                smd.getSummaryStatisticsTable().put(k, StatHelper.calculateSummaryStatistics(stringEntries));
                Map<String, Integer> StrCatStat = StatHelper.calculateCategoryStatistics(stringEntries);
                smd.getCategoryStatisticsTable().put(variableNameList.get(k), StrCatStat);
                smd.getNullValueCounts().put(variableNameList.get(k),
                        StatHelper.countNullValues(stringEntries));

                break;

            default:
                unfValue = null;

            }

            //LOG.fine(String.format("RDATAFileReader: Column \"%s\" (UNF) = %s", name, unfValue));

            // Store UNF value
            unfValues[k] = unfValue;
        } catch (Exception ex) {
            LOG.fine("Exception caught while calculating UNF! " + ex.getMessage());
            ex.printStackTrace();
            throw new IOException("Exception caught while calculating UNF! " + ex.getMessage());
        }
        LOG.fine(String.format("RDATAFileReader: Column \"%s\" (UNF) = %s", name, unfValues[k]));

    }

    try {
        fileUNFvalue = UNF5Util.calculateUNF(unfValues);
    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.fine("Exception caught while calculating the combined UNF for the data set! " + ex.getMessage());
        throw new IOException(
                "Exception caught while calculating the combined UNF for the data set! " + ex.getMessage());
    }
    mCsvDataTable.setUnf(unfValues);
    mCsvDataTable.setFileUnf(fileUNFvalue);

    // Set meta-data to make it look like a SAV file
    // smd.setVariableStorageType(null);
    // smd.setDecimalVariables(mDecimalVariableSet);

    boolean[] b = smd.isContinuousVariable();

    for (int k = 0; k < b.length; k++) {
        String s = b[k] ? "True" : "False";
        LOG.fine(k + " = " + s);
    }

    smd.setVariableUNF(unfValues);
    smd.getFileInformation().put("fileUNF", fileUNFvalue);
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public Object[] subsetObjectVector(File tabfile, int column, int varcount, int casecount, int columntype,
        boolean compatmode) throws IOException {

    Object[] retVector = null;//  w  w  w .  j ava2 s  .c  o m

    boolean isString = false;
    boolean isDouble = false;
    boolean isLong = false;
    boolean isFloat = false;

    //Locale loc = new Locale("en", "US");

    if (columntype == COLUMN_TYPE_STRING) {
        isString = true;
        retVector = new String[casecount];
    } else if (columntype == COLUMN_TYPE_DOUBLE) {
        isDouble = true;
        retVector = new Double[casecount];
    } else if (columntype == COLUMN_TYPE_LONG) {
        isLong = true;
        retVector = new Long[casecount];
    } else if (columntype == COLUMN_TYPE_FLOAT) {
        isFloat = true;
        retVector = new Float[casecount];
    } else {
        throw new IOException("Unsupported column type: " + columntype);
    }

    File rotatedImageFile = getRotatedImage(tabfile, varcount, casecount);
    long[] columnEndOffsets = extractColumnOffsets(rotatedImageFile, varcount, casecount);
    long columnOffset = 0;
    long columnLength = 0;

    if (column > 0) {
        columnOffset = columnEndOffsets[column - 1];
        columnLength = columnEndOffsets[column] - columnEndOffsets[column - 1];
    } else {
        columnOffset = varcount * 8;
        columnLength = columnEndOffsets[0] - varcount * 8;
    }

    FileChannel fc = (FileChannel.open(Paths.get(rotatedImageFile.getAbsolutePath()), StandardOpenOption.READ));
    fc.position(columnOffset);
    int MAX_COLUMN_BUFFER = 8192;

    ByteBuffer in = ByteBuffer.allocate(MAX_COLUMN_BUFFER);

    if (columnLength < MAX_COLUMN_BUFFER) {
        in.limit((int) (columnLength));
    }

    long bytesRead = 0;
    long bytesReadTotal = 0;
    int caseindex = 0;
    int byteoffset = 0;
    byte[] leftover = null;

    while (bytesReadTotal < columnLength) {
        bytesRead = fc.read(in);
        byte[] columnBytes = in.array();
        int bytecount = 0;

        while (bytecount < bytesRead) {
            if (columnBytes[bytecount] == '\n') {
                /*
                String token = new String(columnBytes, byteoffset, bytecount-byteoffset, "UTF8");
                        
                if (leftover != null) {
                String leftoverString = new String (leftover, "UTF8");
                token = leftoverString + token;
                leftover = null;
                }
                */
                /* 
                 * Note that the way I was doing it at first - above - 
                 * was not quite the correct way - because I was creating UTF8
                 * strings from the leftover bytes, and the bytes in the 
                 * current buffer *separately*; which means, if a multi-byte
                 * UTF8 character got split in the middle between one buffer
                 * and the next, both chunks of it would become junk 
                 * characters, on each side!
                 * The correct way of doing it, of course, is to create a
                 * merged byte buffer, and then turn it into a UTF8 string. 
                 *      -- L.A. 4.0
                 */
                String token = null;

                if (leftover == null) {
                    token = new String(columnBytes, byteoffset, bytecount - byteoffset, "UTF8");
                } else {
                    byte[] merged = new byte[leftover.length + bytecount - byteoffset];

                    System.arraycopy(leftover, 0, merged, 0, leftover.length);
                    System.arraycopy(columnBytes, byteoffset, merged, leftover.length, bytecount - byteoffset);
                    token = new String(merged, "UTF8");
                    leftover = null;
                    merged = null;
                }

                if (isString) {
                    if ("".equals(token)) {
                        // An empty string is a string missing value!
                        // An empty string in quotes is an empty string!
                        retVector[caseindex] = null;
                    } else {
                        // Strip the outer quotes:
                        token = token.replaceFirst("^\\\"", "");
                        token = token.replaceFirst("\\\"$", "");

                        // We need to restore the special characters that 
                        // are stored in tab files escaped - quotes, new lines 
                        // and tabs. Before we do that however, we need to 
                        // take care of any escaped backslashes stored in 
                        // the tab file. I.e., "foo\t" should be transformed 
                        // to "foo<TAB>"; but "foo\\t" should be transformed 
                        // to "foo\t". This way new lines and tabs that were
                        // already escaped in the original data are not 
                        // going to be transformed to unescaped tab and 
                        // new line characters!

                        String[] splitTokens = token.split(Matcher.quoteReplacement("\\\\"), -2);

                        // (note that it's important to use the 2-argument version 
                        // of String.split(), and set the limit argument to a
                        // negative value; otherwise any trailing backslashes 
                        // are lost.)

                        for (int i = 0; i < splitTokens.length; i++) {
                            splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\"");
                            splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t");
                            splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n");
                            splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r");
                        }
                        // TODO: 
                        // Make (some of?) the above optional; for ex., we 
                        // do need to restore the newlines when calculating UNFs;
                        // But if we are subsetting these vectors in order to 
                        // create a new tab-delimited file, they will 
                        // actually break things! -- L.A. Jul. 28 2014

                        token = StringUtils.join(splitTokens, '\\');

                        // "compatibility mode" - a hack, to be able to produce
                        // unfs identical to those produced by the "early" 
                        // unf5 jar; will be removed in production 4.0. 
                        // -- L.A. (TODO: ...)
                        if (compatmode && !"".equals(token)) {
                            if (token.length() > 128) {
                                if ("".equals(token.trim())) {
                                    // don't ask... 
                                    token = token.substring(0, 129);
                                } else {
                                    token = token.substring(0, 128);
                                    //token = String.format(loc, "%.128s", token);
                                    token = token.trim();
                                    //dbgLog.info("formatted and trimmed: "+token);
                                }
                            } else {
                                if ("".equals(token.trim())) {
                                    // again, don't ask; 
                                    // - this replicates some bugginness 
                                    // that happens inside unf5;
                                    token = "null";
                                } else {
                                    token = token.trim();
                                }
                            }
                        }

                        retVector[caseindex] = token;
                    }
                } else if (isDouble) {
                    try {
                        // TODO: verify that NaN and +-Inf are 
                        // handled correctly here! -- L.A.
                        // Verified: new Double("nan") works correctly, 
                        // resulting in Double.NaN;
                        // Double("[+-]Inf") doesn't work however; 
                        // (the constructor appears to be expecting it
                        // to be spelled as "Infinity", "-Infinity", etc. 
                        if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) {
                            retVector[caseindex] = java.lang.Double.POSITIVE_INFINITY;
                        } else if ("-inf".equalsIgnoreCase(token)) {
                            retVector[caseindex] = java.lang.Double.NEGATIVE_INFINITY;
                        } else if (token == null || token.equals("")) {
                            // missing value:
                            retVector[caseindex] = null;
                        } else {
                            retVector[caseindex] = new Double(token);
                        }
                    } catch (NumberFormatException ex) {
                        dbgLog.warning("NumberFormatException thrown for " + token + " as Double");

                        retVector[caseindex] = null; // missing value
                        // TODO: ?
                    }
                } else if (isLong) {
                    try {
                        retVector[caseindex] = new Long(token);
                    } catch (NumberFormatException ex) {
                        retVector[caseindex] = null; // assume missing value
                    }
                } else if (isFloat) {
                    try {
                        if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) {
                            retVector[caseindex] = java.lang.Float.POSITIVE_INFINITY;
                        } else if ("-inf".equalsIgnoreCase(token)) {
                            retVector[caseindex] = java.lang.Float.NEGATIVE_INFINITY;
                        } else if (token == null || token.equals("")) {
                            // missing value:
                            retVector[caseindex] = null;
                        } else {
                            retVector[caseindex] = new Float(token);
                        }
                    } catch (NumberFormatException ex) {
                        dbgLog.warning("NumberFormatException thrown for " + token + " as Float");
                        retVector[caseindex] = null; // assume missing value (TODO: ?)
                    }
                }
                caseindex++;

                if (bytecount == bytesRead - 1) {
                    byteoffset = 0;
                } else {
                    byteoffset = bytecount + 1;
                }
            } else {
                if (bytecount == bytesRead - 1) {
                    // We've reached the end of the buffer; 
                    // This means we'll save whatever unused bytes left in 
                    // it - i.e., the bytes between the last new line 
                    // encountered and the end - in the leftover buffer. 

                    // *EXCEPT*, there may be a case of a very long String
                    // that is actually longer than MAX_COLUMN_BUFFER, in 
                    // which case it is possible that we've read through
                    // an entire buffer of bytes without finding any 
                    // new lines... in this case we may need to add this
                    // entire byte buffer to an already existing leftover 
                    // buffer!
                    if (leftover == null) {
                        leftover = new byte[(int) bytesRead - byteoffset];
                        System.arraycopy(columnBytes, byteoffset, leftover, 0, (int) bytesRead - byteoffset);
                    } else {
                        if (byteoffset != 0) {
                            throw new IOException(
                                    "Reached the end of the byte buffer, with some leftover left from the last read; yet the offset is not zero!");
                        }
                        byte[] merged = new byte[leftover.length + (int) bytesRead];

                        System.arraycopy(leftover, 0, merged, 0, leftover.length);
                        System.arraycopy(columnBytes, byteoffset, merged, leftover.length, (int) bytesRead);
                        //leftover = null;
                        leftover = merged;
                        merged = null;
                    }
                    byteoffset = 0;

                }
            }
            bytecount++;
        }

        bytesReadTotal += bytesRead;
        in.clear();
        if (columnLength - bytesReadTotal < MAX_COLUMN_BUFFER) {
            in.limit((int) (columnLength - bytesReadTotal));
        }
    }

    fc.close();

    if (caseindex != casecount) {
        throw new IOException("Faile to read " + casecount + " tokens for column " + column);
        //System.out.println("read "+caseindex+" tokens instead of expected "+casecount+".");
    }

    return retVector;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#isInfinite(java.lang.Object, int)}.
 *//*from  w w w . ja va  2  s . c o m*/
@Test
public void testIsInfiniteObjectInt() {
    assertEquals("null", false, isInfinite(null, -1));
    assertEquals("null", false, isInfinite(null, 0));
    assertEquals("null", false, isInfinite(null, 1));
    assertEquals("empty", false, isInfinite("", -1));
    assertEquals("empty", false, isInfinite("", 0));
    assertEquals("empty", false, isInfinite("", 1));
    assertEquals("invalidString", false, isInfinite("not a number", -1));
    assertEquals("invalidString", false, isInfinite("not a number", 0));
    assertEquals("invalidString", false, isInfinite("not a number", 1));
    assertEquals("notParsable", false, isInfinite(new int[] { 1, 2, 3 }, -1));
    assertEquals("notParsable", false, isInfinite(new int[] { 1, 2, 3 }, 0));
    assertEquals("notParsable", false, isInfinite(new int[] { 1, 2, 3 }, 1));
    assertEquals("notParsable", false,
            isInfinite(new float[] { Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }, -1));
    assertEquals("notParsable", false,
            isInfinite(new float[] { Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }, 0));
    assertEquals("notParsable", false,
            isInfinite(new float[] { Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }, 1));
    assertEquals("NaN", false, isInfinite(Double.NaN, -1));
    assertEquals("NaN", false, isInfinite(Double.NaN, 0));
    assertEquals("NaN", false, isInfinite(Double.NaN, 1));

    assertEquals("Infinity: Float", false, isInfinite(Float.POSITIVE_INFINITY, -1));
    assertEquals("Infinity: Float", true, isInfinite(Float.POSITIVE_INFINITY, 0));
    assertEquals("Infinity: Float", true, isInfinite(Float.POSITIVE_INFINITY, 1));
    assertEquals("Infinity: Double", false, isInfinite(Double.POSITIVE_INFINITY, -1));
    assertEquals("Infinity: Double", true, isInfinite(Double.POSITIVE_INFINITY, 0));
    assertEquals("Infinity: Double", true, isInfinite(Double.POSITIVE_INFINITY, 1));
    assertEquals("Infinity: String", false, isInfinite("Infinity", -1));
    assertEquals("Infinity: String", true, isInfinite("Infinity", 0));
    assertEquals("Infinity: String", true, isInfinite("Infinity", 1));

    assertEquals("-Infinity: Float", true, isInfinite(Float.NEGATIVE_INFINITY, -1));
    assertEquals("-Infinity: Float", true, isInfinite(Float.NEGATIVE_INFINITY, 0));
    assertEquals("-Infinity: Float", false, isInfinite(Float.NEGATIVE_INFINITY, 1));
    assertEquals("-Infinity: Double", true, isInfinite(Double.NEGATIVE_INFINITY, -1));
    assertEquals("-Infinity: Double", true, isInfinite(Double.NEGATIVE_INFINITY, 0));
    assertEquals("-Infinity: Double", false, isInfinite(Double.NEGATIVE_INFINITY, 1));
    assertEquals("-Infinity: String", true, isInfinite("-Infinity", -1));
    assertEquals("-Infinity: String", true, isInfinite("-Infinity", 0));
    assertEquals("-Infinity: String", false, isInfinite("-Infinity", 1));
}

From source file:gedi.util.ArrayUtils.java

/**
 * Computes the max of the given array./*w  w  w  . ja va 2s.c o m*/
 * @param array the array
 * @return the max
 */
public static double max(double[] array) {
    if (array.length == 0)
        return Double.NEGATIVE_INFINITY;
    double re = array[0];
    for (int i = 1; i < array.length; i++)
        re = Math.max(re, array[i]);
    return re;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#isInfiniteOrNaN(java.lang.Object)}.
 *///  ww  w.j ava 2  s  .c o m
// @Test
public void testIsInfiniteOrNaN() {
    assertEquals("null", false, isInfiniteOrNaN(null));
    assertEquals("empty", false, isInfiniteOrNaN(""));
    assertEquals("invalidString", false, isInfiniteOrNaN("not a number"));
    assertEquals("notParsable", false, isInfiniteOrNaN(new int[] { 1, 2, 3 }));
    assertEquals("notParsable", false,
            isInfiniteOrNaN(new float[] { Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }));
    assertEquals("Infinity: Float", true, isInfiniteOrNaN(Float.POSITIVE_INFINITY));
    assertEquals("Infinity: Double", true, isInfiniteOrNaN(Double.POSITIVE_INFINITY));
    assertEquals("Infinity: String", true, isInfiniteOrNaN("Infinity"));
    assertEquals("-Infinity: Float", true, isInfiniteOrNaN(Float.NEGATIVE_INFINITY));
    assertEquals("-Infinity: Double", true, isInfiniteOrNaN(Double.NEGATIVE_INFINITY));
    assertEquals("-Infinity: String", true, isInfiniteOrNaN("-Infinity"));
    assertEquals("NaN: Double", true, isInfiniteOrNaN(Double.NaN));
    assertEquals("NaN: Float", true, isInfiniteOrNaN(Double.NaN));
    assertEquals("NaN: String", true, isInfiniteOrNaN("NaN"));

    assertEquals("NaN: Double", true, isInfiniteOrNaN(Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY));
    assertEquals("NaN: Float", true,
            isInfiniteOrNaN(divide(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, float.class)));
}