Java Code Examples for java.nio.DoubleBuffer

The following examples show how to use java.nio.DoubleBuffer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: java   Source File: DoubleNioDataBuffer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DoubleDataBuffer copyTo(DataBuffer<Double> dst, long size) {
  Validator.copyToArgs(this, dst, size);
  return dst.accept(new DataStorageVisitor<DoubleDataBuffer>() {

    @Override
    public DoubleDataBuffer visit(DoubleBuffer buffer) {
      buffer.duplicate().put((DoubleBuffer)buf.duplicate().limit((int)size));
      return DoubleNioDataBuffer.this;
    }

    @Override
    public DoubleDataBuffer fallback() {
      if (dst instanceof DoubleDataBuffer) {
        DoubleDataBuffer doubleDst = (DoubleDataBuffer)dst;
        for (long idx = 0L; idx < size; ++idx) {
          doubleDst.setDouble(getDouble(idx), idx);
        }
        return DoubleNioDataBuffer.this;
      }
      return slowCopyTo(dst, size);
    }
  });
}
 
Example 2
Source Project: openjdk-jdk9   Source File: ByteBufferViews.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "doubleViewProvider")
public void testDoubleGet(String desc, IntFunction<ByteBuffer> fbb,
                          Function<ByteBuffer, DoubleBuffer> fbi) {
    ByteBuffer bb = allocate(fbb);
    DoubleBuffer vb = fbi.apply(bb);
    int o = bb.position();

    for (int i = 0; i < vb.limit(); i++) {
        double fromBytes = getDoubleFromBytes(bb, o + i * 8);
        double fromMethodView = bb.getDouble(o + i * 8);
        assertValues(i, fromBytes, fromMethodView, bb);

        double fromBufferView = vb.get(i);
        assertValues(i, fromMethodView, fromBufferView, bb, vb);
    }

    for (int i = 0; i < vb.limit(); i++) {
        double v = getDoubleFromBytes(bb, o + i * 8);
        double a = bb.getDouble();
        assertValues(i, v, a, bb);

        double b = vb.get();
        assertValues(i, a, b, bb, vb);
    }

}
 
Example 3
Source Project: icafe   Source File: ArrayUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static double[] toDoubleArray(byte[] data, int offset, int len, boolean bigEndian) {
	
	ByteBuffer byteBuffer = ByteBuffer.wrap(data, offset, len);
	
	if (bigEndian) {
		byteBuffer.order(ByteOrder.BIG_ENDIAN);
	} else {
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
	}
	
	DoubleBuffer doubleBuf = byteBuffer.asDoubleBuffer();
	double[] array = new double[doubleBuf.remaining()];
	doubleBuf.get(array);
	
	return array;
}
 
Example 4
/**
 * Creates a new DoubleBuffer with the same contents as the given
 * DoubleBuffer. The new DoubleBuffer is separate from the old one and
 * changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the DoubleBuffer to copy
 * @return the copy
 */
public static DoubleBuffer clone(DoubleBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    DoubleBuffer copy;
    if (isDirect(buf)) {
        copy = createDoubleBuffer(buf.limit());
    } else {
        copy = DoubleBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
Example 5
Source Project: aion-germany   Source File: BufferUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Buffer clone(Buffer buf) {
	if (buf instanceof FloatBuffer) {
		return clone((FloatBuffer) buf);
	}
	else if (buf instanceof ShortBuffer) {
		return clone((ShortBuffer) buf);
	}
	else if (buf instanceof ByteBuffer) {
		return clone((ByteBuffer) buf);
	}
	else if (buf instanceof IntBuffer) {
		return clone((IntBuffer) buf);
	}
	else if (buf instanceof DoubleBuffer) {
		return clone((DoubleBuffer) buf);
	}
	else {
		throw new UnsupportedOperationException();
	}
}
 
Example 6
Source Project: OSPREY3   Source File: ForcefieldKernelCuda.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public double downloadEnergySync() {
	
	// make sure this thread can use the cuda context
	getStream().getContext().attachCurrentThread();
	
	energies.downloadSync();
	DoubleBuffer buf = energies.getHostBuffer();
	
	// do the last bit of the energy sum on the cpu
	// add one element per work group on the gpu
	// typically, it's a factor of groupSize less than the number of atom pairs
	double energy = subset.getInternalSolvationEnergy();
	buf.rewind();
	int n = getEnergySize(subset, func.blockThreads);
	for (int i=0; i<n; i++) {
		energy += buf.get();
	}
	return energy;
}
 
Example 7
Source Project: jogl-samples   Source File: Gl_410_program_64.java    License: MIT License 6 votes vote down vote up
private boolean initVertexBuffer(GL4 gl4) {

        ShortBuffer elementBuffer = GLBuffers.newDirectShortBuffer(elementData);
        DoubleBuffer positionBuffer = GLBuffers.newDirectDoubleBuffer(positionData);

        gl4.glGenBuffers(Buffer.MAX, bufferName);

        gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName.get(Buffer.ELEMENT));
        gl4.glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementSize, elementBuffer, GL_STATIC_DRAW);
        gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        gl4.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.F64));
        gl4.glBufferData(GL_ARRAY_BUFFER, positionSize, positionBuffer, GL_STATIC_DRAW);
        gl4.glBindBuffer(GL_ARRAY_BUFFER, 0);

        BufferUtils.destroyDirectBuffer(elementBuffer);
        BufferUtils.destroyDirectBuffer(elementBuffer);

        return checkError(gl4, "initArrayBuffer");
    }
 
Example 8
Source Project: jogl-samples   Source File: BufferUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a clone of the given buffer. The clone's capacity is 
 * equal to the given buffer's limit.
 * 
 * @param buf The buffer to clone
 * @return The cloned buffer
 */
public static Buffer clone(Buffer buf) {
    if (buf instanceof FloatBuffer) {
        return clone((FloatBuffer) buf);
    } else if (buf instanceof ShortBuffer) {
        return clone((ShortBuffer) buf);
    } else if (buf instanceof ByteBuffer) {
        return clone((ByteBuffer) buf);
    } else if (buf instanceof IntBuffer) {
        return clone((IntBuffer) buf);
    } else if (buf instanceof DoubleBuffer) {
        return clone((DoubleBuffer) buf);
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example 9
Source Project: libcommon   Source File: ChannelHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ByteChannelからdouble配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static double[] readDoubleArray(@NonNull final ByteChannel channel)
	throws IOException {
	
	final int n = readInt(channel);
	final ByteBuffer buf = ByteBuffer.allocate(n * 8).order(ByteOrder.BIG_ENDIAN);
	final int readBytes = channel.read(buf);
	if (readBytes != n * 8) throw new IOException();
	buf.clear();
	final DoubleBuffer result = buf.asDoubleBuffer();
	if (result.hasArray()) {
		return result.array();
	}  else {
		final double[] b = new double[n];
		result.get(b);
		return b;
	}
}
 
Example 10
CdmrFeatureProto.CoordAxis.Builder encodeCoordAxis(CoverageCoordAxis axis) {
  CdmrFeatureProto.CoordAxis.Builder builder = CdmrFeatureProto.CoordAxis.newBuilder();
  builder.setName(axis.getName());
  builder.setDataType(NcStream.convertDataType(axis.getDataType()));
  builder.setAxisType(convertAxisType(axis.getAxisType()));
  builder.setNvalues(axis.getNcoords());
  if (axis.getUnits() != null)
    builder.setUnits(axis.getUnits());
  if (axis.getDescription() != null)
    builder.setDescription(axis.getDescription());
  builder.setDepend(convertDependenceType(axis.getDependenceType()));
  for (String s : axis.getDependsOnList())
    builder.addDependsOn(s);

  if (axis instanceof LatLonAxis2D) {
    LatLonAxis2D latlon2D = (LatLonAxis2D) axis;
    for (int shape : latlon2D.getShape())
      builder.addShape(shape);
  }

  for (Attribute att : axis.getAttributes())
    builder.addAtts(NcStream.encodeAtt(att));

  builder.setSpacing(convertSpacing(axis.getSpacing()));
  builder.setStartValue(axis.getStartValue());
  builder.setEndValue(axis.getEndValue());
  builder.setResolution(axis.getResolution());

  if (!axis.isRegular() && axis.getNcoords() < MAX_INLINE_NVALUES) {
    double[] values = axis.getValues();
    ByteBuffer bb = ByteBuffer.allocate(8 * values.length);
    DoubleBuffer db = bb.asDoubleBuffer();
    db.put(values);
    builder.setValues(ByteString.copyFrom(bb.array()));
  }

  return builder;
}
 
Example 11
Source Project: djl   Source File: MockNDArray.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void set(Buffer data) {
    int size = data.remaining();
    // int8, uint8, boolean use ByteBuffer, so need to explicitly input DataType
    DataType inputType = DataType.fromBuffer(data);

    int numOfBytes = inputType.getNumOfBytes();
    this.data = ByteBuffer.allocate(size * numOfBytes);

    switch (inputType) {
        case FLOAT32:
            this.data.asFloatBuffer().put((FloatBuffer) data);
            break;
        case FLOAT64:
            this.data.asDoubleBuffer().put((DoubleBuffer) data);
            break;
        case INT8:
            this.data.put((ByteBuffer) data);
            break;
        case INT32:
            this.data.asIntBuffer().put((IntBuffer) data);
            break;
        case INT64:
            this.data.asLongBuffer().put((LongBuffer) data);
            break;
        case UINT8:
        case FLOAT16:
        default:
            throw new AssertionError("Show never happen");
    }
}
 
Example 12
Source Project: java   Source File: DataBuffers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a buffer of doubles that can store up to {@code size} values
 *
 * @param size size of the buffer to allocate
 * @return a new buffer
 */
public static DoubleDataBuffer ofDoubles(long size) {
  Validator.createArgs(size, MAX_32BITS);
  if (RawDataBufferFactory.canBeUsed()) {
    return RawDataBufferFactory.create(new double[(int)size], false);
  }
  return NioDataBufferFactory.create(DoubleBuffer.allocate((int)size));
}
 
Example 13
Source Project: datacollector   Source File: DoubleTensorTypeSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<Field> createListField(Tensor<Double> tensor, DoubleBuffer doubleBuffer) {
  List<Field> fields = new ArrayList<>();
  tensor.writeTo(doubleBuffer);
  double[] doubles = doubleBuffer.array();
  for (double aDouble : doubles) {
    fields.add(Field.create(aDouble));
  }
  return fields;
}
 
Example 14
Source Project: j2objc   Source File: BufferTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testDoubleBufferByteOrder(DoubleBuffer b, ByteOrder bo) throws Exception {
    assertEquals(bo, b.order());
    assertEquals(bo, b.duplicate().order());
    assertEquals(bo, b.slice().order());
    b = b.asReadOnlyBuffer();
    assertEquals(bo, b.order());
    assertEquals(bo, b.duplicate().order());
    assertEquals(bo, b.slice().order());
}
 
Example 15
@Override
public ByteBuffer getDataAsByteBuffer() {
    ByteBuffer bb = ByteBuffer.allocate((int) (8 * getSize()));
    DoubleBuffer ib = bb.asDoubleBuffer();
    ib.put((double[]) get1DJavaArray(double.class)); // make sure its in canonical order
    return bb;
}
 
Example 16
Source Project: OpenRTS   Source File: SilentTangentBinormalGenerator.java    License: MIT License 5 votes vote down vote up
private static void putValue(VertexBuffer.Format format, Buffer buf1, Buffer buf2, int index) {
	switch (format) {
		case Byte:
		case Half:
		case UnsignedByte:
			byte b = ((ByteBuffer) buf2).get(index);
			((ByteBuffer) buf1).put(b);
			break;
		case Short:
		case UnsignedShort:
			short s = ((ShortBuffer) buf2).get(index);
			((ShortBuffer) buf1).put(s);
			break;

		case Int:
		case UnsignedInt:
			int i = ((IntBuffer) buf2).get(index);
			((IntBuffer) buf1).put(i);
			break;
		case Float:
			float f = ((FloatBuffer) buf2).get(index);
			((FloatBuffer) buf1).put(f);
			break;
		case Double:
			double d = ((DoubleBuffer) buf2).get(index);
			((DoubleBuffer) buf1).put(d);
			break;
		default:
			throw new UnsupportedOperationException("Unrecoginized buffer format: " + format);
	}
}
 
Example 17
public static void declareDoubleArray(Jep jep, String variableName, DoubleBuffer buffer) throws JepException {
    jep.eval("from numpy import *");
    jep.eval("from ctypes import *");
    jep.eval("PyBuffer_FromMemory = pythonapi.PyBuffer_FromReadWriteMemory");
    jep.eval("PyBuffer_FromMemory.restype = py_object");
    jep.eval("PyBuffer_FromMemory.argtypes =[c_void_p, c_int32]");
    jep.eval(variableName + "=frombuffer(PyBuffer_FromMemory(" + getAddress(buffer) + ", " + buffer.limit() * 8 + "), float64)");
}
 
Example 18
Source Project: sis   Source File: JDK9.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Place holder for {@code Buffer.duplicate()}.
 *
 * @param  b the buffer to duplicate.
 * @return the duplicate buffer.
 */
public static Buffer duplicate(Buffer b) {
    if (b instanceof ByteBuffer)   return ((ByteBuffer) b).duplicate();
    if (b instanceof ShortBuffer)  return ((ShortBuffer) b).duplicate();
    if (b instanceof IntBuffer)    return ((IntBuffer) b).duplicate();
    if (b instanceof LongBuffer)   return ((LongBuffer) b).duplicate();
    if (b instanceof FloatBuffer)  return ((FloatBuffer) b).duplicate();
    if (b instanceof DoubleBuffer) return ((DoubleBuffer) b).duplicate();
    throw new IllegalArgumentException();
}
 
Example 19
public static byte[] doubleArrayToByteArray(double[] vertices) {
	if (vertices == null) {
		return null;
	}
	ByteBuffer buffer = ByteBuffer.wrap(new byte[vertices.length * 4]);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	DoubleBuffer asDoubleBuffer = buffer.asDoubleBuffer();
	for (double d : vertices) {
		asDoubleBuffer.put(d);
	}
	return buffer.array();
}
 
Example 20
Source Project: aion-germany   Source File: BufferUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new DoubleBuffer of the specified size.
 *
 * @param size
 *            required number of double to store.
 * @return the new DoubleBuffer
 */
public static DoubleBuffer createDoubleBuffer(int size) {
	DoubleBuffer buf = ByteBuffer.allocateDirect(8 * size).order(ByteOrder.nativeOrder()).asDoubleBuffer();
	buf.clear();
	if (trackDirectMemory) {
		trackingHash.put(buf, ref);
	}
	return buf;
}
 
Example 21
public static double[] toDoubleArray(byte[] data) {
	ByteBuffer buffer = ByteBuffer.wrap(data);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	DoubleBuffer doubleBuffer = buffer.asDoubleBuffer();
	double[] result = new double[data.length / 8];
	for (int i=0; i<data.length / 8; i++) {
		result[i] = doubleBuffer.get();
	}
	return result;
}
 
Example 22
@Override
public ColumnBinary toBinary(final ColumnBinaryMakerConfig commonConfig , final ColumnBinaryMakerCustomConfigNode currentConfigNode , final IColumn column ) throws IOException{
  ColumnBinaryMakerConfig currentConfig = commonConfig;
  if( currentConfigNode != null ){
    currentConfig = currentConfigNode.getCurrentConfig();
  }
  byte[] binaryRaw = new byte[ getBinaryLength( column.size() ) ];
  ByteBuffer lengthBuffer = ByteBuffer.wrap( binaryRaw );
  lengthBuffer.putInt( column.size() );
  lengthBuffer.putInt( column.size() * Double.BYTES );

  ByteBuffer nullFlagBuffer = ByteBuffer.wrap( binaryRaw , Integer.BYTES * 2 , column.size() );
  DoubleBuffer doubleBuffer = ByteBuffer.wrap( binaryRaw , ( Integer.BYTES * 2 + column.size() ) , ( column.size() * Double.BYTES ) ).asDoubleBuffer();

  int rowCount = 0;
  for( int i = 0 ; i < column.size() ; i++ ){
    ICell cell = column.get(i);
    if( cell.getType() == ColumnType.NULL ){
      nullFlagBuffer.put( (byte)1 );
      doubleBuffer.put( (double)0 );
    }
    else{
      rowCount++;
      PrimitiveCell byteCell = (PrimitiveCell) cell;
      nullFlagBuffer.put( (byte)0 );
      doubleBuffer.put( byteCell.getRow().getDouble() );
    }
  }

  byte[] binary = currentConfig.compressorClass.compress( binaryRaw , 0 , binaryRaw.length );

  return new ColumnBinary( this.getClass().getName() , currentConfig.compressorClass.getClass().getName() , column.getColumnName() , ColumnType.DOUBLE , rowCount , binaryRaw.length , rowCount * Double.BYTES , -1 , binary , 0 , binary.length , null );
}
 
Example 23
private double getEnergy(CUBuffer<IntBuffer> indices) {
	
	// check broken-ness first. easy peasy
	if (isBroken) {
		return Double.POSITIVE_INFINITY;
	}
	
	// make sure this thread can use the cuda context
	getStream().getContext().attachCurrentThread();
	
	// capture the current molecule state
	DoubleBuffer coordsbuf = coords.getHostBuffer();
	coordsbuf.clear();
	for (Residue res : residues) {
		coordsbuf.put(res.coords);
	}
	coordsbuf.clear();
	coords.uploadAsync();
	
	// launch kernel
	func.setArgs(Pointer.to(
		coords.getDevicePointer(),
		data.getDevicePointer(),
		Pointer.to(new int[] { indices.getHostBuffer().limit() }),
		indices.getDevicePointer(),
		energy.getDevicePointer()
	));
	func.runAsync();
	
	// download the energy
	DoubleBuffer buf = energy.downloadSync();
	buf.rewind();
	return buf.get();
}
 
Example 24
Source Project: tapir   Source File: DoublePointer.java    License: MIT License 5 votes vote down vote up
/**
 * For direct buffers, calls {@link Pointer#Pointer(Buffer)}, while for buffers
 * backed with an array, allocates enough memory for the array and copies it.
 *
 * @param buffer the Buffer to reference or copy
 * @see #put(double[])
 */
public DoublePointer(DoubleBuffer buffer) {
    super(buffer);
    if (buffer != null && buffer.hasArray()) {
        double[] array = buffer.array();
        allocateArray(array.length);
        put(array);
        position(buffer.position());
        limit(buffer.limit());
    }
}
 
Example 25
Source Project: nd4j   Source File: BaseDataBuffer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DoubleBuffer asNioDouble() {
    if (offset() >= Integer.MAX_VALUE)
        throw new IllegalStateException("Index out of bounds " + offset());

    if (offset() == 0) {
        return wrappedBuffer().asDoubleBuffer();
    } else {
        return (DoubleBuffer) wrappedBuffer().asDoubleBuffer().position((int) (offset()));
    }
}
 
Example 26
Source Project: sis   Source File: ArrayVector.java    License: Apache License 2.0 4 votes vote down vote up
/** Wraps this vector in a buffer. */
@Override public Optional<Buffer> buffer() {
    return Optional.of(DoubleBuffer.wrap(array));
}
 
Example 27
Source Project: tess4j   Source File: TessAPIImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int TessBaseAPIGetDoubleVariable(ITessAPI.TessBaseAPI handle, String name, DoubleBuffer value) {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 28
Source Project: JOML   Source File: Matrix3d.java    License: MIT License 4 votes vote down vote up
public DoubleBuffer get(int index, DoubleBuffer buffer) {
    MemUtil.INSTANCE.put(this, index, buffer);
    return buffer;
}
 
Example 29
Source Project: JOML   Source File: Matrix2d.java    License: MIT License 4 votes vote down vote up
public DoubleBuffer getTransposed(DoubleBuffer buffer) {
    return get(buffer.position(), buffer);
}
 
Example 30
private Float64ArrayData(final DoubleBuffer nb, final int start, final int end) {
    super(((DoubleBuffer)nb.position(start).limit(end)).slice(), end - start);
}