Added factories for Complex number buffers and nd-structures

This commit is contained in:
Alexander Nozik 2019-01-05 21:01:30 +03:00
parent 696a916ade
commit 798512517d
3 changed files with 22 additions and 5 deletions

View File

@ -1,6 +1,7 @@
package scientifik.kmath.structures
import scientifik.kmath.operations.Complex
import scientifik.kmath.operations.ComplexField
import java.nio.ByteBuffer
object ComplexBufferSpec : FixedSizeBufferSpec<Complex> {
@ -19,8 +20,18 @@ object ComplexBufferSpec : FixedSizeBufferSpec<Complex> {
}
/**
* Create a mutable buffer which ignores boxing
* Create a read-only/mutable buffer which ignores boxing
*/
fun Complex.Companion.createBuffer(size: Int) = ObjectBuffer.create(ComplexBufferSpec, size)
fun Buffer.Companion.complex(size: Int): Buffer<Complex> =
ObjectBuffer.create(ComplexBufferSpec, size)
fun MutableBuffer.Companion.complex(size: Int) =
ObjectBuffer.create(ComplexBufferSpec, size)
fun NDField.Companion.complex(shape: IntArray) =
BufferNDField(shape, ComplexField) { size, init -> ObjectBuffer.create(ComplexBufferSpec, size, init) }
fun NDElement.Companion.complex(shape: IntArray, initializer: ComplexField.(IntArray) -> Complex) =
NDField.complex(shape).produce(initializer)

View File

@ -23,7 +23,13 @@ class ObjectBuffer<T : Any>(private val buffer: ByteBuffer, private val spec: Fi
}
companion object {
fun <T : Any> create(spec: FixedSizeBufferSpec<T>, size: Int) =
ObjectBuffer<T>(ByteBuffer.allocate(size * spec.unitSize), spec)
fun <T : Any> create(spec: FixedSizeBufferSpec<T>, size: Int, initializer: ((Int) -> T)? = null) =
ObjectBuffer(ByteBuffer.allocate(size * spec.unitSize), spec).also { buffer ->
if (initializer != null) {
(0 until size).forEach {
buffer[it] = initializer(it)
}
}
}
}
}

View File

@ -7,7 +7,7 @@ import kotlin.test.assertEquals
class ComplexBufferSpecTest {
@Test
fun testComplexBuffer() {
val buffer = Complex.createBuffer(20)
val buffer = MutableBuffer.complex(20)
(0 until 20).forEach {
buffer[it] = Complex(it.toDouble(), -it.toDouble())
}