Example usage for java.nio DoubleBuffer put

List of usage examples for java.nio DoubleBuffer put

Introduction

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

Prototype

public abstract DoubleBuffer put(int index, double d);

Source Link

Document

Write a double to the specified index of this buffer and the position is not changed.

Usage

From source file:Main.java

public static void main(String[] args) {
    DoubleBuffer bb = DoubleBuffer.allocate(BSIZE);

    bb.put(0, 98765);

    System.out.println(Arrays.toString(bb.array()));

}

From source file:MainClass.java

public static void main(String[] args) {
    long[] primes = new long[] { 1, 2, 3, 5, 7 };
    File aFile = new File("C:/test/primes.txt");
    FileOutputStream outputFile = null;
    try {//from   w ww  . java 2s  . c  o  m
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    DoubleBuffer doubleBuf = buf.asDoubleBuffer();
    buf.position(8);
    CharBuffer charBuf = buf.asCharBuffer();
    for (long prime : primes) {
        String primeStr = "prime = " + prime;
        doubleBuf.put(0, (double) primeStr.length());
        charBuf.put(primeStr);
        buf.position(2 * charBuf.position() + 8);
        LongBuffer longBuf = buf.asLongBuffer();
        longBuf.put(prime);
        buf.position(buf.position() + 8);
        buf.flip();
        try {
            file.write(buf);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        buf.clear();
        doubleBuf.clear();
        charBuf.clear();
    }
    try {
        System.out.println("File written is " + file.size() + "bytes.");
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

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

/**
 * <p>//from  www . j  a  va  2s  .  c o  m
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[1]);
            if (reps < 1) {
                reps = 10;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];
    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    int index = 0;
    for (int k = 0; k < dim; k++) {
        for (int j = 0; j < dim; j++) {
            for (int i = 0; i < dim; i++) {
                orig[index] = random.nextDouble();
                //recip[index] = orig[index];
                recip[index] = 1.0;
                index++;
            }
        }
    }

    Complex3D complex3D = new Complex3D(dim, dim, dim);
    Complex3DParallel complex3DParallel = new Complex3DParallel(dim, dim, dim, new ParallelTeam(),
            IntegerSchedule.fixed());
    complex3DParallel.setRecip(recip);

    Complex3DCuda complex3DCUDA = new Complex3DCuda(dim, dim, dim);
    Thread cudaThread = new Thread(complex3DCUDA);
    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();
    complex3DCUDA.setRecip(recip);

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3D.convolution(data);
        complex3D.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3DParallel.convolution(data);
        complex3DParallel.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));

    DoubleBuffer cudaBuffer = complex3DCUDA.getDoubleBuffer();
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            // data[j * 2] = orig[j];
            // data[j * 2 + 1] = 0.0;
            cudaBuffer.put(j * 2, orig[j]);
            cudaBuffer.put(j * 2 + 1, 0.0);
        }
        long time = System.nanoTime();
        //complex3DCUDA.convolution(data);
        complex3DCUDA.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - cudaBuffer.get(2 * i));
        // double error = Math.abs(answer[i] / dimCubed -  data[2 * i]);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

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  w ww  .  jav a  2s  .  c o  m
 * @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.mitre.math.linear.BufferRealMatrix.java

/** {@inheritDoc} */
@Override/*from   w w w  .  java2s  .  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:ummisco.gama.opengl.vaoGenerator.GeomMathUtils.java

static public DoubleBuffer getDoubleBuffer(final Matrix4d matrix) {
    final DoubleBuffer result = DoubleBuffer.allocate(16);
    result.put(0, matrix.m00);
    result.put(1, matrix.m01);/*from   w  ww  .j  av a  2  s . c  om*/
    result.put(2, matrix.m02);
    result.put(3, matrix.m03);
    result.put(4, matrix.m10);
    result.put(5, matrix.m11);
    result.put(6, matrix.m12);
    result.put(7, matrix.m13);
    result.put(8, matrix.m20);
    result.put(9, matrix.m21);
    result.put(10, matrix.m22);
    result.put(11, matrix.m23);
    result.put(12, matrix.m30);
    result.put(13, matrix.m31);
    result.put(14, matrix.m32);
    result.put(15, matrix.m33);
    return result;
}