Example usage for java.nio ByteBuffer getFloat

List of usage examples for java.nio ByteBuffer getFloat

Introduction

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

Prototype

public abstract float getFloat();

Source Link

Document

Returns the float at the current position and increases the position by 4.

Usage

From source file:au.org.ala.layers.grid.GridCacheBuilder.java

static void nextRowOfFloats(float[] row, String datatype, boolean byteOrderLSB, int ncols, RandomAccessFile raf,
        byte[] b, float noDataValue) throws IOException {
    int size = 4;
    if (datatype.charAt(0) == 'U') {
        size = 1;// w  ww.j ava 2s  . c  o m
    } else if (datatype.charAt(0) == 'B') {
        size = 1;
    } else if (datatype.charAt(0) == 'S') {
        size = 2;
    } else if (datatype.charAt(0) == 'I') {
        size = 4;
    } else if (datatype.charAt(0) == 'L') {
        size = 8;
    } else if (datatype.charAt(0) == 'F') {
        size = 4;
    } else if (datatype.charAt(0) == 'D') {
        size = 8;
    }

    raf.read(b, 0, size * ncols);
    ByteBuffer bb = ByteBuffer.wrap(b);
    if (byteOrderLSB) {
        bb.order(ByteOrder.LITTLE_ENDIAN);
    } else {
        bb.order(ByteOrder.BIG_ENDIAN);
    }

    int i;
    int length = ncols;
    if (datatype.charAt(0) == 'U') {
        for (i = 0; i < length; i++) {
            float ret = bb.get();
            if (ret < 0) {
                ret += 256;
            }
            row[i] = ret;
        }
    } else if (datatype.charAt(0) == 'B') {

        for (i = 0; i < length; i++) {
            row[i] = (float) bb.get();
        }
    } else if (datatype.charAt(0) == 'S') {
        for (i = 0; i < length; i++) {
            row[i] = (float) bb.getShort();
        }
    } else if (datatype.charAt(0) == 'I') {
        for (i = 0; i < length; i++) {
            row[i] = (float) bb.getInt();
        }
    } else if (datatype.charAt(0) == 'L') {
        for (i = 0; i < length; i++) {
            row[i] = (float) bb.getLong();
        }
    } else if (datatype.charAt(0) == 'F') {
        for (i = 0; i < length; i++) {
            row[i] = (float) bb.getFloat();
        }
    } else if (datatype.charAt(0) == 'D') {
        for (i = 0; i < length; i++) {
            row[i] = (float) bb.getDouble();
        }
    } else {
        logger.info("UNKNOWN TYPE: " + datatype);
    }

    for (i = 0; i < length; i++) {
        if (row[i] == noDataValue) {
            row[i] = Float.NaN;
        }
    }
}

From source file:loci.formats.in.KLBReader.java

private PositiveFloat readFloat32() throws IOException {
    byte[] b = new byte[4];
    in.read(b, 0, 4);/*from  w  w w .  j  av a  2  s. c om*/
    ByteBuffer bb = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN);
    return new PositiveFloat((double) bb.getFloat());
}

From source file:org.bimserver.collada.ColladaSerializer.java

private List<String> floatBufferToStringList(ByteBuffer buffer, Format formatter) {
    // Transform the array into a list.
    List<Float> list = new ArrayList<Float>();
    while (buffer.hasRemaining())
        list.add(new Float(buffer.getFloat()));
    // Get the data as a list of String objects.
    return listToStringList(list, formatter);
}

From source file:io.github.msdk.io.mzdata.MzDataSaxHandler.java

/**
 * {@inheritDoc}//from   w w  w . j av  a2s .  c o  m
 *
 * endElement()
 */
@SuppressWarnings("null")
public void endElement(String namespaceURI, String sName, String qName) throws SAXException {

    if (canceled)
        throw new SAXException("Parsing Cancelled");

    // <spectrumInstrument>
    if (qName.equalsIgnoreCase("spectrumInstrument")) {
        spectrumInstrumentFlag = false;
    }

    // <precursor>
    if (qName.equalsIgnoreCase("precursor")) {
        precursorFlag = false;
    }

    // <spectrum>
    if (qName.equalsIgnoreCase("spectrum")) {

        spectrumInstrumentFlag = false;

        // Auto-detect whether this scan is centroided
        MsSpectrumType spectrumType = SpectrumTypeDetectionAlgorithm.detectSpectrumType(mzBuffer,
                intensityBuffer, peaksCount);

        // Create a new scan
        MsFunction msFunction = MSDKObjectBuilder.getMsFunction(msLevel);

        MsScan newScan = MSDKObjectBuilder.getMsScan(dataStore, scanNumber, msFunction);

        newScan.setDataPoints(mzBuffer, intensityBuffer, peaksCount);
        newScan.setSpectrumType(spectrumType);
        newScan.setPolarity(polarity);

        if (retentionTime != null) {
            ChromatographyInfo chromInfo = MSDKObjectBuilder.getChromatographyInfo1D(SeparationType.UNKNOWN,
                    retentionTime);
            newScan.setChromatographyInfo(chromInfo);
        }

        if (precursorMz != null) {
            IsolationInfo isolation = MSDKObjectBuilder.getIsolationInfo(Range.singleton(precursorMz), null,
                    precursorMz, precursorCharge, null);
            newScan.getIsolations().add(isolation);
        }

        // Add the scan to the file
        newRawFile.addScan(newScan);
        parsedScans++;

    }

    // <mzArrayBinary>
    if (qName.equalsIgnoreCase("mzArrayBinary")) {

        mzArrayBinaryFlag = false;

        // Allocate space for the whole array
        if (mzBuffer.length < peaksCount)
            mzBuffer = new double[peaksCount * 2];

        byte[] peakBytes = Base64.decodeBase64(charBuffer.toString().getBytes());

        ByteBuffer currentMzBytes = ByteBuffer.wrap(peakBytes);

        if (endian.equals("big")) {
            currentMzBytes = currentMzBytes.order(ByteOrder.BIG_ENDIAN);
        } else {
            currentMzBytes = currentMzBytes.order(ByteOrder.LITTLE_ENDIAN);
        }

        for (int i = 0; i < peaksCount; i++) {
            if (precision == null || precision.equals("32"))
                mzBuffer[i] = (double) currentMzBytes.getFloat();
            else
                mzBuffer[i] = currentMzBytes.getDouble();
        }

    }

    // <intenArrayBinary>
    if (qName.equalsIgnoreCase("intenArrayBinary")) {

        intenArrayBinaryFlag = false;

        // Allocate space for the whole array
        if (intensityBuffer.length < peaksCount)
            intensityBuffer = new float[peaksCount * 2];

        byte[] peakBytes = Base64.decodeBase64(charBuffer.toString().getBytes());

        ByteBuffer currentIntensityBytes = ByteBuffer.wrap(peakBytes);

        if (endian.equals("big")) {
            currentIntensityBytes = currentIntensityBytes.order(ByteOrder.BIG_ENDIAN);
        } else {
            currentIntensityBytes = currentIntensityBytes.order(ByteOrder.LITTLE_ENDIAN);
        }

        for (int i = 0; i < peaksCount; i++) {
            if (precision == null || precision.equals("32"))
                intensityBuffer[i] = currentIntensityBytes.getFloat();
            else
                intensityBuffer[i] = (float) currentIntensityBytes.getDouble();
        }
    }
}

From source file:edu.umn.cs.spatialHadoop.visualization.FrequencyMap.java

@Override
public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    int length = in.readInt();
    byte[] serializedData = new byte[length];
    in.readFully(serializedData);//  ww  w  .  j a v  a  2 s.  c o  m
    ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
    GZIPInputStream gzis = new GZIPInputStream(bais);

    byte[] buffer = new byte[8];
    gzis.read(buffer);
    ByteBuffer bbuffer = ByteBuffer.wrap(buffer);
    int width = bbuffer.getInt();
    int height = bbuffer.getInt();
    // Reallocate memory only if needed
    if (width != this.getWidth() || height != this.getHeight())
        frequencies = new float[width][height];
    buffer = new byte[getHeight() * 4];
    for (int x = 0; x < getWidth(); x++) {
        int size = 0;
        while (size < buffer.length) {
            size += gzis.read(buffer, size, buffer.length - size);
        }
        bbuffer = ByteBuffer.wrap(buffer);
        for (int y = 0; y < getHeight(); y++) {
            frequencies[x][y] = bbuffer.getFloat();
        }
    }
}

From source file:org.bimserver.collada.ColladaSerializer.java

private void setGeometry(PrintWriter out, IfcProduct ifcProductObject, String material)
        throws RenderEngineException, SerializerException {
    // Mostly just skips IfcOpeningElements which one would probably not want to end up in the Collada file.
    if (ifcProductObject instanceof IfcFeatureElementSubtraction)
        return;/*from  w  w  w.java 2 s .  c  o  m*/
    //
    GeometryInfo geometryInfo = ifcProductObject.getGeometry();
    if (geometryInfo != null && geometryInfo.getTransformation() != null) {
        GeometryData geometryData = geometryInfo.getData();
        ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
        indicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // TODO: In Blender (3d modeling tool) and Three.js, normals are ignored in favor of vertex order. The incoming geometry seems to be in order 0 1 2 when it needs to be in 1 0 2. Need more test cases.
        // Failing order: (0, 1050, 2800), (0, 1050, 3100), (3580, 1050, 3100)
        // Successful order: (0, 1050, 3100), (0, 1050, 2800), (3580, 1050, 3100)
        List<Integer> list = new ArrayList<Integer>();
        while (indicesBuffer.hasRemaining())
            list.add(indicesBuffer.getInt());
        indicesBuffer.rewind();
        for (int i = 0; i < list.size(); i += 3) {
            Integer first = list.get(i);
            Integer next = list.get(i + 1);
            list.set(i, next);
            list.set(i + 1, first);
        }
        // Positions the X or the Y or the Z of (X, Y, Z).
        ByteBuffer positionsBuffer = ByteBuffer.wrap(geometryData.getVertices());
        positionsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Do pass to find highest Z for considered objects.
        while (positionsBuffer.hasRemaining()) {
            float x = positionsBuffer.getFloat();
            float y = positionsBuffer.getFloat();
            float z = positionsBuffer.getFloat();
            // X
            if (x > highestObserved.x())
                highestObserved.x(x);
            else if (x < lowestObserved.x())
                lowestObserved.x(x);
            // Y
            if (y > highestObserved.y())
                highestObserved.y(y);
            else if (y < lowestObserved.y())
                lowestObserved.y(y);
            // Z
            if (z > highestObserved.z())
                highestObserved.z(z);
            else if (z < lowestObserved.z())
                lowestObserved.z(z);
        }
        positionsBuffer.rewind();
        //
        ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
        normalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Create a geometry identification number in the form of: geom-320450
        long oid = ifcProductObject.getOid();
        String id = String.format("geom-%d", oid);
        // If the material doesn't exist in the converted map, add it.
        if (!converted.containsKey(material))
            converted.put(material, new HashSet<IfcProduct>());
        // Add the current IfcProduct to the appropriate entry in the material map.
        converted.get(material).add(ifcProductObject);
        // Name for geometry.
        String name = (ifcProductObject.getGlobalId() == null) ? "[NO_GUID]" : ifcProductObject.getGlobalId();
        // Counts.
        int vertexComponentsTotal = positionsBuffer.capacity() / 4,
                normalComponentsTotal = normalsBuffer.capacity() / 4;
        int verticesCount = positionsBuffer.capacity() / 12, normalsCount = normalsBuffer.capacity() / 12,
                triangleCount = indicesBuffer.capacity() / 12;
        // Vertex scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringPositionScalars = byteBufferToFloatingPointSpaceDelimitedString(positionsBuffer);
        // Normal scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringNormalScalars = byteBufferToFloatingPointSpaceDelimitedString(normalsBuffer); //doubleBufferToFloatingPointSpaceDelimitedString(flippedNormalsBuffer);
        // Vertex indices as one long string: 1 0 2 0 3 2 5 4 6
        String stringIndexScalars = listToSpaceDelimitedString(list, intFormat);
        // Write geometry block for this IfcProduct (i.e. IfcRoof, IfcSlab, etc).
        out.println(" <geometry id=\"" + id + "\" name=\"" + name + "\">");
        out.println("  <mesh>");
        out.println("   <source id=\"positions-" + oid + "\" name=\"positions-" + oid + "\">");
        out.println("    <float_array id=\"positions-array-" + oid + "\" count=\"" + vertexComponentsTotal
                + "\">" + stringPositionScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + verticesCount + "\" offset=\"0\" source=\"#positions-array-"
                + oid + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <source id=\"normals-" + oid + "\" name=\"normals-" + oid + "\">");
        out.println("    <float_array id=\"normals-array-" + oid + "\" count=\"" + normalComponentsTotal + "\">"
                + stringNormalScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + normalsCount + "\" offset=\"0\" source=\"#normals-array-" + oid
                + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <vertices id=\"vertices-" + oid + "\">");
        out.println("    <input semantic=\"POSITION\" source=\"#positions-" + oid + "\"/>");
        out.println("    <input semantic=\"NORMAL\" source=\"#normals-" + oid + "\"/>");
        out.println("   </vertices>");
        out.println("   <triangles count=\"" + triangleCount + "\" material=\"Material-" + oid + "\">");
        out.println("    <input offset=\"0\" semantic=\"VERTEX\" source=\"#vertices-" + oid + "\"/>");
        out.println("    <p>" + stringIndexScalars + "</p>");
        out.println("   </triangles>");
        out.println("  </mesh>");
        out.println(" </geometry>");
    }
}

From source file:au.org.ala.delta.intkey.model.IntkeyDatasetFileReader.java

/**
 * Read a list of floating-point values from the current pointer location in
 * the supplied binary file/*from   w  w w. ja v a2s.  co  m*/
 * 
 * @param bFile
 *            the binary (characters or taxa) file
 * @param numFloats
 *            the number of floating point values to read
 * @return the list of floating point values
 */
private static List<Float> readFloatList(BinFile bFile, int numFloats) {
    ByteBuffer bb = bFile.readByteBuffer(numFloats * Constants.SIZE_INT_IN_BYTES);

    List<Float> retList = new ArrayList<Float>();
    for (int i = 0; i < numFloats; i++) {
        retList.add(bb.getFloat());
    }
    return retList;
}

From source file:org.wso2.carbon.analytics.data.commons.utils.AnalyticsCommonUtils.java

public static Map<String, Object> decodeRecordValues(byte[] data, Set<String> columns)
        throws AnalyticsException {
    /* using LinkedHashMap to retain the column order */
    Map<String, Object> result = new LinkedHashMap<>();
    int type, size;
    String colName;// w  w w  .  j  a va  2 s  .  co m
    Object value;
    byte[] buff;
    byte boolVal;
    byte[] binData;
    try {
        ByteBuffer buffer = ByteBuffer.wrap(data);
        while (buffer.remaining() > 0) {
            size = buffer.getInt();
            if (size == 0) {
                break;
            }
            buff = new byte[size];
            buffer.get(buff, 0, size);
            colName = new String(buff, StandardCharsets.UTF_8);
            type = buffer.get();
            switch (type) {
            case DATA_TYPE_STRING:
                size = buffer.getInt();
                buff = new byte[size];
                buffer.get(buff, 0, size);
                value = new String(buff, StandardCharsets.UTF_8);
                break;
            case DATA_TYPE_LONG:
                value = buffer.getLong();
                break;
            case DATA_TYPE_DOUBLE:
                value = buffer.getDouble();
                break;
            case DATA_TYPE_BOOLEAN:
                boolVal = buffer.get();
                if (boolVal == BOOLEAN_TRUE) {
                    value = true;
                } else if (boolVal == BOOLEAN_FALSE) {
                    value = false;
                } else {
                    throw new AnalyticsException("Invalid encoded boolean value: " + boolVal);
                }
                break;
            case DATA_TYPE_INTEGER:
                value = buffer.getInt();
                break;
            case DATA_TYPE_FLOAT:
                value = buffer.getFloat();
                break;
            case DATA_TYPE_BINARY:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = binData;
                break;
            case DATA_TYPE_OBJECT:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = deserializeObject(binData);
                break;
            case DATA_TYPE_NULL:
                value = null;
                break;
            default:
                throw new AnalyticsException("Unknown encoded data source type : " + type);
            }
            if (columns == null || columns.contains(colName)) {
                result.put(colName, value);
            }
        }
    } catch (Exception e) {
        throw new AnalyticsException("Error in decoding record values: " + e.getMessage(), e);
    }
    return result;
}

From source file:org.wso2.carbon.analytics.datasource.core.util.GenericUtils.java

public static Map<String, Object> decodeRecordValues(byte[] data, Set<String> columns)
        throws AnalyticsException {
    /* using LinkedHashMap to retain the column order */
    Map<String, Object> result = new LinkedHashMap<>();
    int type, size;
    String colName;//www .ja v  a  2  s  . c o m
    Object value;
    byte[] buff;
    byte boolVal;
    byte[] binData;
    try {
        ByteBuffer buffer = ByteBuffer.wrap(data);
        while (buffer.remaining() > 0) {
            size = buffer.getInt();
            if (size == 0) {
                break;
            }
            buff = new byte[size];
            buffer.get(buff, 0, size);
            colName = new String(buff, StandardCharsets.UTF_8);
            type = buffer.get();
            switch (type) {
            case DATA_TYPE_STRING:
                size = buffer.getInt();
                buff = new byte[size];
                buffer.get(buff, 0, size);
                value = new String(buff, StandardCharsets.UTF_8);
                break;
            case DATA_TYPE_LONG:
                value = buffer.getLong();
                break;
            case DATA_TYPE_DOUBLE:
                value = buffer.getDouble();
                break;
            case DATA_TYPE_BOOLEAN:
                boolVal = buffer.get();
                if (boolVal == BOOLEAN_TRUE) {
                    value = true;
                } else if (boolVal == BOOLEAN_FALSE) {
                    value = false;
                } else {
                    throw new AnalyticsException("Invalid encoded boolean value: " + boolVal);
                }
                break;
            case DATA_TYPE_INTEGER:
                value = buffer.getInt();
                break;
            case DATA_TYPE_FLOAT:
                value = buffer.getFloat();
                break;
            case DATA_TYPE_BINARY:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = binData;
                break;
            case DATA_TYPE_OBJECT:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = GenericUtils.deserializeObject(binData);
                break;
            case DATA_TYPE_NULL:
                value = null;
                break;
            default:
                throw new AnalyticsException("Unknown encoded data source type : " + type);
            }
            if (columns == null || columns.contains(colName)) {
                result.put(colName, value);
            }
        }
    } catch (Exception e) {
        throw new AnalyticsException("Error in decoding record values: " + e.getMessage(), e);
    }
    return result;
}

From source file:hivemall.recommend.SlimUDTF.java

private void replayTrain(@Nonnull final ByteBuffer buf) {
    final int itemI = buf.getInt();
    final int knnSize = buf.getInt();

    final Int2ObjectMap<Int2FloatMap> knnItems = new Int2ObjectOpenHashMap<>(1024);
    final IntSet pairItems = new IntOpenHashSet();
    for (int i = 0; i < knnSize; i++) {
        int user = buf.getInt();
        int ruSize = buf.getInt();
        Int2FloatMap ru = new Int2FloatOpenHashMap(ruSize);
        ru.defaultReturnValue(0.f);/* w w w .jav  a 2  s. c  o m*/

        for (int j = 0; j < ruSize; j++) {
            int itemK = buf.getInt();
            pairItems.add(itemK);
            float ruk = buf.getFloat();
            ru.put(itemK, ruk);
        }
        knnItems.put(user, ru);
    }

    for (int itemJ : pairItems) {
        train(itemI, knnItems, itemJ);
    }
}