Example usage for java.nio DoubleBuffer get

List of usage examples for java.nio DoubleBuffer get

Introduction

In this page you can find the example usage for java.nio DoubleBuffer get.

Prototype

public abstract double get(int index);

Source Link

Document

Returns a double at the specified index; the position is not changed.

Usage

From source file:org.bimserver.geometry.StreamingGeometryGenerator.java

private ByteBuffer quantizeVertices(DoubleBuffer vertices, double[] quantizationMatrix, double multiplierToMm) {
    ByteBuffer quantizedBuffer = ByteBuffer.wrap(new byte[vertices.capacity() * 2]);
    quantizedBuffer.order(ByteOrder.LITTLE_ENDIAN);

    double[] vertex = new double[4];
    double[] result = new double[4];
    vertex[3] = 1;//from  ww  w .  ja  v a  2  s.  c om
    int nrVertices = vertices.capacity();
    for (int i = 0; i < nrVertices; i += 3) {
        vertex[0] = vertices.get(i);
        vertex[1] = vertices.get(i + 1);
        vertex[2] = vertices.get(i + 2);

        if (multiplierToMm != 1f) {
            vertex[0] = vertex[0] * multiplierToMm;
            vertex[1] = vertex[1] * multiplierToMm;
            vertex[2] = vertex[2] * multiplierToMm;
        }

        Matrix.multiplyMV(result, 0, quantizationMatrix, 0, vertex, 0);

        quantizedBuffer.putShort((short) result[0]);
        quantizedBuffer.putShort((short) result[1]);
        quantizedBuffer.putShort((short) result[2]);
    }

    return quantizedBuffer;
}

From source file:org.bimserver.geometry.StreamingGeometryGenerator.java

void processExtendsUntranslated(VirtualObject geometryInfo, DoubleBuffer vertices, int index,
        GenerateGeometryResult generateGeometryResult) throws BimserverDatabaseException {
    double x = vertices.get(index);
    double y = vertices.get(index + 1);
    double z = vertices.get(index + 2);

    HashMapWrappedVirtualObject bounds = (HashMapWrappedVirtualObject) geometryInfo
            .eGet(GeometryPackage.eINSTANCE.getGeometryInfo_BoundsUntransformed());
    HashMapWrappedVirtualObject minBounds = (HashMapWrappedVirtualObject) bounds
            .eGet(GeometryPackage.eINSTANCE.getBounds_Min());
    HashMapWrappedVirtualObject maxBounds = (HashMapWrappedVirtualObject) bounds
            .eGet(GeometryPackage.eINSTANCE.getBounds_Max());

    minBounds.set("x", Math.min(x, (double) minBounds.eGet("x")));
    minBounds.set("y", Math.min(y, (double) minBounds.eGet("y")));
    minBounds.set("z", Math.min(z, (double) minBounds.eGet("z")));
    maxBounds.set("x", Math.max(x, (double) maxBounds.eGet("x")));
    maxBounds.set("y", Math.max(y, (double) maxBounds.eGet("y")));
    maxBounds.set("z", Math.max(z, (double) maxBounds.eGet("z")));

    generateGeometryResult.setUntranslatedMinX(Math.min(x, generateGeometryResult.getUntranslatedMinX()));
    generateGeometryResult.setUntranslatedMinY(Math.min(y, generateGeometryResult.getUntranslatedMinY()));
    generateGeometryResult.setUntranslatedMinZ(Math.min(z, generateGeometryResult.getUntranslatedMinZ()));
    generateGeometryResult.setUntranslatedMaxX(Math.max(x, generateGeometryResult.getUntranslatedMaxX()));
    generateGeometryResult.setUntranslatedMaxY(Math.max(y, generateGeometryResult.getUntranslatedMaxY()));
    generateGeometryResult.setUntranslatedMaxZ(Math.max(z, generateGeometryResult.getUntranslatedMaxZ()));
}

From source file:org.bimserver.geometry.StreamingGeometryGenerator.java

void processExtends(HashMapWrappedVirtualObject minBounds, HashMapWrappedVirtualObject maxBounds,
        double[] transformationMatrix, DoubleBuffer vertices, int index,
        GenerateGeometryResult generateGeometryResult) throws BimserverDatabaseException {
    double x = vertices.get(index);
    double y = vertices.get(index + 1);
    double z = vertices.get(index + 2);

    double[] result = new double[4];

    Matrix.multiplyMV(result, 0, transformationMatrix, 0, new double[] { x, y, z, 1 }, 0);
    x = result[0];//from w  w  w .  j a  v a 2s .  c  om
    y = result[1];
    z = result[2];

    minBounds.set("x", Math.min(x, (double) minBounds.eGet("x")));
    minBounds.set("y", Math.min(y, (double) minBounds.eGet("y")));
    minBounds.set("z", Math.min(z, (double) minBounds.eGet("z")));
    maxBounds.set("x", Math.max(x, (double) maxBounds.eGet("x")));
    maxBounds.set("y", Math.max(y, (double) maxBounds.eGet("y")));
    maxBounds.set("z", Math.max(z, (double) maxBounds.eGet("z")));

    generateGeometryResult.setMinX(Math.min(x, generateGeometryResult.getMinX()));
    generateGeometryResult.setMinY(Math.min(y, generateGeometryResult.getMinY()));
    generateGeometryResult.setMinZ(Math.min(z, generateGeometryResult.getMinZ()));
    generateGeometryResult.setMaxX(Math.max(x, generateGeometryResult.getMaxX()));
    generateGeometryResult.setMaxY(Math.max(y, generateGeometryResult.getMaxY()));
    generateGeometryResult.setMaxZ(Math.max(z, generateGeometryResult.getMaxZ()));
}

From source file:org.geotools.imageio.netcdf.NetCDFImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *///  ww w  . ja va 2s .c o  m
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final Slice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final VariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);

    // Flipping is needed only when the input latitude coordinate is ordered
    // from min to max
    if (needsFlipping) {
        flipVertically(param, height, srcRegion);
    }
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.geotools.imageio.unidata.UnidataImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *//* w  w w.jav a 2s  . c o  m*/
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final UnidataSlice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final UnidataVariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);
    flipVertically(param, height, srcRegion);
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.mitre.math.linear.BufferRealMatrix.java

/**
 * Gets a submatrix. Rows and columns are indicated
 * counting from 0 to n-1.//from w  ww.  j av  a 2s .  com
 *
 * @param startRow Initial row index
 * @param endRow Final row index (inclusive)
 * @param startColumn Initial column index
 * @param endColumn Final column index (inclusive)
 * @return The subMatrix containing the data of the
 *         specified rows and columns
 * @exception MatrixIndexException  if the indices are not valid
 */
public double[][] getSubMatrixData(final int startRow, final int endRow, final int startColumn,
        final int endColumn) throws MatrixIndexException {

    // safety checks
    MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);

    // create the output matrix
    final double[][] out = new double[endRow - startRow + 1][endColumn - startColumn + 1];

    // compute blocks shifts
    final int blockStartRow = startRow / BLOCK_SIZE;
    final int blockEndRow = endRow / BLOCK_SIZE;
    final int blockStartColumn = startColumn / BLOCK_SIZE;
    final int blockEndColumn = endColumn / BLOCK_SIZE;

    // perform extraction block-wise, to ensure good cache behavior
    for (int iBlock = blockStartRow; iBlock <= blockEndRow; ++iBlock) {
        for (int jBlock = blockStartColumn; jBlock <= blockEndColumn; ++jBlock) {
            // blocks are rows major order
            final int blockIndex = iBlock * this.blockColumns + jBlock;
            try {
                final long blockOffset = this.getBlockOffset(blockIndex);
                final DoubleBuffer block = this.dataFileChannel
                        .map(FileChannel.MapMode.READ_WRITE, blockOffset, BLOCK_BYTE_SIZE).asDoubleBuffer();
                block.clear();
                final int iStart = Math.max(startRow, iBlock * BLOCK_SIZE);
                final int iEnd = Math.min(endRow, (iBlock * BLOCK_SIZE) + BLOCK_SIZE);
                final int jStart = Math.max(startColumn, jBlock * BLOCK_SIZE);
                final int jEnd = Math.min(endColumn, (jBlock * BLOCK_SIZE) + BLOCK_SIZE);

                LOG.info(String.format("blockIndex=%d (%d, %d), iStart=%d, iEnd=%d, jStart=%d, jEnd=%d",
                        blockIndex, jBlock, iBlock, iStart, iEnd, jStart, jEnd));
                for (int i = iStart; i < iEnd; ++i) {
                    for (int j = jStart; j < jEnd; ++j) {
                        // data in blocks are rows major, get our index in the block
                        final int index = (i - iBlock * BLOCK_SIZE) * BLOCK_SIZE + (j - jBlock * BLOCK_SIZE);
                        out[i - startRow][j - startColumn] = block.get(index);
                    }
                }
            } catch (IOException ioe) {
                throw new MathRuntimeException(
                        "IO Exception while visiting blockIndex {0} (iBlock={1}, jBlock={2})", blockIndex,
                        iBlock, jBlock);
            }
        }
    }
    return out;
}

From source file:org.mitre.math.linear.BufferRealMatrix.java

/** {@inheritDoc} */
@Override//from ww w.j a  va  2s. co m
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) throws MatrixVisitorException {
    visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
    for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
        final int pStart = iBlock * BLOCK_SIZE;
        final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);

        for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
            try {
                final int qStart = jBlock * BLOCK_SIZE;
                final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);

                final long blockOffset = this.getBlockOffset(blockIndex);
                LOG.debug(String.format("BlockIndex=%d (offset=%d) pStart=%d pEnd=%d qStart=%d qEnd=%d",
                        blockIndex, blockOffset, pStart, pEnd, qStart, qEnd));

                final DoubleBuffer block = this.dataFileChannel
                        .map(FileChannel.MapMode.READ_WRITE, blockOffset, BLOCK_BYTE_SIZE).asDoubleBuffer();
                block.clear();

                for (int p = pStart, k = 0; p < pEnd; ++p) {
                    // jump to end of row incase we are not there
                    k = (p - pStart) * BLOCK_SIZE;
                    for (int q = qStart; q < qEnd; ++q, ++k) {
                        block.put(k, visitor.visit(p, q, block.get(k)));
                    }
                }
                this.dataFileChannel.force(false);
            } catch (IOException ioe) {
                throw new MathRuntimeException(
                        "IO Exception while visiting blockIndex {0} (iBlock={1}, jBlock={2})", blockIndex,
                        iBlock, jBlock);
            }
        }
    }
    return visitor.end();
}

From source file:org.mitre.math.linear.BufferRealMatrix.java

/** {@inheritDoc} */
@Override//from  ww w.java 2s.  co  m
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) throws MatrixVisitorException {
    visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
    for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
        final int pStart = iBlock * BLOCK_SIZE;
        final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);

        for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
            try {
                final int qStart = jBlock * BLOCK_SIZE;
                final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);

                final long blockOffset = this.getBlockOffset(blockIndex);
                final DoubleBuffer block = this.dataFileChannel
                        .map(FileChannel.MapMode.READ_WRITE, blockOffset, BLOCK_BYTE_SIZE).asDoubleBuffer();
                block.clear();

                LOG.debug(String.format("BlockIndex=%d pStart=%d pEnd=%d qStart=%d qEnd=%d", blockIndex, pStart,
                        pEnd, qStart, qEnd));
                for (int p = pStart, k = 0; p < pEnd; ++p) {
                    // jump to end of row incase we are not there
                    k = (p - pStart) * BLOCK_SIZE;
                    for (int q = qStart; q < qEnd; ++q, ++k) {
                        visitor.visit(p, q, block.get(k));
                    }
                }

                this.dataFileChannel.force(false);
            } catch (IOException ioe) {
                throw new MathRuntimeException(
                        "IO Exception while visiting blockIndex {0} (iBlock={1}, jBlock={2})", blockIndex,
                        iBlock, jBlock);
            }
        }
    }
    return visitor.end();
}

From source file:org.mrgeo.data.raster.RasterWritable.java

private static Raster read(final byte[] rasterBytes, Writable payload) throws IOException {
    WritableRaster raster;/*  w  ww  . jav a 2  s.com*/

    final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes);

    @SuppressWarnings("unused")
    final int headersize = rasterBuffer.getInt(); // this isn't really used anymore...
    final int height = rasterBuffer.getInt();
    final int width = rasterBuffer.getInt();
    final int bands = rasterBuffer.getInt();
    final int datatype = rasterBuffer.getInt();
    final SampleModelType sampleModelType = SampleModelType.values()[rasterBuffer.getInt()];

    SampleModel model;
    switch (sampleModelType) {
    case BANDED:
        model = new BandedSampleModel(datatype, width, height, bands);
        break;
    case MULTIPIXELPACKED:
        throw new NotImplementedException("MultiPixelPackedSampleModel not implemented yet");
        // model = new MultiPixelPackedSampleModel(dataType, w, h, numberOfBits)
    case PIXELINTERLEAVED: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new PixelInterleavedSampleModel(datatype, width, height, pixelStride, scanlineStride,
                bandOffsets);
        break;
    }
    case SINGLEPIXELPACKED:
        throw new NotImplementedException("SinglePixelPackedSampleModel not implemented yet");
        // model = new SinglePixelPackedSampleModel(dataType, w, h, bitMasks);
    case COMPONENT: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new ComponentSampleModel(datatype, width, height, pixelStride, scanlineStride, bandOffsets);
        break;
    }
    default:
        throw new RasterWritableException("Unknown RasterSampleModel type");
    }

    // include the header size param in the count
    int startdata = rasterBuffer.position();

    // calculate the data size
    int[] samplesize = model.getSampleSize();
    int samplebytes = 0;
    for (int ss : samplesize) {
        // bits to bytes
        samplebytes += (ss / 8);
    }
    int databytes = model.getHeight() * model.getWidth() * samplebytes;

    // final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes, headerbytes, databytes);
    // the corner of the raster is always 0,0
    raster = Raster.createWritableRaster(model, null);

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        // we can't use the byte buffer explicitly because the header info is
        // still in it...
        final byte[] bytedata = new byte[databytes];
        rasterBuffer.get(bytedata);

        raster.setDataElements(0, 0, width, height, bytedata);
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final FloatBuffer floatbuff = rasterBuffer.asFloatBuffer();
        final float[] floatdata = new float[databytes / RasterUtils.FLOAT_BYTES];

        floatbuff.get(floatdata);

        raster.setDataElements(0, 0, width, height, floatdata);
        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final DoubleBuffer doublebuff = rasterBuffer.asDoubleBuffer();
        final double[] doubledata = new double[databytes / RasterUtils.DOUBLE_BYTES];

        doublebuff.get(doubledata);

        raster.setDataElements(0, 0, width, height, doubledata);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final IntBuffer intbuff = rasterBuffer.asIntBuffer();
        final int[] intdata = new int[databytes / RasterUtils.INT_BYTES];

        intbuff.get(intdata);

        raster.setDataElements(0, 0, width, height, intdata);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final ShortBuffer shortbuff = rasterBuffer.asShortBuffer();
        final short[] shortdata = new short[databytes / RasterUtils.SHORT_BYTES];
        shortbuff.get(shortdata);
        raster.setDataElements(0, 0, width, height, shortdata);
        break;
    }
    default:
        throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
    }

    // should we even try to extract the payload?
    if (payload != null) {
        // test to see if this is a raster with a possible payload
        final int payloadStart = startdata + databytes;
        if (rasterBytes.length > payloadStart) {
            // extract the payload
            final ByteArrayInputStream bais = new ByteArrayInputStream(rasterBytes, payloadStart,
                    rasterBytes.length - payloadStart);
            final DataInputStream dis = new DataInputStream(bais);
            payload.readFields(dis);
        }
    }
    return raster;
}

From source file:ubic.basecode.io.ByteArrayConverter.java

/**
 * @param barray//from  w ww . j a  v  a  2s  .c  om
 * @return double[]
 */
public double[] byteArrayToDoubles(byte[] barray) {
    if (barray == null)
        return null;

    DoubleBuffer buf = ByteBuffer.wrap(barray).asDoubleBuffer();
    double[] array = new double[buf.remaining()];
    buf.get(array);

    return array;

}