java.nio.DoubleBuffer Java Examples

The following examples show how to use java.nio.DoubleBuffer. 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 File: ArrayUtils.java    From icafe with 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 #2
Source File: DoubleNioDataBuffer.java    From java with 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 #3
Source File: BufferUtils.java    From jogl-samples with 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 #4
Source File: BufferUtils.java    From aion-germany with 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 #5
Source File: ForcefieldKernelCuda.java    From OSPREY3 with 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 #6
Source File: BufferUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #7
Source File: ByteBufferViews.java    From openjdk-jdk9 with 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 #8
Source File: Gl_410_program_64.java    From jogl-samples with 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 #9
Source File: ChannelHelper.java    From libcommon with 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
Source File: BaseDataBuffer.java    From nd4j with 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 #11
Source File: GeometryUtils.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #12
Source File: BufferUtils.java    From aion-germany with 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 #13
Source File: MockNDArray.java    From djl with 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 #14
Source File: DataBuffers.java    From java with 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 #15
Source File: WflowPythonToJavaAdapter.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #16
Source File: CdmrfWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #17
Source File: DumpDoubleColumnBinaryMaker.java    From multiple-dimension-spread with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: GeometryUtils.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #19
Source File: JDK9.java    From sis with 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 #20
Source File: DoubleTensorTypeSupport.java    From datacollector with 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 #21
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with 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 #22
Source File: DoublePointer.java    From tapir with 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 #23
Source File: BufferTest.java    From j2objc with 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 #24
Source File: ResidueForcefieldEnergyCuda.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
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 #25
Source File: ArrayComplex.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: ForcefieldKernelOpenCL.java    From OSPREY3 with GNU General Public License v2.0 4 votes vote down vote up
public DoubleBuffer downloadCoordsSync() {
	coords.getBuffer().rewind();
	downloadBufferSync(coords);
	return coords.getBuffer();
}
 
Example #27
Source File: NativeFloat64Array.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
private Float64ArrayData(final DoubleBuffer nb, final int start, final int end) {
    super(((DoubleBuffer)nb.position(start).limit(end)).slice(), end - start);
}
 
Example #28
Source File: TensorConverter.java    From vespa with Apache License 2.0 4 votes vote down vote up
DoubleValues(org.tensorflow.Tensor<?> tfTensor) {
    super(tfTensor.numElements());
    values = DoubleBuffer.allocate(tfTensor.numElements());
    tfTensor.writeTo(values);
}
 
Example #29
Source File: DumpDoubleColumnBinaryMaker.java    From multiple-dimension-spread with Apache License 2.0 4 votes vote down vote up
public DoubleDicManager( final byte[] nullBuffer , final int nullBufferStart , final int nullBufferLength , final DoubleBuffer dicBuffer ){
  this.nullBuffer = nullBuffer;
  this.nullBufferStart = nullBufferStart;
  this.nullBufferLength = nullBufferLength;
  this.dicBuffer = dicBuffer;
}
 
Example #30
Source File: BufferTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testDoubleBufferByteOrderWrapped() throws Exception {
    assertEquals(ByteOrder.nativeOrder(), DoubleBuffer.wrap(new double[10]).order());
    assertEquals(ByteOrder.nativeOrder(), DoubleBuffer.wrap(new double[10]).asReadOnlyBuffer().order());
}