Example usage for java.nio ByteBuffer asDoubleBuffer

List of usage examples for java.nio ByteBuffer asDoubleBuffer

Introduction

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

Prototype

public abstract DoubleBuffer asDoubleBuffer();

Source Link

Document

Returns a double buffer which is based on the remaining content of this byte buffer.

Usage

From source file:Main.java

public static DoubleBuffer newDoubleBuffer(int numDoubles) {
    ByteBuffer buffer = ByteBuffer.allocateDirect(numDoubles * 8);
    buffer.order(ByteOrder.nativeOrder());
    return buffer.asDoubleBuffer();
}

From source file:ffx.numerics.fft.Complex3DCuda.java

/**
 * {@inheritDoc}/*from   w ww  .  jav a2  s .co m*/
 */
@Override
public void run() {
    JCudaDriver.setExceptionsEnabled(true);
    JCufft.setExceptionsEnabled(true);
    JCudaDriver.setLogLevel(LogLevel.LOG_INFO);
    JCufft.setLogLevel(LogLevel.LOG_INFO);
    JCufft.initialize();

    // Initialize the driver and create a context for the first device.
    cuInit(0);
    CUcontext pctx = new CUcontext();
    CUdevice dev = new CUdevice();
    CUdevprop prop = new CUdevprop();
    cuDeviceGetProperties(prop, dev);
    logger.log(Level.INFO, "   CUDA {0}", prop.toFormattedString());
    cuDeviceGet(dev, 0);

    // Create a context that allows the GPU to map pinned host memory.
    if (usePinnedMemory) {
        cuCtxCreate(pctx, CUctx_flags.CU_CTX_MAP_HOST, dev);
    } else {
        // Create a context that does not allows the GPU to map pinned host memory.
        cuCtxCreate(pctx, 0, dev);
    }

    // Load the CUBIN file and obtain the "recipSummation" function.
    try {
        String bit = System.getProperty("sun.arch.data.model").trim();
        URL source = getClass().getClassLoader()
                .getResource("ffx/numerics/fft/recipSummation-" + bit + ".cubin");
        File cubinFile = File.createTempFile("recipSummation", "cubin");
        FileUtils.copyURLToFile(source, cubinFile);
        module = new CUmodule();
        cuModuleLoad(module, cubinFile.getCanonicalPath());
        function = new CUfunction();
        cuModuleGetFunction(function, module, "recipSummation");
    } catch (Exception e) {
        String message = " Error loading the reciprocal summation kernel";
        logger.log(Level.SEVERE, message, e);
    }

    pinnedMemory = new Pointer();

    if (usePinnedMemory) {
        // Allocate pinned memory mapped into the GPU address space.
        cuMemHostAlloc(pinnedMemory, len * 2 * Sizeof.DOUBLE, CU_MEMHOSTALLOC_DEVICEMAP);
    } else {
        // Allocate memory
        cuMemHostAlloc(pinnedMemory, len * 2 * Sizeof.DOUBLE, 0);
    }

    ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, len * 2 * Sizeof.DOUBLE);
    byteBuffer.order(ByteOrder.nativeOrder());
    pinnedMemoryBuffer = byteBuffer.asDoubleBuffer();

    // Allocate a work array on the device.
    dataDevice = new CUdeviceptr();
    cuMemAlloc(dataDevice, len * 2 * Sizeof.DOUBLE);

    // Allocate memory on the device for the reciprocal space array.
    recipDevice = new CUdeviceptr();
    cuMemAlloc(recipDevice, len * Sizeof.DOUBLE);

    // Create and execute a JCufft plan for the data
    plan = new cufftHandle();

    cufftPlan3d(plan, nZ, nY, nX, cufftType.CUFFT_Z2Z);
    //cufftSetCompatibilityMode(plan, cufftCompatibility.CUFFT_COMPATIBILITY_FFTW_ALL);

    dataGPUPtr = Pointer.to(dataDevice);
    recipGPUPtr = Pointer.to(recipDevice);

    int threads = prop.maxThreadsPerBlock;
    int nBlocks = len / threads + (len % threads == 0 ? 0 : 1);
    int gridSize = (int) Math.floor(Math.sqrt(nBlocks)) + 1;

    logger.info(format("   CUDA thread initialized: %d threads per block", threads));
    logger.info(format("   Grid Size:                     (%3d,%3d,%3d)", gridSize, gridSize, 1));

    assert (gridSize * gridSize * threads >= len);

    synchronized (this) {
        while (!free) {
            if (mode != null) {
                switch (mode) {

                case RECIP:
                    cuMemcpyHtoD(recipDevice, recipCPUPtr, len * Sizeof.DOUBLE);
                    break;

                case FFT:
                    // Zero Copy
                    if (usePinnedMemory) {
                        cufftExecZ2Z(plan, pinnedMemory, pinnedMemory, CUFFT_FORWARD);
                    } else {
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_FORWARD);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;

                case CONVOLUTION:

                    if (usePinnedMemory) {
                        // Zero Copy
                        cufftExecZ2Z(plan, pinnedMemory, dataDevice, CUFFT_FORWARD);
                    } else {
                        // Copy data to device and run forward FFT.
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_FORWARD);
                    }

                    // Set up the execution parameters for the kernel
                    cuFuncSetBlockShape(function, threads, 1, 1);
                    int offset = 0;
                    offset = align(offset, Sizeof.POINTER);
                    cuParamSetv(function, offset, dataGPUPtr, Sizeof.POINTER);
                    offset += Sizeof.POINTER;
                    offset = align(offset, Sizeof.POINTER);
                    cuParamSetv(function, offset, recipGPUPtr, Sizeof.POINTER);
                    offset += Sizeof.POINTER;
                    offset = align(offset, Sizeof.INT);
                    cuParamSeti(function, offset, len);
                    offset += Sizeof.INT;
                    cuParamSetSize(function, offset);
                    // Call the kernel function.
                    cuLaunchGrid(function, gridSize, gridSize);
                    if (usePinnedMemory) {
                        // Zero Copy
                        cufftExecZ2Z(plan, dataDevice, pinnedMemory, CUFFT_INVERSE);
                    } else {
                        // Perform inverse FFT and copy memory back to the CPU.
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_INVERSE);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;

                case IFFT:
                    // Zero Copy
                    if (usePinnedMemory) {
                        cufftExecZ2Z(plan, pinnedMemory, pinnedMemory, CUFFT_INVERSE);
                    } else {
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_INVERSE);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;
                }

                // Block for the context's tasks to complete.
                cuCtxSynchronize();

                // Reset the mode to null and notify the calling thread.
                mode = null;
                notify();
            }
            // The CUDA thread will wait until it's notified again.
            try {
                wait();
            } catch (InterruptedException e) {
                logger.severe(e.toString());
            }
        }
        cufftDestroy(plan);
        cuMemFree(dataDevice);
        cuMemFree(recipDevice);
        cuMemFreeHost(pinnedMemory);
        dead = true;
        notify();
    }
    logger.info(" CUDA Thread Done!");
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * readDoubleData ---//from   w ww  .j av  a 2 s  .  c o m
 * <p>
 * Reads double precision floating point values in list mode in the DATA
 * segment and updates eventList with the integer values of the values.
 * </p>
 *
 * @param data
 *            <code>ByteBuffer</code> containing the DATA segment of the
 *            underlying file.
 */
private void readDoubleData(ByteBuffer data) {
    // Allocate the eventList
    eventList = new double[parameters][totalEvents];

    if (littleEndianP) {
        data.order(ByteOrder.LITTLE_ENDIAN);
    }

    // Convert the byte buffer into a double buffer - doesn't get any easier
    DoubleBuffer db = data.asDoubleBuffer();

    final int totalEvents = this.totalEvents;
    final int parameters = this.parameters;

    for (int i = 0; i < totalEvents; i++) {
        for (int j = 0; j < parameters; j++) {
            // Store the value into the array
            eventList[j][i] = db.get();
        }
    }
}

From source file:nitf.imageio.NITFReader.java

/**
 * Optimization to read the entire image in one fell swoop... This is most
 * likely the common use case for this codec, so we hope this optimization
 * will be helpful.//  www  .  j ava  2 s . c om
 * 
 * @param imageIndex
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param pixelSize
 * @param imRas
 * @throws IOException
 */
protected void readFullImage(int imageIndex, Rectangle destRegion, int sourceXSubsampling,
        int sourceYSubsampling, int[] bandOffsets, int pixelSize, WritableRaster imRas) throws IOException {
    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = destRegion.width;
        int numRows = destRegion.height;

        int nBands = subheader.getBandCount();

        /*
         * NOTE: This is a "fix" that will be removed once the underlying
         * NITRO library gets patched. Currently, if you make a request of a
         * single band, it doesn't matter which band you request - the data
         * from the first band will be returned regardless. This is
         * obviously wrong. To thwart this, we will read all bands, then
         * scale down what we return to the user based on their actual
         * request.
         */

        int[] requestBands = bandOffsets;
        /*
         * if (nBands != bandOffsets.length && bandOffsets.length == 1
         * && bandOffsets[0] != 0)
         * {
         * requestBands = new int[nBands];
         * for (int i = 0; i < nBands; ++i)
         * requestBands[i] = i;
         * }
         */

        int bufSize = numCols * numRows * pixelSize;
        byte[][] imageBuf = new byte[requestBands.length][bufSize];

        // make a SubWindow from the params
        // TODO may want to read by blocks or rows to make faster and more
        // memory efficient
        SubWindow window;
        window = new SubWindow();
        window.setNumBands(requestBands.length);
        window.setBandList(requestBands);
        window.setNumCols(numCols);
        window.setNumRows(numRows);
        window.setStartCol(0);
        window.setStartRow(0);

        // the NITRO library can do the subsampling for us
        if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
            DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
            window.setDownSampler(downSampler);
        }

        // String pixelJustification = subheader.getPixelJustification()
        // .getStringData().trim();
        // boolean shouldSwap = pixelJustification.equals("R");

        // since this is Java, we need the data in big-endian format
        // boolean shouldSwap = ByteOrder.nativeOrder() !=
        // ByteOrder.BIG_ENDIAN;

        nitf.ImageReader imageReader = getImageReader(imageIndex);
        imageReader.read(window, imageBuf);

        List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();

        for (int i = 0; i < bandOffsets.length; ++i) {
            ByteBuffer bandBuf = null;

            // the special "fix" we added needs to do this
            if (bandOffsets.length != requestBands.length) {
                bandBuf = ByteBuffer.wrap(imageBuf[bandOffsets[i]]);
            } else {
                bandBuf = ByteBuffer.wrap(imageBuf[i]);
            }
            // ban dBuf.order(ByteOrder.nativeOrder());
            // shouldSwap ? ByteOrder.LITTLE_ENDIAN
            // : ByteOrder.BIG_ENDIAN);

            bandBufs.add(bandBuf);
        }

        // optimization for 1 band case... just dump the whole thing
        if (bandOffsets.length == 1) {
            ByteBuffer bandBuf = bandBufs.get(0);

            switch (pixelSize) {
            case 1:
                ByteBuffer rasterByteBuf = ByteBuffer.wrap(((DataBufferByte) imRas.getDataBuffer()).getData());
                rasterByteBuf.put(bandBuf);
                break;
            case 2:
                ShortBuffer rasterShortBuf = ShortBuffer
                        .wrap(((DataBufferUShort) imRas.getDataBuffer()).getData());
                rasterShortBuf.put(bandBuf.asShortBuffer());
                break;
            case 4:
                FloatBuffer rasterFloatBuf = FloatBuffer
                        .wrap(((DataBufferFloat) imRas.getDataBuffer()).getData());
                rasterFloatBuf.put(bandBuf.asFloatBuffer());
                break;
            case 8:
                DoubleBuffer rasterDoubleBuf = DoubleBuffer
                        .wrap(((DataBufferDouble) imRas.getDataBuffer()).getData());
                rasterDoubleBuf.put(bandBuf.asDoubleBuffer());
                break;
            }
        } else {
            // for multi-band case, we need to iterate over each pixel...
            // TODO -- optimize this!... somehow

            for (int srcY = 0, srcX = 0; srcY < numRows; srcY++) {
                // Copy each (subsampled) source pixel into imRas
                for (int dstX = 0; dstX < numCols; srcX += pixelSize, dstX++) {
                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(i);

                        switch (pixelSize) {
                        case 1:
                            imRas.setSample(dstX, srcY, i, bandBuf.get(srcX));
                            break;
                        case 2:
                            imRas.setSample(dstX, srcY, i, bandBuf.getShort(srcX));
                            break;
                        case 4:
                            imRas.setSample(dstX, srcY, i, bandBuf.getFloat(srcX));
                            break;
                        case 8:
                            imRas.setSample(dstX, srcY, i, bandBuf.getDouble(srcX));
                            break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(ExceptionUtils.getStackTrace(e1));
    }
}

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

void setTransformationMatrix(VirtualObject geometryInfo, double[] transformationMatrix)
        throws BimserverDatabaseException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 8);
    byteBuffer.order(ByteOrder.nativeOrder());
    DoubleBuffer asDoubleBuffer = byteBuffer.asDoubleBuffer();
    for (double d : transformationMatrix) {
        asDoubleBuffer.put(d);//from  w ww  .  ja v a 2s. c  o  m
    }
    geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Transformation(), byteBuffer.array());
}

From source file:org.bimserver.utils.BinUtils.java

public static byte[] doubleToByteArray(Double inDouble) {
    byte[] bArray = new byte[8];
    ByteBuffer bBuffer = ByteBuffer.wrap(bArray);
    DoubleBuffer lBuffer = bBuffer.asDoubleBuffer();
    lBuffer.put(inDouble);//  ww w . j ava2s . c  o  m
    return bArray;
}

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

/**
 * Returns the result of postmultiplying this by m.
 *
 * @param m    matrix to postmultiply by
 * @return     this * m/*from   ww w  . j  av  a  2 s .  c om*/
 * @throws     IllegalArgumentException
 *             if columnDimension(this) != rowDimension(m)
 */
public BufferRealMatrix multiply(final BufferRealMatrix b) throws IllegalArgumentException {

    // safety check
    MatrixUtils.checkMultiplicationCompatible(this, b);

    try {
        final BufferRealMatrix c = new BufferRealMatrix(rows, b.columns, null);
        // allocate one row for our matrix
        final ByteBuffer abb = ByteBuffer.allocate(BLOCK_SIZE * DOUBLE_BYTE_SIZE);
        // for some funny reason we can't get an array, even if we wrap it before! So, allocate it here and use latter
        //  final double[] ar = new double[BLOCK_SIZE]; This isn't faster

        // perform multiplication block-wise, to ensure good cache behavior
        int blockIndex = 0;
        for (int iBlock = 0; iBlock < c.blockRows; ++iBlock) {
            final int pStart = iBlock * BLOCK_SIZE;
            final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
            //System.err.printf("pStart=%d\tpEnd=%d\tblockRows=%d\tblockColumns=%d\n", pStart, pEnd, c.blockRows, c.blockColumns);
            for (int jBlock = 0; jBlock < c.blockColumns; ++jBlock) {
                final int jWidth = BLOCK_SIZE; // square block no matter what
                final int jWidth2 = jWidth + jWidth;
                final int jWidth3 = jWidth2 + jWidth;
                final int jWidth4 = jWidth3 + jWidth;

                // select current product block
                DoubleBuffer cdb = c.dataFileChannel
                        .map(FileChannel.MapMode.READ_WRITE, c.getBlockOffset(blockIndex), BLOCK_BYTE_SIZE)
                        .asDoubleBuffer();
                cdb.clear();

                // perform multiplication on current block
                for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
                    //final int kWidth = blockWidth(kBlock);
                    final int kWidth = BLOCK_SIZE;

                    LOG.debug(String.format("Getting a block %d and b block %d", iBlock * blockColumns + kBlock,
                            kBlock * b.blockColumns + jBlock));

                    // walk down the blocks columns
                    DoubleBuffer bdb = b.dataFileChannel
                            .map(FileChannel.MapMode.READ_WRITE,
                                    b.getBlockOffset(kBlock * b.blockColumns + jBlock), BLOCK_BYTE_SIZE)
                            .asDoubleBuffer();
                    bdb.clear();

                    LOG.debug("Processing blocks");
                    for (int p = pStart, k = 0; p < pEnd; ++p) {
                        // a's width (# cols) is the same as b's height (# rows) and c's width
                        final int lStart = (p - pStart) * kWidth; // Square padded with zeros    
                        final int lEnd = blockWidth(kBlock); // Can stop at the last column in a's block
                        //System.err.printf("k=%d\tp=%d\tlstart=%d\tlend=%d\t\n", k, p, lStart, lEnd);
                        // For each row in a, multiple the columns in b
                        // Can stop at the last column in the c's block which should be the last column in b

                        // walk across A's blocks rows grabbing a row at a time
                        abb.clear();
                        this.dataFileChannel.position(this.getBlockOffset(iBlock * blockColumns + kBlock)
                                + (lStart * DOUBLE_BYTE_SIZE));
                        final int r = this.dataFileChannel.read(abb); // relative get into local bytebuffer
                        //System.err.printf("Got %d bytes (%d doubles) for %d block width\n", r, r / DOUBLE_BYTE_SIZE, kWidth);
                        if (r == -1) {
                            LOG.fatal("Unable to read in data");
                        }
                        abb.clear();
                        final DoubleBuffer adb = abb.asDoubleBuffer();
                        adb.clear();
                        // tried getting access to local copy (array) but it wasn't faster access

                        for (int nStart = 0; nStart < c.blockWidth(jBlock); ++nStart) {
                            double sum = 0;
                            int l = 0; // first column in this row
                            int n = nStart;
                            // do four at a time (why four?)
                            adb.position(l);

                            while (l < lEnd - 3) {
                                sum += adb.get() * bdb.get(n) + adb.get() * bdb.get(n + jWidth)
                                        + adb.get() * bdb.get(n + jWidth2) + adb.get() * bdb.get(n + jWidth3);
                                l += 4;
                                n += jWidth4;
                            }
                            while (l < lEnd) {
                                sum += adb.get() * bdb.get(n);
                                n += jWidth;
                                l++;
                            }
                            sum += cdb.get(k);
                            cdb.put(k++, sum);
                            //System.err.printf("k=%d\tn=%d\n", k, n);
                        }
                        // correct k for difference in blockWidth since we are always square
                        k = (p + 1) * BLOCK_SIZE;
                        //System.err.printf("end of p-loop (%d), k=%d\n", p, k);
                    }
                }
                this.dataFileChannel.force(false);
                System.err.printf("Finished block %d\n", blockIndex);
                // go to next block
                ++blockIndex;
            }
        }
        return c;
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex.getMessage());
    }
}

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

private static byte[] rasterToBytes(final Raster raster) {
    final int datatype = raster.getTransferType();

    byte[] pixels;

    final Object elements = raster.getDataElements(raster.getMinX(), raster.getMinY(), raster.getWidth(),
            raster.getHeight(), null);/*  w ww.j  av a  2 s. c  om*/

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        pixels = (byte[]) elements;
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final float[] floatElements = (float[]) elements;

        pixels = new byte[floatElements.length * RasterUtils.FLOAT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final FloatBuffer floatbuff = bytebuff.asFloatBuffer();
        floatbuff.put(floatElements);

        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final double[] doubleElements = (double[]) elements;

        pixels = new byte[doubleElements.length * RasterUtils.DOUBLE_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final DoubleBuffer doubleBuff = bytebuff.asDoubleBuffer();
        doubleBuff.put(doubleElements);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final int[] intElements = (int[]) elements;

        pixels = new byte[intElements.length * RasterUtils.INT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final IntBuffer intBuff = bytebuff.asIntBuffer();
        intBuff.put(intElements);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final short[] shortElements = (short[]) elements;

        pixels = new byte[shortElements.length * RasterUtils.SHORT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final ShortBuffer shortbuff = bytebuff.asShortBuffer();
        shortbuff.put(shortElements);

        break;
    }
    default:
        throw new RasterWritableException("Error trying to append raster.  Bad raster data type");
    }

    return pixels;
}

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

private static Raster read(final byte[] rasterBytes, Writable payload) throws IOException {
    WritableRaster raster;//from   w  w  w. ja  v a2 s  .  c  om

    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;
}