Example usage for java.nio ByteBuffer putFloat

List of usage examples for java.nio ByteBuffer putFloat

Introduction

In this page you can find the example usage for java.nio ByteBuffer putFloat.

Prototype

public abstract ByteBuffer putFloat(float value);

Source Link

Document

Writes the given float to the current position and increases the position by 4.

Usage

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * for grid cutter//  www .  j  a  v  a 2s  . c  o  m
 * <p/>
 * writes out a list of double (same as getGrid() returns) to a file
 * <p/>
 * byteorderlsb
 * data type, FLOAT
 *
 * @param newfilename
 * @param dfiltered
 */
public void writeGrid(String newfilename, double[] dfiltered, double xmin, double ymin, double xmax,
        double ymax, double xres, double yres, int nrows, int ncols) {
    int size, i, length = dfiltered.length;
    double maxvalue = Double.MAX_VALUE * -1;
    double minvalue = Double.MAX_VALUE;

    //write data as whole file
    RandomAccessFile afile = null;
    try { //read of random access file can throw an exception
        afile = new RandomAccessFile(newfilename + ".gri", "rw");

        size = 4;
        byte[] b = new byte[size * length];
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            bb.order(ByteOrder.BIG_ENDIAN);
        }
        for (i = 0; i < length; i++) {
            if (Double.isNaN(dfiltered[i])) {
                bb.putFloat((float) noDataValueDefault);
            } else {
                if (minvalue > dfiltered[i]) {
                    minvalue = dfiltered[i];
                }
                if (maxvalue < dfiltered[i]) {
                    maxvalue = dfiltered[i];
                }
                bb.putFloat((float) dfiltered[i]);
            }
        }

        afile.write(b);
    } catch (Exception e) {
        logger.error("error writing grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    writeHeader(newfilename, xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows, ncols,
            minvalue, maxvalue, "FLT4BYTES", String.valueOf(noDataValueDefault));
}

From source file:au.org.ala.layers.intersect.Grid.java

public void writeGrid(String newfilename, float[] dfiltered, double xmin, double ymin, double xmax, double ymax,
        double xres, double yres, int nrows, int ncols) {
    int size, i, length = dfiltered.length;
    double maxvalue = Double.MAX_VALUE * -1;
    double minvalue = Double.MAX_VALUE;

    //write data as whole file
    RandomAccessFile afile = null;
    try { //read of random access file can throw an exception
        afile = new RandomAccessFile(newfilename + ".gri", "rw");

        size = 4;/*from  www . ja  va2s.  c  o  m*/
        byte[] b = new byte[size * length];
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            bb.order(ByteOrder.BIG_ENDIAN);
        }
        for (i = 0; i < length; i++) {
            if (Double.isNaN(dfiltered[i])) {
                bb.putFloat((float) noDataValueDefault);
            } else {
                if (minvalue > dfiltered[i]) {
                    minvalue = dfiltered[i];
                }
                if (maxvalue < dfiltered[i]) {
                    maxvalue = dfiltered[i];
                }
                bb.putFloat((float) dfiltered[i]);
            }
        }

        afile.write(b);
    } catch (Exception e) {
        logger.error("error writing grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    writeHeader(newfilename, xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows, ncols,
            minvalue, maxvalue, "FLT4BYTES", String.valueOf(noDataValueDefault));

}

From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java

protected ByteBuffer writeFixedLengthField(Object obj, ByteBuffer buffer) throws IOException {
    // since booleans are not written by this method, it's safe to convert any
    // incoming boolean into an integer.
    obj = booleanToInteger(obj);/*from  w ww.  j  av a 2 s .  com*/

    switch (getType()) {
    case BOOLEAN:
        //Do nothing
        break;
    case BYTE:
        buffer.put(toNumber(obj).byteValue());
        break;
    case INT:
        buffer.putShort(toNumber(obj).shortValue());
        break;
    case LONG:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case MONEY:
        writeCurrencyValue(buffer, obj);
        break;
    case FLOAT:
        buffer.putFloat(toNumber(obj).floatValue());
        break;
    case DOUBLE:
        buffer.putDouble(toNumber(obj).doubleValue());
        break;
    case SHORT_DATE_TIME:
        writeDateValue(buffer, obj);
        break;
    case TEXT:
        // apparently text numeric values are also occasionally written as fixed
        // length...
        int numChars = getLengthInUnits();
        // force uncompressed encoding for fixed length text
        buffer.put(encodeTextValue(obj, numChars, numChars, true));
        break;
    case GUID:
        writeGUIDValue(buffer, obj);
        break;
    case NUMERIC:
        // yes, that's right, occasionally numeric values are written as fixed
        // length...
        writeNumericValue(buffer, obj);
        break;
    case BINARY:
    case UNKNOWN_0D:
    case UNKNOWN_11:
    case COMPLEX_TYPE:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case UNSUPPORTED_FIXEDLEN:
        byte[] bytes = toByteArray(obj);
        if (bytes.length != getLength()) {
            throw new IOException(
                    "Invalid fixed size binary data, size " + getLength() + ", got " + bytes.length);
        }
        buffer.put(bytes);
        break;
    default:
        throw new IOException("Unsupported data type: " + getType());
    }
    return buffer;
}

From source file:hivemall.GeneralLearnerBaseUDTF.java

protected void recordTrainSampleToTempFile(@Nonnull final FeatureValue[] featureVector, final float target)
        throws HiveException {
    if (iterations == 1) {
        return;//w  w w. j a va  2  s  . c  o  m
    }

    ByteBuffer buf = inputBuf;
    NioStatefulSegment dst = fileIO;

    if (buf == null) {
        final File file;
        try {
            file = File.createTempFile("hivemall_general_learner", ".sgmt");
            file.deleteOnExit();
            if (!file.canWrite()) {
                throw new UDFArgumentException("Cannot write a temporary file: " + file.getAbsolutePath());
            }
            logger.info("Record training samples to a file: " + file.getAbsolutePath());
        } catch (IOException ioe) {
            throw new UDFArgumentException(ioe);
        } catch (Throwable e) {
            throw new UDFArgumentException(e);
        }
        this.inputBuf = buf = ByteBuffer.allocateDirect(1024 * 1024); // 1 MB
        this.fileIO = dst = new NioStatefulSegment(file, false);
    }

    int featureVectorBytes = 0;
    for (FeatureValue f : featureVector) {
        if (f == null) {
            continue;
        }
        int featureLength = f.getFeatureAsString().length();

        // feature as String (even if it is Text or Integer)
        featureVectorBytes += SizeOf.CHAR * featureLength;

        // NIOUtils.putString() first puts the length of string before string itself
        featureVectorBytes += SizeOf.INT;

        // value
        featureVectorBytes += SizeOf.DOUBLE;
    }

    // feature length, feature 1, feature 2, ..., feature n, target
    int recordBytes = SizeOf.INT + featureVectorBytes + SizeOf.FLOAT;
    int requiredBytes = SizeOf.INT + recordBytes; // need to allocate space for "recordBytes" itself

    int remain = buf.remaining();
    if (remain < requiredBytes) {
        writeBuffer(buf, dst);
    }

    buf.putInt(recordBytes);
    buf.putInt(featureVector.length);
    for (FeatureValue f : featureVector) {
        writeFeatureValue(buf, f);
    }
    buf.putFloat(target);
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Serialize an Object into a raw byte value for this column
 * @param obj Object to serialize/*from w ww.  j a  va 2s. c  o m*/
 * @param order Order in which to serialize
 * @return A buffer containing the bytes
 * @usage _advanced_method_
 */
public ByteBuffer writeFixedLengthField(Object obj, ByteOrder order) throws IOException {
    int size = getType().getFixedSize(_columnLength);

    // create buffer for data
    ByteBuffer buffer = getPageChannel().createBuffer(size, order);

    // since booleans are not written by this method, it's safe to convert any
    // incoming boolean into an integer.
    obj = booleanToInteger(obj);

    switch (getType()) {
    case BOOLEAN:
        //Do nothing
        break;
    case BYTE:
        buffer.put(toNumber(obj).byteValue());
        break;
    case INT:
        buffer.putShort(toNumber(obj).shortValue());
        break;
    case LONG:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case MONEY:
        writeCurrencyValue(buffer, obj);
        break;
    case FLOAT:
        buffer.putFloat(toNumber(obj).floatValue());
        break;
    case DOUBLE:
        buffer.putDouble(toNumber(obj).doubleValue());
        break;
    case SHORT_DATE_TIME:
        writeDateValue(buffer, obj);
        break;
    case TEXT:
        // apparently text numeric values are also occasionally written as fixed
        // length...
        int numChars = getLengthInUnits();
        // force uncompressed encoding for fixed length text
        buffer.put(encodeTextValue(obj, numChars, numChars, true));
        break;
    case GUID:
        writeGUIDValue(buffer, obj, order);
        break;
    case NUMERIC:
        // yes, that's right, occasionally numeric values are written as fixed
        // length...
        writeNumericValue(buffer, obj);
        break;
    case BINARY:
    case UNKNOWN_0D:
    case UNKNOWN_11:
    case COMPLEX_TYPE:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case UNSUPPORTED_FIXEDLEN:
        byte[] bytes = toByteArray(obj);
        if (bytes.length != getLength()) {
            throw new IOException(
                    "Invalid fixed size binary data, size " + getLength() + ", got " + bytes.length);
        }
        buffer.put(bytes);
        break;
    default:
        throw new IOException("Unsupported data type: " + getType());
    }
    buffer.flip();
    return buffer;
}

From source file:au.org.ala.layers.intersect.Grid.java

public void mergeMissingValues(Grid sourceOfMissingValues, boolean hideMissing) {
    float[] cells = sourceOfMissingValues.getGrid();

    float[] actual = getGrid();

    int length = actual.length;

    int i;//from   w w  w.  ja  va 2s  . c om
    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "rw");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "rw");
        }

        byte[] b = new byte[(int) afile.length()];

        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        }

        afile.seek(0);

        if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    if (nodatavalue >= 128) {
                        bb.put((byte) (nodatavalue - 256));
                    } else {
                        bb.put((byte) nodatavalue);
                    }
                } else {
                    if (actual[i] >= 128) {
                        bb.put((byte) (actual[i] - 256));
                    } else {
                        bb.put((byte) actual[i]);
                    }
                }
            }
        } else if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < length; i++) {
                bb.put((byte) actual[i]);
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putShort((short) nodatavalue);
                } else {
                    bb.putShort((short) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putInt((int) nodatavalue);
                } else {
                    bb.putInt((int) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putLong((long) nodatavalue);
                } else {
                    bb.putLong((long) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putFloat((float) nodatavalue);
                } else {
                    bb.putFloat(actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putDouble((double) nodatavalue);
                } else {
                    bb.putDouble((double) actual[i]);
                }
            }
        } else {
            // should not happen
            logger.error("unsupported grid data type: " + datatype);
        }

        afile.write(bb.array());
    } catch (Exception e) {
        logger.error("error getting grid file values", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}