Grand derivative refactoring. Phase 1

This commit is contained in:
Alexander Nozik 2022-07-15 15:21:49 +03:00
parent 56f3c05907
commit 5846f42141
No known key found for this signature in database
GPG Key ID: F7FCF2DD25C71357
14 changed files with 311 additions and 1363 deletions

View File

@ -5,11 +5,11 @@
package space.kscience.kmath.expressions
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableBufferFactory
import kotlin.math.max
import kotlin.math.min
internal fun <T> MutableBuffer<T>.fill(element: T, fromIndex: Int = 0, toIndex: Int = size) {
@ -54,7 +54,7 @@ internal fun <T> MutableBuffer<T>.fill(element: T, fromIndex: Int = 0, toIndex:
* @property order Derivation order.
* @see DerivativeStructure
*/
internal class DSCompiler<T, out A : Algebra<T>> internal constructor(
class DSCompiler<T, out A : Algebra<T>> internal constructor(
val algebra: A,
val bufferFactory: MutableBufferFactory<T>,
val freeParameters: Int,
@ -120,8 +120,7 @@ internal class DSCompiler<T, out A : Algebra<T>> internal constructor(
* This number includes the single 0 order derivative element, which is
* guaranteed to be stored in the first element of the array.
*/
val size: Int
get() = sizes[freeParameters][order]
val size: Int get() = sizes[freeParameters][order]
/**
* Get the index of a partial derivative in the array.
@ -178,7 +177,7 @@ internal fun <T, A> DSCompiler<T, A>.ln(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : ExponentialOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -211,7 +210,7 @@ internal fun <T, A> DSCompiler<T, A>.pow(
operandOffset: Int,
n: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : PowerOperations<T> = algebra {
if (n == 0) {
// special case, x^0 = 1 for all x
@ -267,7 +266,7 @@ internal fun <T, A> DSCompiler<T, A>.exp(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Ring<T>, A : ScaleOperations<T>, A : ExponentialOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -290,7 +289,7 @@ internal fun <T, A> DSCompiler<T, A>.sqrt(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : PowerOperations<T> = algebra {
// create the function value and derivatives
// [x^(1/n), (1/n)x^((1/n)-1), (1-n)/n^2x^((1/n)-2), ... ]
@ -351,7 +350,7 @@ internal fun <T, A> DSCompiler<T, A>.pow(
operandOffset: Int,
p: Double,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Ring<T>, A : NumericAlgebra<T>, A : PowerOperations<T>, A : ScaleOperations<T> = algebra {
// create the function value and derivatives
// [x^p, px^(p-1), p(p-1)x^(p-2), ... ]
@ -387,7 +386,7 @@ internal fun <T, A> DSCompiler<T, A>.tan(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Ring<T>, A : TrigonometricOperations<T>, A : ScaleOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -469,7 +468,7 @@ internal fun <T, A> DSCompiler<T, A>.sin(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Ring<T>, A : ScaleOperations<T>, A : TrigonometricOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -497,7 +496,7 @@ internal fun <T, A> DSCompiler<T, A>.acos(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : TrigonometricOperations<T>, A : PowerOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -559,7 +558,7 @@ internal fun <T, A> DSCompiler<T, A>.asin(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : TrigonometricOperations<T>, A : PowerOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -618,7 +617,7 @@ internal fun <T, A> DSCompiler<T, A>.atan(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : TrigonometricOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -678,7 +677,7 @@ internal fun <T, A> DSCompiler<T, A>.cosh(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Ring<T>, A : ScaleOperations<T>, A : ExponentialOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -708,7 +707,7 @@ internal fun <T, A> DSCompiler<T, A>.tanh(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : ExponentialOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -765,7 +764,7 @@ internal fun <T, A> DSCompiler<T, A>.acosh(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : ExponentialOperations<T>, A : PowerOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -857,7 +856,7 @@ internal fun <T, A> DSCompiler<T, A>.sinh(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : ExponentialOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -964,7 +963,7 @@ internal fun <T, A> DSCompiler<T, A>.asinh(
operand: Buffer<T>,
operandOffset: Int,
result: MutableBuffer<T>,
resultOffset: Int
resultOffset: Int,
) where A : Field<T>, A : ExponentialOperations<T>, A : PowerOperations<T> = algebra {
// create the function value and derivatives
val function = bufferFactory(1 + order) { zero }
@ -1109,59 +1108,6 @@ internal fun <T, A> DSCompiler<T, A>.atanh(
compose(operand, operandOffset, function, result, resultOffset)
}
/**
* Get the compiler for number of free parameters and order.
*
* @param parameters number of free parameters.
* @param order derivation order.
* @return cached rules set.
*/
internal fun <T, A : Algebra<T>> getCompiler(
algebra: A,
bufferFactory: MutableBufferFactory<T>,
parameters: Int,
order: Int
): DSCompiler<T, A> {
// get the cached compilers
val cache: Array<Array<DSCompiler<T, A>?>>? = null
// we need to create more compilers
val maxParameters: Int = max(parameters, cache?.size ?: 0)
val maxOrder: Int = max(order, if (cache == null) 0 else cache[0].size)
val newCache: Array<Array<DSCompiler<T, A>?>> = Array(maxParameters + 1) { arrayOfNulls(maxOrder + 1) }
if (cache != null) {
// preserve the already created compilers
for (i in cache.indices) {
cache[i].copyInto(newCache[i], endIndex = cache[i].size)
}
}
// create the array in increasing diagonal order
// create the array in increasing diagonal order
for (diag in 0..parameters + order) {
for (o in max(0, diag - parameters)..min(order, diag)) {
val p: Int = diag - o
if (newCache[p][o] == null) {
val valueCompiler: DSCompiler<T, A>? = if (p == 0) null else newCache[p - 1][o]!!
val derivativeCompiler: DSCompiler<T, A>? = if (o == 0) null else newCache[p][o - 1]!!
newCache[p][o] = DSCompiler(
algebra,
bufferFactory,
p,
o,
valueCompiler,
derivativeCompiler,
)
}
}
}
return newCache[parameters][order]!!
}
/**
* Compile the sizes array.
*

View File

@ -6,10 +6,9 @@
package space.kscience.kmath.expressions
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.NumericAlgebra
import space.kscience.kmath.operations.Ring
import space.kscience.kmath.operations.ScaleOperations
import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.asBuffer
/**
* Class representing both the value and the differentials of a function.
@ -28,128 +27,29 @@ import space.kscience.kmath.structures.MutableBuffer
* [Commons Math's `DerivativeStructure`](https://github.com/apache/commons-math/blob/924f6c357465b39beb50e3c916d5eb6662194175/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/analysis/differentiation/DerivativeStructure.java).
*/
@UnstableKMathAPI
public open class DerivativeStructure<T, A> internal constructor(
internal val derivativeAlgebra: DerivativeStructureRing<T, A>,
internal val compiler: DSCompiler<T, A>,
) where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> {
/**
* Combined array holding all values.
*/
internal var data: MutableBuffer<T> =
derivativeAlgebra.bufferFactory(compiler.size) { derivativeAlgebra.algebra.zero }
public open class DerivativeStructure<T, A : Ring<T>> @PublishedApi internal constructor(
private val derivativeAlgebra: DerivativeStructureAlgebra<T, A>,
@PublishedApi internal val data: Buffer<T>,
) {
/**
* Build an instance with all values and derivatives set to 0.
*
* @param parameters number of free parameters.
* @param order derivation order.
*/
public constructor (
derivativeAlgebra: DerivativeStructureRing<T, A>,
parameters: Int,
order: Int,
) : this(
derivativeAlgebra,
getCompiler<T, A>(derivativeAlgebra.algebra, derivativeAlgebra.bufferFactory, parameters, order),
)
/**
* Build an instance representing a constant value.
*
* @param parameters number of free parameters.
* @param order derivation order.
* @param value value of the constant.
* @see DerivativeStructure
*/
public constructor (
derivativeAlgebra: DerivativeStructureRing<T, A>,
parameters: Int,
order: Int,
value: T,
) : this(
derivativeAlgebra,
parameters,
order,
) {
data[0] = value
}
/**
* Build an instance representing a variable.
*
* Instances built using this constructor are considered to be the free variables with respect to which
* differentials are computed. As such, their differential with respect to themselves is +1.
*
* @param parameters number of free parameters.
* @param order derivation order.
* @param index index of the variable (from 0 to `parameters - 1`).
* @param value value of the variable.
*/
public constructor (
derivativeAlgebra: DerivativeStructureRing<T, A>,
parameters: Int,
order: Int,
index: Int,
value: T,
) : this(derivativeAlgebra, parameters, order, value) {
require(index < parameters) { "number is too large: $index >= $parameters" }
if (order > 0) {
// the derivative of the variable with respect to itself is 1.
data[getCompiler(derivativeAlgebra.algebra, derivativeAlgebra.bufferFactory, index, order).size] =
derivativeAlgebra.algebra.one
}
}
/**
* Build an instance from all its derivatives.
*
* @param parameters number of free parameters.
* @param order derivation order.
* @param derivatives derivatives sorted according to [DSCompiler.getPartialDerivativeIndex].
*/
public constructor (
derivativeAlgebra: DerivativeStructureRing<T, A>,
parameters: Int,
order: Int,
vararg derivatives: T,
) : this(
derivativeAlgebra,
parameters,
order,
) {
require(derivatives.size == data.size) { "dimension mismatch: ${derivatives.size} and ${data.size}" }
data = derivativeAlgebra.bufferFactory(data.size) { derivatives[it] }
}
/**
* Copy constructor.
*
* @param ds instance to copy.
*/
internal constructor(ds: DerivativeStructure<T, A>) : this(ds.derivativeAlgebra, ds.compiler) {
this.data = ds.data.copy()
}
public val compiler: DSCompiler<T, A> get() = derivativeAlgebra.compiler
/**
* The number of free parameters.
*/
public val freeParameters: Int
get() = compiler.freeParameters
public val freeParameters: Int get() = compiler.freeParameters
/**
* The derivation order.
*/
public val order: Int
get() = compiler.order
public val order: Int get() = compiler.order
/**
* The value part of the derivative structure.
*
* @see getPartialDerivative
*/
public val value: T
get() = data[0]
public val value: T get() = data[0]
/**
* Get a partial derivative.
@ -183,4 +83,75 @@ public open class DerivativeStructure<T, A> internal constructor(
public override fun hashCode(): Int =
227 + 229 * freeParameters + 233 * order + 239 * data.hashCode()
public companion object {
/**
* Build an instance representing a variable.
*
* Instances built using this constructor are considered to be the free variables with respect to which
* differentials are computed. As such, their differential with respect to themselves is +1.
*/
public fun <T, A : Ring<T>> variable(
derivativeAlgebra: DerivativeStructureAlgebra<T, A>,
index: Int,
value: T,
): DerivativeStructure<T, A> {
val compiler = derivativeAlgebra.compiler
require(index < compiler.freeParameters) { "number is too large: $index >= ${compiler.freeParameters}" }
return DerivativeStructure(derivativeAlgebra, derivativeAlgebra.bufferForVariable(index, value))
}
/**
* Build an instance from all its derivatives.
*
* @param derivatives derivatives sorted according to [DSCompiler.getPartialDerivativeIndex].
*/
public fun <T, A : Ring<T>> ofDerivatives(
derivativeAlgebra: DerivativeStructureAlgebra<T, A>,
vararg derivatives: T,
): DerivativeStructure<T, A> {
val compiler = derivativeAlgebra.compiler
require(derivatives.size == compiler.size) { "dimension mismatch: ${derivatives.size} and ${compiler.size}" }
val data = derivatives.asBuffer()
return DerivativeStructure(
derivativeAlgebra,
data
)
}
}
}
@OptIn(UnstableKMathAPI::class)
private fun <T, A : Ring<T>> DerivativeStructureAlgebra<T, A>.bufferForVariable(index: Int, value: T): Buffer<T> {
val buffer = bufferFactory(compiler.size) { algebra.zero }
buffer[0] = value
if (compiler.order > 0) {
// the derivative of the variable with respect to itself is 1.
val indexOfDerivative = compiler.getPartialDerivativeIndex(*IntArray(numberOfVariables).apply {
set(index, 1)
})
buffer[indexOfDerivative] = algebra.one
}
return buffer
}
/**
* A class implementing both [DerivativeStructure] and [Symbol].
*/
@UnstableKMathAPI
public class DerivativeStructureSymbol<T, A : Ring<T>> internal constructor(
derivativeAlgebra: DerivativeStructureAlgebra<T, A>,
index: Int,
symbol: Symbol,
value: T,
) : Symbol by symbol, DerivativeStructure<T, A>(
derivativeAlgebra, derivativeAlgebra.bufferForVariable(index, value)
) {
override fun toString(): String = symbol.toString()
override fun equals(other: Any?): Boolean = (other as? Symbol) == symbol
override fun hashCode(): Int = symbol.hashCode()
}

View File

@ -7,83 +7,89 @@ package space.kscience.kmath.expressions
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableBufferFactory
import space.kscience.kmath.structures.indices
import kotlin.math.max
import kotlin.math.min
/**
* A class implementing both [DerivativeStructure] and [Symbol].
*/
@UnstableKMathAPI
public class DerivativeStructureSymbol<T, A>(
derivativeAlgebra: DerivativeStructureRing<T, A>,
size: Int,
order: Int,
index: Int,
symbol: Symbol,
value: T,
) : Symbol by symbol, DerivativeStructure<T, A>(
derivativeAlgebra,
size,
order,
index,
value
) where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> {
override fun toString(): String = symbol.toString()
override fun equals(other: Any?): Boolean = (other as? Symbol) == symbol
override fun hashCode(): Int = symbol.hashCode()
}
/**
* A ring over [DerivativeStructure].
*
* @property order The derivation order.
* @param bindings The map of bindings values. All bindings are considered free parameters.
*/
@UnstableKMathAPI
public open class DerivativeStructureRing<T, A>(
public abstract class DerivativeStructureAlgebra<T, A : Ring<T>>(
public val algebra: A,
public val bufferFactory: MutableBufferFactory<T>,
public val order: Int,
bindings: Map<Symbol, T>,
) : Ring<DerivativeStructure<T, A>>, ScaleOperations<DerivativeStructure<T, A>>,
NumericAlgebra<DerivativeStructure<T, A>>,
ExpressionAlgebra<T, DerivativeStructure<T, A>>,
NumbersAddOps<DerivativeStructure<T, A>> where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> {
) : ExpressionAlgebra<T, DerivativeStructure<T, A>> {
public val numberOfVariables: Int = bindings.size
override val zero: DerivativeStructure<T, A> by lazy {
DerivativeStructure(
this,
numberOfVariables,
order,
)
}
override val one: DerivativeStructure<T, A> by lazy {
DerivativeStructure(
this,
numberOfVariables,
order,
algebra.one,
)
}
/**
* Get the compiler for number of free parameters and order.
*
* @return cached rules set.
*/
@PublishedApi
internal val compiler: DSCompiler<T, A> by lazy {
// get the cached compilers
val cache: Array<Array<DSCompiler<T, A>?>>? = null
override fun number(value: Number): DerivativeStructure<T, A> = const(algebra.number(value))
// we need to create more compilers
val maxParameters: Int = max(numberOfVariables, cache?.size ?: 0)
val maxOrder: Int = max(order, if (cache == null) 0 else cache[0].size)
val newCache: Array<Array<DSCompiler<T, A>?>> = Array(maxParameters + 1) { arrayOfNulls(maxOrder + 1) }
if (cache != null) {
// preserve the already created compilers
for (i in cache.indices) {
cache[i].copyInto(newCache[i], endIndex = cache[i].size)
}
}
// create the array in increasing diagonal order
for (diag in 0..numberOfVariables + order) {
for (o in max(0, diag - numberOfVariables)..min(order, diag)) {
val p: Int = diag - o
if (newCache[p][o] == null) {
val valueCompiler: DSCompiler<T, A>? = if (p == 0) null else newCache[p - 1][o]!!
val derivativeCompiler: DSCompiler<T, A>? = if (o == 0) null else newCache[p][o - 1]!!
newCache[p][o] = DSCompiler(
algebra,
bufferFactory,
p,
o,
valueCompiler,
derivativeCompiler,
)
}
}
}
return@lazy newCache[numberOfVariables][order]!!
}
private val variables: Map<Symbol, DerivativeStructureSymbol<T, A>> =
bindings.entries.mapIndexed { index, (key, value) ->
key to DerivativeStructureSymbol(
this,
numberOfVariables,
order,
index,
key,
value,
)
}.toMap()
public override fun const(value: T): DerivativeStructure<T, A> =
DerivativeStructure(this, numberOfVariables, order, value)
public override fun const(value: T): DerivativeStructure<T, A> {
val buffer = bufferFactory(compiler.size) { algebra.zero }
buffer[0] = value
return DerivativeStructure(
this,
buffer
)
}
override fun bindSymbolOrNull(value: String): DerivativeStructureSymbol<T, A>? = variables[StringSymbol(value)]
@ -103,54 +109,99 @@ public open class DerivativeStructureRing<T, A>(
public fun DerivativeStructure<T, A>.derivative(vararg symbols: Symbol): T = derivative(symbols.toList())
}
/**
* A ring over [DerivativeStructure].
*
* @property order The derivation order.
* @param bindings The map of bindings values. All bindings are considered free parameters.
*/
@UnstableKMathAPI
public open class DerivativeStructureRing<T, A>(
algebra: A,
bufferFactory: MutableBufferFactory<T>,
order: Int,
bindings: Map<Symbol, T>,
) : DerivativeStructureAlgebra<T, A>(algebra, bufferFactory, order, bindings),
Ring<DerivativeStructure<T, A>>, ScaleOperations<DerivativeStructure<T, A>>,
NumericAlgebra<DerivativeStructure<T, A>>,
NumbersAddOps<DerivativeStructure<T, A>> where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> {
override fun bindSymbolOrNull(value: String): DerivativeStructureSymbol<T, A>? =
super<DerivativeStructureAlgebra>.bindSymbolOrNull(value)
override fun DerivativeStructure<T, A>.unaryMinus(): DerivativeStructure<T, A> {
val ds = DerivativeStructure(this@DerivativeStructureRing, compiler)
for (i in ds.data.indices) {
ds.data[i] = algebra { -data[i] }
}
return ds
val newData = algebra { data.map(bufferFactory) { -it } }
return DerivativeStructure(this@DerivativeStructureRing, newData)
}
/**
* Create a copy of given [Buffer] and modify it according to [block]
*/
protected inline fun DerivativeStructure<T, A>.transformDataBuffer(block: DSCompiler<T, A>.(MutableBuffer<T>) -> Unit): DerivativeStructure<T, A> {
val newData = bufferFactory(compiler.size) { data[it] }
compiler.block(newData)
return DerivativeStructure(this@DerivativeStructureRing, newData)
}
protected fun DerivativeStructure<T, A>.mapData(block: (T) -> T): DerivativeStructure<T, A> {
val newData: Buffer<T> = data.map(bufferFactory, block)
return DerivativeStructure(this@DerivativeStructureRing, newData)
}
protected fun DerivativeStructure<T, A>.mapDataIndexed(block: (Int, T) -> T): DerivativeStructure<T, A> {
val newData: Buffer<T> = data.mapIndexed(bufferFactory, block)
return DerivativeStructure(this@DerivativeStructureRing, newData)
}
override val zero: DerivativeStructure<T, A> by lazy {
const(algebra.zero)
}
override val one: DerivativeStructure<T, A> by lazy {
const(algebra.one)
}
override fun number(value: Number): DerivativeStructure<T, A> = const(algebra.number(value))
override fun add(left: DerivativeStructure<T, A>, right: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
left.compiler.checkCompatibility(right.compiler)
val ds = DerivativeStructure(left)
left.compiler.add(left.data, 0, right.data, 0, ds.data, 0)
return ds
return left.transformDataBuffer { result ->
add(left.data, 0, right.data, 0, result, 0)
}
}
override fun scale(a: DerivativeStructure<T, A>, value: Double): DerivativeStructure<T, A> {
val ds = DerivativeStructure(a)
for (i in ds.data.indices) {
ds.data[i] = algebra { ds.data[i].times(value) }
}
return ds
override fun scale(a: DerivativeStructure<T, A>, value: Double): DerivativeStructure<T, A> = algebra {
a.mapData { it.times(value) }
}
override fun multiply(
left: DerivativeStructure<T, A>,
right: DerivativeStructure<T, A>
right: DerivativeStructure<T, A>,
): DerivativeStructure<T, A> {
left.compiler.checkCompatibility(right.compiler)
val result = DerivativeStructure(this, left.compiler)
left.compiler.multiply(left.data, 0, right.data, 0, result.data, 0)
return result
return left.transformDataBuffer { result ->
multiply(left.data, 0, right.data, 0, result, 0)
}
}
override fun DerivativeStructure<T, A>.minus(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
compiler.checkCompatibility(arg.compiler)
val ds = DerivativeStructure(this)
compiler.subtract(data, 0, arg.data, 0, ds.data, 0)
return ds
return transformDataBuffer { result ->
subtract(data, 0, arg.data, 0, result, 0)
}
}
override operator fun DerivativeStructure<T, A>.plus(other: Number): DerivativeStructure<T, A> {
val ds = DerivativeStructure(this)
ds.data[0] = algebra { ds.data[0] + number(other) }
return ds
override operator fun DerivativeStructure<T, A>.plus(other: Number): DerivativeStructure<T, A> = algebra {
transformDataBuffer {
it[0] += number(other)
}
}
override operator fun DerivativeStructure<T, A>.minus(other: Number): DerivativeStructure<T, A> =
this + -other.toDouble()
this + (-other.toDouble())
override operator fun Number.plus(other: DerivativeStructure<T, A>): DerivativeStructure<T, A> = other + this
override operator fun Number.minus(other: DerivativeStructure<T, A>): DerivativeStructure<T, A> = other - this
@ -194,119 +245,85 @@ public class DerivativeStructureField<T, A : ExtendedField<T>>(
override fun divide(left: DerivativeStructure<T, A>, right: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
left.compiler.checkCompatibility(right.compiler)
val result = DerivativeStructure(this, left.compiler)
left.compiler.divide(left.data, 0, right.data, 0, result.data, 0)
return result
return left.transformDataBuffer { result ->
left.compiler.divide(left.data, 0, right.data, 0, result, 0)
}
}
override fun sin(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.sin(arg.data, 0, result.data, 0)
return result
override fun sin(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
sin(arg.data, 0, result, 0)
}
override fun cos(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.cos(arg.data, 0, result.data, 0)
return result
override fun cos(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
cos(arg.data, 0, result, 0)
}
override fun tan(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.tan(arg.data, 0, result.data, 0)
return result
override fun tan(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
tan(arg.data, 0, result, 0)
}
override fun asin(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.asin(arg.data, 0, result.data, 0)
return result
override fun asin(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
asin(arg.data, 0, result, 0)
}
override fun acos(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.acos(arg.data, 0, result.data, 0)
return result
override fun acos(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
acos(arg.data, 0, result, 0)
}
override fun atan(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.atan(arg.data, 0, result.data, 0)
return result
override fun atan(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
atan(arg.data, 0, result, 0)
}
override fun sinh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.sinh(arg.data, 0, result.data, 0)
return result
override fun sinh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
sinh(arg.data, 0, result, 0)
}
override fun cosh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.cosh(arg.data, 0, result.data, 0)
return result
override fun cosh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
cosh(arg.data, 0, result, 0)
}
override fun tanh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.tanh(arg.data, 0, result.data, 0)
return result
override fun tanh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
tanh(arg.data, 0, result, 0)
}
override fun asinh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.asinh(arg.data, 0, result.data, 0)
return result
override fun asinh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
asinh(arg.data, 0, result, 0)
}
override fun acosh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.acosh(arg.data, 0, result.data, 0)
return result
override fun acosh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
acosh(arg.data, 0, result, 0)
}
override fun atanh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.atanh(arg.data, 0, result.data, 0)
return result
override fun atanh(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
atanh(arg.data, 0, result, 0)
}
override fun power(arg: DerivativeStructure<T, A>, pow: Number): DerivativeStructure<T, A> = when (pow) {
is Int -> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.pow(arg.data, 0, pow, result.data, 0)
result
is Int -> arg.transformDataBuffer { result ->
pow(arg.data, 0, pow, result, 0)
}
else -> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.pow(arg.data, 0, pow.toDouble(), result.data, 0)
result
else -> arg.transformDataBuffer { result ->
pow(arg.data, 0, pow.toDouble(), result, 0)
}
}
override fun sqrt(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.sqrt(arg.data, 0, result.data, 0)
return result
override fun sqrt(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
sqrt(arg.data, 0, result, 0)
}
public fun power(arg: DerivativeStructure<T, A>, pow: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
arg.compiler.checkCompatibility(pow.compiler)
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.pow(arg.data, 0, pow.data, 0, result.data, 0)
return result
return arg.transformDataBuffer { result ->
pow(arg.data, 0, pow.data, 0, result, 0)
}
}
override fun exp(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.exp(arg.data, 0, result.data, 0)
return result
override fun exp(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
exp(arg.data, 0, result, 0)
}
override fun ln(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> {
val result = DerivativeStructure(this, arg.compiler)
arg.compiler.ln(arg.data, 0, result.data, 0)
return result
override fun ln(arg: DerivativeStructure<T, A>): DerivativeStructure<T, A> = arg.transformDataBuffer { result ->
ln(arg.data, 0, result, 0)
}
}

View File

@ -188,7 +188,7 @@ public interface LinearSpace<T, out A : Ring<T>> {
*/
public fun <T : Any, A : Ring<T>> buffered(
algebra: A,
bufferFactory: BufferFactory<T> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<T> = BufferFactory(Buffer.Companion::boxing),
): LinearSpace<T, A> = BufferedLinearSpace(BufferRingOps(algebra, bufferFactory))
@Deprecated("use DoubleField.linearSpace")

View File

@ -27,5 +27,5 @@ public annotation class UnstableKMathAPI
RequiresOptIn.Level.WARNING,
)
public annotation class PerformancePitfall(
val message: String = "Potential performance problem"
val message: String = "Potential performance problem",
)

View File

@ -69,7 +69,7 @@ public class MutableBufferND<T>(
* Transform structure to a new structure using provided [MutableBufferFactory] and optimizing if argument is [MutableBufferND]
*/
public inline fun <T, reified R : Any> MutableStructureND<T>.mapToMutableBuffer(
factory: MutableBufferFactory<R> = MutableBuffer.Companion::auto,
factory: MutableBufferFactory<R> = MutableBufferFactory(MutableBuffer.Companion::auto),
crossinline transform: (T) -> R,
): MutableBufferND<R> {
return if (this is MutableBufferND<T>)

View File

@ -120,7 +120,7 @@ public interface StructureND<out T> : Featured<StructureFeature>, WithShape {
*/
public fun <T> buffered(
strides: Strides,
bufferFactory: BufferFactory<T> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<T> = BufferFactory(Buffer.Companion::boxing),
initializer: (IntArray) -> T,
): BufferND<T> = BufferND(strides, bufferFactory(strides.linearSize) { i -> initializer(strides.index(i)) })
@ -140,7 +140,7 @@ public interface StructureND<out T> : Featured<StructureFeature>, WithShape {
public fun <T> buffered(
shape: IntArray,
bufferFactory: BufferFactory<T> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<T> = BufferFactory(Buffer.Companion::boxing),
initializer: (IntArray) -> T,
): BufferND<T> = buffered(DefaultStrides(shape), bufferFactory, initializer)

View File

@ -6,12 +6,10 @@
package space.kscience.kmath.operations
import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.BufferFactory
import space.kscience.kmath.structures.DoubleBuffer
import space.kscience.kmath.structures.asBuffer
import kotlin.math.*
/**
@ -21,7 +19,7 @@ public abstract class DoubleBufferOps : BufferAlgebra<Double, DoubleField>, Exte
Norm<Buffer<Double>, Double> {
override val elementAlgebra: DoubleField get() = DoubleField
override val bufferFactory: BufferFactory<Double> get() = ::DoubleBuffer
override val bufferFactory: BufferFactory<Double> get() = BufferFactory(::DoubleBuffer)
override fun Buffer<Double>.map(block: DoubleField.(Double) -> Double): DoubleBuffer =
mapInline { DoubleField.block(it) }

View File

@ -61,31 +61,39 @@ public inline fun <reified T> Buffer<T>.toTypedArray(): Array<T> = Array(size, :
/**
* Create a new buffer from this one with the given mapping function and using [Buffer.Companion.auto] buffer factory.
*/
public inline fun <T : Any, reified R : Any> Buffer<T>.map(block: (T) -> R): Buffer<R> =
public inline fun <T, reified R : Any> Buffer<T>.map(block: (T) -> R): Buffer<R> =
Buffer.auto(size) { block(get(it)) }
/**
* Create a new buffer from this one with the given mapping function.
* Provided [bufferFactory] is used to construct the new buffer.
*/
public inline fun <T : Any, R : Any> Buffer<T>.map(
public inline fun <T, R> Buffer<T>.map(
bufferFactory: BufferFactory<R>,
crossinline block: (T) -> R,
): Buffer<R> = bufferFactory(size) { block(get(it)) }
/**
* Create a new buffer from this one with the given indexed mapping function.
* Provided [BufferFactory] is used to construct the new buffer.
* Create a new buffer from this one with the given mapping (indexed) function.
* Provided [bufferFactory] is used to construct the new buffer.
*/
public inline fun <T : Any, reified R : Any> Buffer<T>.mapIndexed(
bufferFactory: BufferFactory<R> = Buffer.Companion::auto,
public inline fun <T, R> Buffer<T>.mapIndexed(
bufferFactory: BufferFactory<R>,
crossinline block: (index: Int, value: T) -> R,
): Buffer<R> = bufferFactory(size) { block(it, get(it)) }
/**
* Create a new buffer from this one with the given indexed mapping function.
* Provided [BufferFactory] is used to construct the new buffer.
*/
public inline fun <T, reified R : Any> Buffer<T>.mapIndexed(
crossinline block: (index: Int, value: T) -> R,
): Buffer<R> = BufferFactory<R>(Buffer.Companion::auto).invoke(size) { block(it, get(it)) }
/**
* Fold given buffer according to [operation]
*/
public inline fun <T : Any, R> Buffer<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
public inline fun <T, R> Buffer<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
var accumulator = initial
for (index in this.indices) accumulator = operation(accumulator, get(index))
return accumulator
@ -95,9 +103,9 @@ public inline fun <T : Any, R> Buffer<T>.fold(initial: R, operation: (acc: R, T)
* Zip two buffers using given [transform].
*/
@UnstableKMathAPI
public inline fun <T1 : Any, T2 : Any, reified R : Any> Buffer<T1>.zip(
public inline fun <T1, T2 : Any, reified R : Any> Buffer<T1>.zip(
other: Buffer<T2>,
bufferFactory: BufferFactory<R> = Buffer.Companion::auto,
bufferFactory: BufferFactory<R> = BufferFactory(Buffer.Companion::auto),
crossinline transform: (T1, T2) -> R,
): Buffer<R> {
require(size == other.size) { "Buffer size mismatch in zip: expected $size but found ${other.size}" }

View File

@ -14,14 +14,18 @@ import kotlin.reflect.KClass
*
* @param T the type of buffer.
*/
public typealias BufferFactory<T> = (Int, (Int) -> T) -> Buffer<T>
public fun interface BufferFactory<T> {
public operator fun invoke(size: Int, builder: (Int) -> T): Buffer<T>
}
/**
* Function that produces [MutableBuffer] from its size and function that supplies values.
*
* @param T the type of buffer.
*/
public typealias MutableBufferFactory<T> = (Int, (Int) -> T) -> MutableBuffer<T>
public fun interface MutableBufferFactory<T>: BufferFactory<T>{
override fun invoke(size: Int, builder: (Int) -> T): MutableBuffer<T>
}
/**
* A generic read-only random-access structure for both primitives and objects.

View File

@ -28,7 +28,7 @@ public class UniformHistogramGroupND<V : Any, A : Field<V>>(
private val lower: Buffer<Double>,
private val upper: Buffer<Double>,
private val binNums: IntArray = IntArray(lower.size) { 20 },
private val bufferFactory: BufferFactory<V> = Buffer.Companion::boxing,
private val bufferFactory: BufferFactory<V> = BufferFactory(Buffer.Companion::boxing),
) : HistogramGroupND<Double, HyperSquareDomain, V> {
init {
@ -114,7 +114,7 @@ public class UniformHistogramGroupND<V : Any, A : Field<V>>(
public fun <V : Any, A : Field<V>> Histogram.Companion.uniformNDFromRanges(
valueAlgebraND: FieldOpsND<V, A>,
vararg ranges: ClosedFloatingPointRange<Double>,
bufferFactory: BufferFactory<V> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<V> = BufferFactory(Buffer.Companion::boxing),
): UniformHistogramGroupND<V, A> = UniformHistogramGroupND(
valueAlgebraND,
ranges.map(ClosedFloatingPointRange<Double>::start).asBuffer(),
@ -140,7 +140,7 @@ public fun Histogram.Companion.uniformDoubleNDFromRanges(
public fun <V : Any, A : Field<V>> Histogram.Companion.uniformNDFromRanges(
valueAlgebraND: FieldOpsND<V, A>,
vararg ranges: Pair<ClosedFloatingPointRange<Double>, Int>,
bufferFactory: BufferFactory<V> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<V> = BufferFactory(Buffer.Companion::boxing),
): UniformHistogramGroupND<V, A> = UniformHistogramGroupND(
valueAlgebraND,
ListBuffer(

View File

@ -6,6 +6,7 @@
package space.kscience.kmath.multik
import org.jetbrains.kotlinx.multik.ndarray.data.DataType
import space.kscience.kmath.misc.PerformancePitfall
import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.ExponentialOperations
@ -22,10 +23,13 @@ public object MultikDoubleAlgebra : MultikDivisionTensorAlgebra<Double, DoubleFi
override fun tan(arg: StructureND<Double>): MultikTensor<Double> = sin(arg) / cos(arg)
@PerformancePitfall
override fun asin(arg: StructureND<Double>): MultikTensor<Double> = arg.map { asin(it) }
@PerformancePitfall
override fun acos(arg: StructureND<Double>): MultikTensor<Double> = arg.map { acos(it) }
@PerformancePitfall
override fun atan(arg: StructureND<Double>): MultikTensor<Double> = arg.map { atan(it) }
override fun exp(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.exp(arg.asMultik().array).wrap()
@ -42,10 +46,13 @@ public object MultikDoubleAlgebra : MultikDivisionTensorAlgebra<Double, DoubleFi
return (expPlus - expMinus) / (expPlus + expMinus)
}
@PerformancePitfall
override fun asinh(arg: StructureND<Double>): MultikTensor<Double> = arg.map { asinh(it) }
@PerformancePitfall
override fun acosh(arg: StructureND<Double>): MultikTensor<Double> = arg.map { acosh(it) }
@PerformancePitfall
override fun atanh(arg: StructureND<Double>): MultikTensor<Double> = arg.map { atanh(it) }
}

View File

@ -35,7 +35,7 @@ public fun interface Sampler<out T : Any> {
public fun <T : Any> Sampler<T>.sampleBuffer(
generator: RandomGenerator,
size: Int,
bufferFactory: BufferFactory<T> = Buffer.Companion::boxing,
bufferFactory: BufferFactory<T> = BufferFactory(Buffer.Companion::boxing),
): Chain<Buffer<T>> {
require(size > 1)
//creating temporary storage once