Grid generators for 1D double array

This commit is contained in:
Alexander Nozik 2018-09-11 22:00:00 +03:00
parent ba63b2e373
commit 9c064b00b1
3 changed files with 52 additions and 5 deletions

View File

@ -0,0 +1,40 @@
package scientifik.kmath.misc
import kotlin.coroutines.experimental.buildSequence
/**
* Convert double range to sequence.
*
* If the step is positive, than the sequence starts with the lower boundary and increments by [step] until current value is lower than upper boundary.
* The boundary itself is not necessary included.
*
* If step is negative, the same goes from upper boundary downwards
*/
fun ClosedFloatingPointRange<Double>.toSequence(step: Double): Sequence<Double> {
return when {
step == 0.0 -> error("Zero step in double progression")
step > 0 -> buildSequence {
var current = start
while (current <= endInclusive) {
yield(current)
current += step
}
}
else -> buildSequence {
var current = endInclusive
while (current >= start) {
yield(current)
current += step
}
}
}
}
/**
* Convert double range to array of evenly spaced doubles, where the size of array equals [numPoints]
*/
fun ClosedFloatingPointRange<Double>.toGrid(numPoints: Int): DoubleArray {
if (numPoints < 2) error("Can't create grid with less than two points")
return DoubleArray(numPoints) { i -> start + (endInclusive - start) / (numPoints - 1) * i }
}

View File

@ -40,11 +40,12 @@ abstract class BufferNDField<T>(shape: List<Int>, field: Field<T>) : NDField<T>(
}.sum()
}
protected fun index(offset: Int): List<Int>{
//TODO introduce a fast way to calculate index of the next element?
protected fun index(offset: Int): List<Int> {
return buildSequence {
var current = offset
var strideIndex = strides.size-2
while (strideIndex>=0){
var strideIndex = strides.size - 2
while (strideIndex >= 0) {
yield(current / strides[strideIndex])
current %= strides[strideIndex]
strideIndex--
@ -59,7 +60,7 @@ abstract class BufferNDField<T>(shape: List<Int>, field: Field<T>) : NDField<T>(
protected abstract fun createBuffer(capacity: Int, initializer: (Int) -> T): Buffer<T>
override fun produce(initializer: (List<Int>) -> T): NDArray<T> {
val buffer = createBuffer(capacity){initializer(index(it))}
val buffer = createBuffer(capacity) { initializer(index(it)) }
return BufferNDArray(this, buffer)
}

View File

@ -22,3 +22,9 @@ compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
sourceCompatibility = "1.8"
kotlin {
experimental {
coroutines "enable"
}
}