From 5d2eaaf68aeb0b4c5d455aa46e366436d61de77d Mon Sep 17 00:00:00 2001 From: Iaroslav Postovalov Date: Tue, 13 Jul 2021 00:21:46 +0700 Subject: [PATCH] Add contracts to some functions, fix multiple style issues --- .../kmath/benchmarks/JafamaBenchmark.kt | 13 +++--- .../benchmarks/MatrixInverseBenchmark.kt | 4 +- docs/nd-structure.md | 2 + .../space/kscience/kmath/ast/astRendering.kt | 2 +- .../kscience/kmath/ast/rendering/features.kt | 2 +- .../TestCompilerConsistencyWithInterpreter.kt | 1 - .../kmath/ast/TestCompilerVariables.kt | 1 - .../kscience/kmath/internal/estree/estree.kt | 2 + .../kotlin/space/kscience/kmath/ast/utils.kt | 3 ++ .../kscience/kmath/wasm/TestWasmSpecific.kt | 1 - .../kotlin/space/kscience/kmath/ast/utils.kt | 7 +++- .../DerivativeStructureExpression.kt | 2 +- .../commons/optimization/CMOptimization.kt | 4 +- .../commons/transform/Transformations.kt | 2 +- .../DerivativeStructureExpressionTest.kt | 2 +- .../kscience/kmath/complex/Quaternion.kt | 2 +- .../kscience/kmath/data/XYColumnarData.kt | 2 +- .../kscience/kmath/data/XYZColumnarData.kt | 4 +- .../space/kscience/kmath/domains/Domain.kt | 2 +- .../expressions/DifferentiableExpression.kt | 17 ++++---- .../FunctionalExpressionAlgebra.kt | 42 +++++++++++-------- .../kmath/expressions/SimpleAutoDiff.kt | 9 ++-- .../kmath/expressions/SymbolIndexer.kt | 14 +++++-- .../kmath/linear/BufferedLinearSpace.kt | 4 +- .../kscience/kmath/linear/LinearSpace.kt | 2 +- .../kscience/kmath/linear/MatrixFeatures.kt | 14 +++---- .../space/kscience/kmath/misc/cumulative.kt | 2 +- .../space/kscience/kmath/nd/AlgebraND.kt | 9 ++-- .../kscience/kmath/nd/BufferAlgebraND.kt | 6 +-- .../space/kscience/kmath/nd/ShortRingND.kt | 7 ++-- .../space/kscience/kmath/nd/StructureND.kt | 2 +- .../kmath/operations/AlgebraElements.kt | 2 +- .../space/kscience/kmath/operations/BigInt.kt | 2 +- .../kmath/structures/BufferAccessor2D.kt | 18 ++++---- .../kmath/structures/bufferOperation.kt | 4 +- .../kscience/kmath/linear/VectorSpaceTest.kt | 5 --- .../kscience/kmath/testutils/FieldVerifier.kt | 2 +- .../kscience/kmath/testutils/RingVerifier.kt | 2 +- .../kmath/chains/BlockingDoubleChain.kt | 2 +- .../kmath/coroutines/coroutinesExtra.kt | 15 ++++--- .../kscience/kmath/dimensions/Wrappers.kt | 10 ++--- .../kscience/dimensions/DMatrixContextTest.kt | 0 .../space/kscience/kmath/real/RealMatrix.kt | 2 +- .../kaceince/kmath/real/DoubleMatrixTest.kt | 2 +- .../kscience/kmath/functions/Piecewise.kt | 8 ++-- .../kscience/kmath/functions/Polynomial.kt | 4 +- .../kscience/kmath/integration/Integrand.kt | 2 +- .../kmath/integration/UnivariateIntegrand.kt | 2 +- .../kmath/interpolation/Interpolator.kt | 2 +- .../space/kscience/kmath/geometry/Line.kt | 2 +- .../kscience/kmath/histogram/Histogram.kt | 6 +-- .../kmath/histogram/IndexedHistogramSpace.kt | 2 +- .../kmath/histogram/TreeHistogramSpace.kt | 13 +++--- kmath-kotlingrad/build.gradle.kts | 6 +-- .../kscience/kmath/nd4j/Nd4jArrayIterator.kt | 2 +- .../kmath/optimization/Optimization.kt | 2 +- .../kmath/samplers/ConstantSampler.kt | 18 -------- .../space/kscience/kmath/stat/MCScope.kt | 14 +++++-- .../space/kscience/kmath/stat/Sampler.kt | 2 +- .../kscience/kmath/stat/SamplerAlgebra.kt | 6 +-- .../space/kscience/kmath/stat/Statistic.kt | 8 ++-- .../kscience/kmath/symja/SymjaExpression.kt | 3 +- kmath-tensors/README.md | 2 +- kmath-tensors/build.gradle.kts | 14 +++---- .../kmath/tensors/core/BufferedTensor.kt | 4 +- .../kmath/tensors/core/DoubleTensor.kt | 2 +- .../kmath/tensors/core/DoubleTensorAlgebra.kt | 20 ++++----- .../kmath/tensors/core/internal/linUtils.kt | 6 +-- .../tensors/core/internal/tensorCastsUtils.kt | 1 + .../kmath/tensors/core/internal/utils.kt | 1 + .../core/TestDoubleLinearOpsAlgebra.kt | 2 +- .../tensors/core/TestDoubleTensorAlgebra.kt | 2 +- .../kmath/viktor/ViktorStructureND.kt | 2 +- 73 files changed, 210 insertions(+), 200 deletions(-) delete mode 100644 kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/VectorSpaceTest.kt rename kmath-dimensions/src/commonTest/kotlin/{ => space}/kscience/dimensions/DMatrixContextTest.kt (100%) delete mode 100644 kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/ConstantSampler.kt diff --git a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/JafamaBenchmark.kt b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/JafamaBenchmark.kt index 24a730375..5d4eee7c0 100644 --- a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/JafamaBenchmark.kt +++ b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/JafamaBenchmark.kt @@ -13,6 +13,8 @@ import space.kscience.kmath.jafama.JafamaDoubleField import space.kscience.kmath.jafama.StrictJafamaDoubleField import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.invoke +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract import kotlin.random.Random @State(Scope.Benchmark) @@ -31,9 +33,10 @@ internal class JafamaBenchmark { fun strictJafama(blackhole: Blackhole) = invokeBenchmarks(blackhole) { x -> StrictJafamaDoubleField { x * power(x, 4) * exp(x) / cos(x) + sin(x) } } - - private inline fun invokeBenchmarks(blackhole: Blackhole, expr: (Double) -> Double) { - val rng = Random(0) - repeat(1000000) { blackhole.consume(expr(rng.nextDouble())) } - } +} + +private inline fun invokeBenchmarks(blackhole: Blackhole, expr: (Double) -> Double) { + contract { callsInPlace(expr, InvocationKind.AT_LEAST_ONCE) } + val rng = Random(0) + repeat(1000000) { blackhole.consume(expr(rng.nextDouble())) } } diff --git a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MatrixInverseBenchmark.kt b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MatrixInverseBenchmark.kt index 7bb32af28..e3179c05c 100644 --- a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MatrixInverseBenchmark.kt +++ b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MatrixInverseBenchmark.kt @@ -40,14 +40,14 @@ internal class MatrixInverseBenchmark { @Benchmark fun cmLUPInversion(blackhole: Blackhole) { - with(CMLinearSpace) { + CMLinearSpace { blackhole.consume(inverse(matrix)) } } @Benchmark fun ejmlInverse(blackhole: Blackhole) { - with(EjmlLinearSpaceDDRM) { + EjmlLinearSpaceDDRM { blackhole.consume(matrix.getFeature>()?.inverse) } } diff --git a/docs/nd-structure.md b/docs/nd-structure.md index ec9b4d521..ab214094e 100644 --- a/docs/nd-structure.md +++ b/docs/nd-structure.md @@ -115,6 +115,8 @@ via extension function. Usually it is bad idea to compare the direct numerical operation performance in different languages, but it hard to work completely without frame of reference. In this case, simple numpy code: ```python +import numpy as np + res = np.ones((1000,1000)) for i in range(1000): res = res + 1.0 diff --git a/examples/src/main/kotlin/space/kscience/kmath/ast/astRendering.kt b/examples/src/main/kotlin/space/kscience/kmath/ast/astRendering.kt index e16769464..c4f263f97 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/ast/astRendering.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/ast/astRendering.kt @@ -10,7 +10,7 @@ import space.kscience.kmath.ast.rendering.LatexSyntaxRenderer import space.kscience.kmath.ast.rendering.MathMLSyntaxRenderer import space.kscience.kmath.ast.rendering.renderWithStringBuilder -public fun main() { +fun main() { val mst = "exp(sqrt(x))-asin(2*x)/(2e10+x^3)/(-12)".parseMath() val syntax = FeaturedMathRendererWithPostProcess.Default.render(mst) println("MathSyntax:") diff --git a/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt b/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt index a2f42d1bf..203cdf8b3 100644 --- a/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt +++ b/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt @@ -13,7 +13,7 @@ import space.kscience.kmath.operations.* import kotlin.reflect.KClass /** - * Prints any [Symbol] as a [SymbolSyntax] containing the [Symbol.value] of it. + * Prints any [Symbol] as a [SymbolSyntax] containing the [Symbol.identity] of it. * * @author Iaroslav Postovalov */ diff --git a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerConsistencyWithInterpreter.kt b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerConsistencyWithInterpreter.kt index 3116466e6..1edb5923e 100644 --- a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerConsistencyWithInterpreter.kt +++ b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerConsistencyWithInterpreter.kt @@ -11,7 +11,6 @@ import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.interpret import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.IntRing -import space.kscience.kmath.operations.bindSymbol import space.kscience.kmath.operations.invoke import kotlin.test.Test import kotlin.test.assertEquals diff --git a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerVariables.kt b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerVariables.kt index bed5bc7fa..af1a2e338 100644 --- a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerVariables.kt +++ b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerVariables.kt @@ -9,7 +9,6 @@ import space.kscience.kmath.expressions.MstRing import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.invoke import space.kscience.kmath.operations.IntRing -import space.kscience.kmath.operations.bindSymbol import space.kscience.kmath.operations.invoke import kotlin.test.Test import kotlin.test.assertEquals diff --git a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.kt b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.kt index e5254013e..b62b8c06c 100644 --- a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.kt +++ b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.kt @@ -3,6 +3,8 @@ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ +@file:Suppress("ClassName") + package space.kscience.kmath.internal.estree import kotlin.js.RegExp diff --git a/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/ast/utils.kt b/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/ast/utils.kt index 93b7e9449..0d896c6f6 100644 --- a/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/ast/utils.kt +++ b/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/ast/utils.kt @@ -10,6 +10,8 @@ import space.kscience.kmath.expressions.MST import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.IntRing +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract import space.kscience.kmath.estree.compile as estreeCompile import space.kscience.kmath.estree.compileToExpression as estreeCompileToExpression import space.kscience.kmath.wasm.compile as wasmCompile @@ -34,6 +36,7 @@ private object ESTreeCompilerTestContext : CompilerTestContext { } internal actual inline fun runCompilerTest(action: CompilerTestContext.() -> Unit) { + contract { callsInPlace(action, InvocationKind.AT_LEAST_ONCE) } action(WasmCompilerTestContext) action(ESTreeCompilerTestContext) } diff --git a/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/wasm/TestWasmSpecific.kt b/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/wasm/TestWasmSpecific.kt index 45776c191..8ae5fcb36 100644 --- a/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/wasm/TestWasmSpecific.kt +++ b/kmath-ast/src/jsTest/kotlin/space/kscience/kmath/wasm/TestWasmSpecific.kt @@ -11,7 +11,6 @@ import space.kscience.kmath.expressions.invoke import space.kscience.kmath.expressions.symbol import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.IntRing -import space.kscience.kmath.operations.bindSymbol import space.kscience.kmath.operations.invoke import kotlin.test.Test import kotlin.test.assertEquals diff --git a/kmath-ast/src/jvmTest/kotlin/space/kscience/kmath/ast/utils.kt b/kmath-ast/src/jvmTest/kotlin/space/kscience/kmath/ast/utils.kt index d3b554efd..a7f0bb3fb 100644 --- a/kmath-ast/src/jvmTest/kotlin/space/kscience/kmath/ast/utils.kt +++ b/kmath-ast/src/jvmTest/kotlin/space/kscience/kmath/ast/utils.kt @@ -10,6 +10,8 @@ import space.kscience.kmath.expressions.MST import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.IntRing +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract import space.kscience.kmath.asm.compile as asmCompile import space.kscience.kmath.asm.compileToExpression as asmCompileToExpression @@ -22,4 +24,7 @@ private object AsmCompilerTestContext : CompilerTestContext { asmCompile(algebra, arguments) } -internal actual inline fun runCompilerTest(action: CompilerTestContext.() -> Unit) = action(AsmCompilerTestContext) +internal actual inline fun runCompilerTest(action: CompilerTestContext.() -> Unit) { + contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } + action(AsmCompilerTestContext) +} diff --git a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpression.kt b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpression.kt index 361027968..d0ab8b1e8 100644 --- a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpression.kt +++ b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpression.kt @@ -15,7 +15,7 @@ import space.kscience.kmath.operations.NumbersAddOperations * A field over commons-math [DerivativeStructure]. * * @property order The derivation order. - * @property bindings The map of bindings values. All bindings are considered free parameters + * @param bindings The map of bindings values. All bindings are considered free parameters */ @OptIn(UnstableKMathAPI::class) public class DerivativeStructureField( diff --git a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/optimization/CMOptimization.kt b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/optimization/CMOptimization.kt index 400ee0310..a46f06568 100644 --- a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/optimization/CMOptimization.kt +++ b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/optimization/CMOptimization.kt @@ -52,11 +52,11 @@ public class CMOptimization( public fun exportOptimizationData(): List = optimizationData.values.toList() - public override fun initialGuess(map: Map): Unit { + public override fun initialGuess(map: Map) { addOptimizationData(InitialGuess(map.toDoubleArray())) } - public override fun function(expression: Expression): Unit { + public override fun function(expression: Expression) { val objectiveFunction = ObjectiveFunction { val args = it.toMap() expression(args) diff --git a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/transform/Transformations.kt b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/transform/Transformations.kt index d29491d63..6fef12138 100644 --- a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/transform/Transformations.kt +++ b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/transform/Transformations.kt @@ -32,7 +32,7 @@ public object Transformations { /** * Create a virtual buffer on top of array */ - private fun Array.asBuffer() = VirtualBuffer(size) { + private fun Array.asBuffer() = VirtualBuffer(size) { val value = get(it) Complex(value.real, value.imaginary) } diff --git a/kmath-commons/src/test/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpressionTest.kt b/kmath-commons/src/test/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpressionTest.kt index 966675062..0bf1d53f0 100644 --- a/kmath-commons/src/test/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpressionTest.kt +++ b/kmath-commons/src/test/kotlin/space/kscience/kmath/commons/expressions/DerivativeStructureExpressionTest.kt @@ -16,7 +16,7 @@ internal inline fun diff( order: Int, vararg parameters: Pair, block: DerivativeStructureField.() -> Unit, -): Unit { +) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } DerivativeStructureField(order, mapOf(*parameters)).run(block) } diff --git a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt index c59aabdcb..28aae7bb4 100644 --- a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt +++ b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt @@ -147,7 +147,7 @@ public object QuaternionField : Field, Norm, return if (arg.w > 0) Quaternion(ln(arg.w), 0, 0, 0) else { - val l = ComplexField { ComplexField.ln(arg.w.toComplex()) } + val l = ComplexField { ln(arg.w.toComplex()) } Quaternion(l.re, l.im, 0, 0) } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYColumnarData.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYColumnarData.kt index 08bfd3ca3..920fcc021 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYColumnarData.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYColumnarData.kt @@ -16,7 +16,7 @@ import kotlin.math.max * The buffer of X values. */ @UnstableKMathAPI -public interface XYColumnarData : ColumnarData { +public interface XYColumnarData : ColumnarData { /** * The buffer of X values */ diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYZColumnarData.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYZColumnarData.kt index 39a6b858c..6050c311c 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYZColumnarData.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYZColumnarData.kt @@ -14,7 +14,7 @@ import space.kscience.kmath.structures.Buffer * Inherits [XYColumnarData]. */ @UnstableKMathAPI -public interface XYZColumnarData : XYColumnarData { +public interface XYZColumnarData : XYColumnarData { public val z: Buffer override fun get(symbol: Symbol): Buffer? = when (symbol) { @@ -23,4 +23,4 @@ public interface XYZColumnarData : XYColumna Symbol.z -> z else -> null } -} \ No newline at end of file +} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains/Domain.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains/Domain.kt index e6e703cbf..b5a84cf6c 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains/Domain.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains/Domain.kt @@ -12,7 +12,7 @@ import space.kscience.kmath.linear.Point * * @param T the type of element of this domain. */ -public interface Domain { +public interface Domain { /** * Checks if the specified point is contained in this domain. */ diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/DifferentiableExpression.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/DifferentiableExpression.kt index 1dcada6d3..ce1265b2f 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/DifferentiableExpression.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/DifferentiableExpression.kt @@ -9,7 +9,6 @@ package space.kscience.kmath.expressions * Represents expression which structure can be differentiated. * * @param T the type this expression takes as argument and returns. - * @param R the type of expression this expression can be differentiated to. */ public interface DifferentiableExpression : Expression { /** @@ -24,16 +23,18 @@ public interface DifferentiableExpression : Expression { public fun DifferentiableExpression.derivative(symbols: List): Expression = derivativeOrNull(symbols) ?: error("Derivative by symbols $symbols not provided") -public fun DifferentiableExpression.derivative(vararg symbols: Symbol): Expression = +public fun DifferentiableExpression.derivative(vararg symbols: Symbol): Expression = derivative(symbols.toList()) -public fun DifferentiableExpression.derivative(name: String): Expression = +public fun DifferentiableExpression.derivative(name: String): Expression = derivative(StringSymbol(name)) /** - * A special type of [DifferentiableExpression] which returns typed expressions as derivatives + * A special type of [DifferentiableExpression] which returns typed expressions as derivatives. + * + * @param R the type of expression this expression can be differentiated to. */ -public interface SpecialDifferentiableExpression>: DifferentiableExpression { +public interface SpecialDifferentiableExpression> : DifferentiableExpression { override fun derivativeOrNull(symbols: List): R? } @@ -53,9 +54,9 @@ public abstract class FirstDerivativeExpression : DifferentiableExpression /** * Returns first derivative of this expression by given [symbol]. */ - public abstract fun derivativeOrNull(symbol: Symbol): Expression? + public abstract fun derivativeOrNull(symbol: Symbol): Expression? - public final override fun derivativeOrNull(symbols: List): Expression? { + public final override fun derivativeOrNull(symbols: List): Expression? { val dSymbol = symbols.firstOrNull() ?: return null return derivativeOrNull(dSymbol) } @@ -64,6 +65,6 @@ public abstract class FirstDerivativeExpression : DifferentiableExpression /** * A factory that converts an expression in autodiff variables to a [DifferentiableExpression] */ -public fun interface AutoDiffProcessor, out R : Expression> { +public fun interface AutoDiffProcessor, out R : Expression> { public fun process(function: A.() -> I): DifferentiableExpression } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/FunctionalExpressionAlgebra.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/FunctionalExpressionAlgebra.kt index 951ec9474..a10e29cf0 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/FunctionalExpressionAlgebra.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/FunctionalExpressionAlgebra.kt @@ -6,13 +6,15 @@ package space.kscience.kmath.expressions import space.kscience.kmath.operations.* +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract /** * A context class for [Expression] construction. * * @param algebra The algebra to provide for Expressions built. */ -public abstract class FunctionalExpressionAlgebra>( +public abstract class FunctionalExpressionAlgebra>( public val algebra: A, ) : ExpressionAlgebra> { /** @@ -29,9 +31,6 @@ public abstract class FunctionalExpressionAlgebra>( ?: error("Symbol '$value' is not supported in $this") } - /** - * Builds an Expression of dynamic call of binary operation [operation] on [left] and [right]. - */ public override fun binaryOperationFunction(operation: String): (left: Expression, right: Expression) -> Expression = { left, right -> Expression { arguments -> @@ -39,9 +38,6 @@ public abstract class FunctionalExpressionAlgebra>( } } - /** - * Builds an Expression of dynamic call of unary operation with name [operation] on [arg]. - */ public override fun unaryOperationFunction(operation: String): (arg: Expression) -> Expression = { arg -> Expression { arguments -> algebra.unaryOperationFunction(operation)(arg.invoke(arguments)) } } @@ -50,7 +46,7 @@ public abstract class FunctionalExpressionAlgebra>( /** * A context class for [Expression] construction for [Ring] algebras. */ -public open class FunctionalExpressionGroup>( +public open class FunctionalExpressionGroup>( algebra: A, ) : FunctionalExpressionAlgebra(algebra), Group> { public override val zero: Expression get() = const(algebra.zero) @@ -84,7 +80,7 @@ public open class FunctionalExpressionGroup>( } -public open class FunctionalExpressionRing>( +public open class FunctionalExpressionRing>( algebra: A, ) : FunctionalExpressionGroup(algebra), Ring> { public override val one: Expression get() = const(algebra.one) @@ -105,7 +101,7 @@ public open class FunctionalExpressionRing>( super.binaryOperationFunction(operation) } -public open class FunctionalExpressionField>( +public open class FunctionalExpressionField>( algebra: A, ) : FunctionalExpressionRing(algebra), Field>, ScaleOperations> { /** @@ -131,7 +127,7 @@ public open class FunctionalExpressionField>( super.bindSymbolOrNull(value) } -public open class FunctionalExpressionExtendedField>( +public open class FunctionalExpressionExtendedField>( algebra: A, ) : FunctionalExpressionField(algebra), ExtendedField> { public override fun number(value: Number): Expression = const(algebra.number(value)) @@ -172,14 +168,26 @@ public open class FunctionalExpressionExtendedField>( public override fun bindSymbol(value: String): Expression = super.bindSymbol(value) } -public inline fun > A.expressionInSpace(block: FunctionalExpressionGroup.() -> Expression): Expression = - FunctionalExpressionGroup(this).block() +public inline fun > A.expressionInGroup( + block: FunctionalExpressionGroup.() -> Expression, +): Expression { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return FunctionalExpressionGroup(this).block() +} -public inline fun > A.expressionInRing(block: FunctionalExpressionRing.() -> Expression): Expression = - FunctionalExpressionRing(this).block() +public inline fun > A.expressionInRing( + block: FunctionalExpressionRing.() -> Expression, +): Expression { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return FunctionalExpressionRing(this).block() +} -public inline fun > A.expressionInField(block: FunctionalExpressionField.() -> Expression): Expression = - FunctionalExpressionField(this).block() +public inline fun > A.expressionInField( + block: FunctionalExpressionField.() -> Expression, +): Expression { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return FunctionalExpressionField(this).block() +} public inline fun > A.expressionInExtendedField( block: FunctionalExpressionExtendedField.() -> Expression, diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt index 478b85620..960f6fd79 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt @@ -119,8 +119,6 @@ public open class SimpleAutoDiffField>( get() = getDerivative(this) set(value) = setDerivative(this, value) - public inline fun const(block: F.() -> T): AutoDiffValue = const(context.block()) - /** * Performs update of derivative after the rest of the formula in the back-pass. * @@ -194,6 +192,11 @@ public open class SimpleAutoDiffField>( } } +public inline fun > SimpleAutoDiffField.const(block: F.() -> T): AutoDiffValue { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return const(context.block()) +} + /** * Runs differentiation and establishes [SimpleAutoDiffField] context inside the block of code. @@ -208,7 +211,7 @@ public open class SimpleAutoDiffField>( * assertEquals(9.0, x.d) // dy/dx * ``` * - * @param body the action in [SimpleAutoDiffField] context returning [AutoDiffVariable] to differentiate with respect to. + * @param body the action in [SimpleAutoDiffField] context returning [AutoDiffValue] to differentiate with respect to. * @return the result of differentiation. */ public fun > F.simpleAutoDiff( diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SymbolIndexer.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SymbolIndexer.kt index 06634704c..c02bdad02 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SymbolIndexer.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SymbolIndexer.kt @@ -9,6 +9,8 @@ import space.kscience.kmath.linear.Point import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.structures.BufferFactory +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract import kotlin.jvm.JvmInline /** @@ -65,9 +67,13 @@ public value class SimpleSymbolIndexer(override val symbols: List) : Sym * Execute the block with symbol indexer based on given symbol order */ @UnstableKMathAPI -public inline fun withSymbols(vararg symbols: Symbol, block: SymbolIndexer.() -> R): R = - with(SimpleSymbolIndexer(symbols.toList()), block) +public inline fun withSymbols(vararg symbols: Symbol, block: SymbolIndexer.() -> R): R { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return with(SimpleSymbolIndexer(symbols.toList()), block) +} @UnstableKMathAPI -public inline fun withSymbols(symbols: Collection, block: SymbolIndexer.() -> R): R = - with(SimpleSymbolIndexer(symbols.toList()), block) \ No newline at end of file +public inline fun withSymbols(symbols: Collection, block: SymbolIndexer.() -> R): R { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return with(SimpleSymbolIndexer(symbols.toList()), block) +} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferedLinearSpace.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferedLinearSpace.kt index 9b4451a62..f1839077f 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferedLinearSpace.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferedLinearSpace.kt @@ -15,7 +15,7 @@ import space.kscience.kmath.structures.VirtualBuffer import space.kscience.kmath.structures.indices -public class BufferedLinearSpace>( +public class BufferedLinearSpace>( override val elementAlgebra: A, private val bufferFactory: BufferFactory, ) : LinearSpace { @@ -88,4 +88,4 @@ public class BufferedLinearSpace>( override fun Matrix.times(value: T): Matrix = ndRing(rowNum, colNum).run { unwrap().map { it * value }.as2D() } -} \ No newline at end of file +} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt index ec073ac48..badf2794e 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt @@ -32,7 +32,7 @@ public typealias Point = Buffer * Basic operations on matrices and vectors. Operates on [Matrix]. * * @param T the type of items in the matrices. - * @param M the type of operated matrices. + * @param A the type of ring over [T]. */ public interface LinearSpace> { public val elementAlgebra: A diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixFeatures.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixFeatures.kt index 37c93d249..e0d733a66 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixFeatures.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixFeatures.kt @@ -35,7 +35,7 @@ public object UnitFeature : DiagonalFeature * * @param T the type of matrices' items. */ -public interface InverseMatrixFeature : MatrixFeature { +public interface InverseMatrixFeature : MatrixFeature { /** * The inverse matrix of the matrix that owns this feature. */ @@ -47,7 +47,7 @@ public interface InverseMatrixFeature : MatrixFeature { * * @param T the type of matrices' items. */ -public interface DeterminantFeature : MatrixFeature { +public interface DeterminantFeature : MatrixFeature { /** * The determinant of the matrix that owns this feature. */ @@ -80,7 +80,7 @@ public object UFeature : MatrixFeature * * @param T the type of matrices' items. */ -public interface LUDecompositionFeature : MatrixFeature { +public interface LUDecompositionFeature : MatrixFeature { /** * The lower triangular matrix in this decomposition. It may have [LFeature]. */ @@ -98,7 +98,7 @@ public interface LUDecompositionFeature : MatrixFeature { * * @param T the type of matrices' items. */ -public interface LupDecompositionFeature : MatrixFeature { +public interface LupDecompositionFeature : MatrixFeature { /** * The lower triangular matrix in this decomposition. It may have [LFeature]. */ @@ -126,7 +126,7 @@ public object OrthogonalFeature : MatrixFeature * * @param T the type of matrices' items. */ -public interface QRDecompositionFeature : MatrixFeature { +public interface QRDecompositionFeature : MatrixFeature { /** * The orthogonal matrix in this decomposition. It may have [OrthogonalFeature]. */ @@ -144,7 +144,7 @@ public interface QRDecompositionFeature : MatrixFeature { * * @param T the type of matrices' items. */ -public interface CholeskyDecompositionFeature : MatrixFeature { +public interface CholeskyDecompositionFeature : MatrixFeature { /** * The triangular matrix in this decomposition. It may have either [UFeature] or [LFeature]. */ @@ -157,7 +157,7 @@ public interface CholeskyDecompositionFeature : MatrixFeature { * * @param T the type of matrices' items. */ -public interface SingularValueDecompositionFeature : MatrixFeature { +public interface SingularValueDecompositionFeature : MatrixFeature { /** * The matrix in this decomposition. It is unitary, and it consists from left singular vectors. */ diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/misc/cumulative.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/misc/cumulative.kt index 889eb4f22..ee7f1d8be 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/misc/cumulative.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/misc/cumulative.kt @@ -34,7 +34,7 @@ public inline fun Iterable.cumulative(initial: R, crossinline operatio public inline fun Sequence.cumulative(initial: R, crossinline operation: (R, T) -> R): Sequence = Sequence { this@cumulative.iterator().cumulative(initial, operation) } -public fun List.cumulative(initial: R, operation: (R, T) -> R): List = +public inline fun List.cumulative(initial: R, crossinline operation: (R, T) -> R): List = iterator().cumulative(initial, operation).asSequence().toList() //Cumulative sum diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/AlgebraND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/AlgebraND.kt index 35bbc44f6..38985f216 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/AlgebraND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/AlgebraND.kt @@ -24,7 +24,6 @@ public class ShapeMismatchException(public val expected: IntArray, public val ac * * @param T the type of ND-structure element. * @param C the type of the element context. - * @param N the type of the structure. */ public interface AlgebraND> { /** @@ -118,8 +117,7 @@ internal fun > AlgebraND.checkShape(element: StructureND * Space of [StructureND]. * * @param T the type of the element contained in ND structure. - * @param N the type of ND structure. - * @param S the type of space of structure elements. + * @param S the type of group over structure elements. */ public interface GroupND> : Group>, AlgebraND { /** @@ -186,8 +184,7 @@ public interface GroupND> : Group>, AlgebraND * Ring of [StructureND]. * * @param T the type of the element contained in ND structure. - * @param N the type of ND structure. - * @param R the type of ring of structure elements. + * @param R the type of ring over structure elements. */ public interface RingND> : Ring>, GroupND { /** @@ -227,7 +224,7 @@ public interface RingND> : Ring>, GroupND> : Field>, RingND, ScaleOperations> { /** diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/BufferAlgebraND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/BufferAlgebraND.kt index 2b82a36ae..6eacf1ca5 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/BufferAlgebraND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/BufferAlgebraND.kt @@ -57,7 +57,7 @@ public interface BufferAlgebraND> : AlgebraND { } } -public open class BufferedGroupND>( +public open class BufferedGroupND>( final override val shape: IntArray, final override val elementContext: A, final override val bufferFactory: BufferFactory, @@ -67,7 +67,7 @@ public open class BufferedGroupND>( override fun StructureND.unaryMinus(): StructureND = produce { -get(it) } } -public open class BufferedRingND>( +public open class BufferedRingND>( shape: IntArray, elementContext: R, bufferFactory: BufferFactory, @@ -75,7 +75,7 @@ public open class BufferedRingND>( override val one: BufferND by lazy { produce { one } } } -public open class BufferedFieldND>( +public open class BufferedFieldND>( shape: IntArray, elementContext: R, bufferFactory: BufferFactory, diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/ShortRingND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/ShortRingND.kt index 720a06ace..1305558e5 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/ShortRingND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/ShortRingND.kt @@ -31,11 +31,10 @@ public class ShortRingND( /** * Fast element production using function inlining. */ -public inline fun BufferedRingND.produceInline(crossinline initializer: ShortRing.(Int) -> Short): BufferND { - return BufferND(strides, ShortBuffer(ShortArray(strides.linearSize) { offset -> ShortRing.initializer(offset) })) -} +public inline fun BufferedRingND.produceInline(crossinline initializer: ShortRing.(Int) -> Short): BufferND = + BufferND(strides, ShortBuffer(ShortArray(strides.linearSize) { offset -> ShortRing.initializer(offset) })) public inline fun ShortRing.nd(vararg shape: Int, action: ShortRingND.() -> R): R { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } return ShortRingND(shape).run(action) -} \ No newline at end of file +} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/StructureND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/StructureND.kt index 7fc91e321..1ad8289bc 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/StructureND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/StructureND.kt @@ -53,7 +53,7 @@ public interface StructureND { public fun elements(): Sequence> /** - * Feature is some additional strucure information which allows to access it special properties or hints. + * Feature is some additional structure information which allows to access it special properties or hints. * If the feature is not present, null is returned. */ @UnstableKMathAPI diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/AlgebraElements.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/AlgebraElements.kt index cc058d3fc..403a9c9b1 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/AlgebraElements.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/AlgebraElements.kt @@ -15,7 +15,7 @@ import space.kscience.kmath.misc.UnstableKMathAPI */ @UnstableKMathAPI @Deprecated("AlgebraElements are considered odd and will be removed in future releases.") -public interface AlgebraElement> { +public interface AlgebraElement> { /** * The context this element belongs to. */ diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt index ac53c4d5e..c332b086e 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt @@ -445,7 +445,7 @@ public fun UIntArray.toBigInt(sign: Byte): BigInt { * Returns null if a valid number can not be read from a string */ public fun String.parseBigInteger(): BigInt? { - if (this.isEmpty()) return null + if (isEmpty()) return null val sign: Int val positivePartIndex = when (this[0]) { diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/BufferAccessor2D.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/BufferAccessor2D.kt index 352c75956..03b3822c3 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/BufferAccessor2D.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/BufferAccessor2D.kt @@ -14,30 +14,30 @@ import space.kscience.kmath.nd.as2D * A context that allows to operate on a [MutableBuffer] as on 2d array */ internal class BufferAccessor2D( - public val rowNum: Int, - public val colNum: Int, + val rowNum: Int, + val colNum: Int, val factory: MutableBufferFactory, ) { - public operator fun Buffer.get(i: Int, j: Int): T = get(i * colNum + j) + operator fun Buffer.get(i: Int, j: Int): T = get(i * colNum + j) - public operator fun MutableBuffer.set(i: Int, j: Int, value: T) { + operator fun MutableBuffer.set(i: Int, j: Int, value: T) { set(i * colNum + j, value) } - public inline fun create(crossinline init: (i: Int, j: Int) -> T): MutableBuffer = + inline fun create(crossinline init: (i: Int, j: Int) -> T): MutableBuffer = factory(rowNum * colNum) { offset -> init(offset / colNum, offset % colNum) } - public fun create(mat: Structure2D): MutableBuffer = create { i, j -> mat[i, j] } + fun create(mat: Structure2D): MutableBuffer = create { i, j -> mat[i, j] } //TODO optimize wrapper - public fun MutableBuffer.collect(): Structure2D = StructureND.buffered( + fun MutableBuffer.collect(): Structure2D = StructureND.buffered( DefaultStrides(intArrayOf(rowNum, colNum)), factory ) { (i, j) -> get(i, j) }.as2D() - public inner class Row(public val buffer: MutableBuffer, public val rowIndex: Int) : MutableBuffer { + inner class Row(val buffer: MutableBuffer, val rowIndex: Int) : MutableBuffer { override val size: Int get() = colNum override operator fun get(index: Int): T = buffer[rowIndex, index] @@ -54,5 +54,5 @@ internal class BufferAccessor2D( /** * Get row */ - public fun MutableBuffer.row(i: Int): Row = Row(this, i) + fun MutableBuffer.row(i: Int): Row = Row(this, i) } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/bufferOperation.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/bufferOperation.kt index 1b89e7838..3dad14ac5 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/bufferOperation.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/bufferOperation.kt @@ -67,9 +67,9 @@ public inline fun Buffer.map(block: (T) -> R): Buf * Create a new buffer from this one with the given mapping function. * Provided [bufferFactory] is used to construct the new buffer. */ -public fun Buffer.map( +public inline fun Buffer.map( bufferFactory: BufferFactory, - block: (T) -> R, + crossinline block: (T) -> R, ): Buffer = bufferFactory(size) { block(get(it)) } /** diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/VectorSpaceTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/VectorSpaceTest.kt deleted file mode 100644 index f2c7f1f90..000000000 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/VectorSpaceTest.kt +++ /dev/null @@ -1,5 +0,0 @@ -/* - * Copyright 2018-2021 KMath contributors. - * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. - */ - diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/FieldVerifier.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/FieldVerifier.kt index bd09ff449..20a7b6a72 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/FieldVerifier.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/FieldVerifier.kt @@ -10,7 +10,7 @@ import space.kscience.kmath.operations.invoke import kotlin.test.assertEquals import kotlin.test.assertNotEquals -internal class FieldVerifier>( +internal class FieldVerifier>( algebra: A, a: T, b: T, c: T, x: Number, ) : RingVerifier(algebra, a, b, c, x) { diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/RingVerifier.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/RingVerifier.kt index 885857f04..daf18834a 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/RingVerifier.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/testutils/RingVerifier.kt @@ -10,7 +10,7 @@ import space.kscience.kmath.operations.ScaleOperations import space.kscience.kmath.operations.invoke import kotlin.test.assertEquals -internal open class RingVerifier(algebra: A, a: T, b: T, c: T, x: Number) : +internal open class RingVerifier(algebra: A, a: T, b: T, c: T, x: Number) : SpaceVerifier(algebra, a, b, c, x) where A : Ring, A : ScaleOperations { override fun verify() { diff --git a/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/chains/BlockingDoubleChain.kt b/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/chains/BlockingDoubleChain.kt index 526250cf0..88456e124 100644 --- a/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/chains/BlockingDoubleChain.kt +++ b/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/chains/BlockingDoubleChain.kt @@ -29,4 +29,4 @@ public fun BlockingDoubleChain.map(transform: (Double) -> Double): BlockingDoubl } override suspend fun fork(): BlockingDoubleChain = this@map.fork().map(transform) -} \ No newline at end of file +} diff --git a/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/coroutines/coroutinesExtra.kt b/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/coroutines/coroutinesExtra.kt index 49f32f82f..1f17efe49 100644 --- a/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/coroutines/coroutinesExtra.kt +++ b/kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/coroutines/coroutinesExtra.kt @@ -15,30 +15,33 @@ public val Dispatchers.Math: CoroutineDispatcher /** * An imitator of [Deferred] which holds a suspended function block and dispatcher */ -internal class LazyDeferred(val dispatcher: CoroutineDispatcher, val block: suspend CoroutineScope.() -> T) { +@PublishedApi +internal class LazyDeferred(val dispatcher: CoroutineDispatcher, val block: suspend CoroutineScope.() -> T) { private var deferred: Deferred? = null - internal fun start(scope: CoroutineScope) { + fun start(scope: CoroutineScope) { if (deferred == null) deferred = scope.async(dispatcher, block = block) } suspend fun await(): T = deferred?.await() ?: error("Coroutine not started") } -public class AsyncFlow internal constructor(internal val deferredFlow: Flow>) : Flow { +public class AsyncFlow @PublishedApi internal constructor( + @PublishedApi internal val deferredFlow: Flow>, +) : Flow { override suspend fun collect(collector: FlowCollector): Unit = deferredFlow.collect { collector.emit((it.await())) } } -public fun Flow.async( +public inline fun Flow.async( dispatcher: CoroutineDispatcher = Dispatchers.Default, - block: suspend CoroutineScope.(T) -> R, + crossinline block: suspend CoroutineScope.(T) -> R, ): AsyncFlow { val flow = map { LazyDeferred(dispatcher) { block(it) } } return AsyncFlow(flow) } -public fun AsyncFlow.map(action: (T) -> R): AsyncFlow = +public inline fun AsyncFlow.map(crossinline action: (T) -> R): AsyncFlow = AsyncFlow(deferredFlow.map { input -> //TODO add function composition LazyDeferred(input.dispatcher) { diff --git a/kmath-dimensions/src/commonMain/kotlin/space/kscience/kmath/dimensions/Wrappers.kt b/kmath-dimensions/src/commonMain/kotlin/space/kscience/kmath/dimensions/Wrappers.kt index 2ebcc454d..a2ee14301 100644 --- a/kmath-dimensions/src/commonMain/kotlin/space/kscience/kmath/dimensions/Wrappers.kt +++ b/kmath-dimensions/src/commonMain/kotlin/space/kscience/kmath/dimensions/Wrappers.kt @@ -17,7 +17,7 @@ import kotlin.jvm.JvmInline /** * A matrix with compile-time controlled dimension */ -public interface DMatrix : Structure2D { +public interface DMatrix : Structure2D { public companion object { /** * Coerces a regular matrix to a matrix with type-safe dimensions and throws a error if coercion failed @@ -46,7 +46,7 @@ public interface DMatrix : Structure2D { * An inline wrapper for a Matrix */ @JvmInline -public value class DMatrixWrapper( +public value class DMatrixWrapper( private val structure: Structure2D, ) : DMatrix { override val shape: IntArray get() = structure.shape @@ -58,7 +58,7 @@ public value class DMatrixWrapper( /** * Dimension-safe point */ -public interface DPoint : Point { +public interface DPoint : Point { public companion object { public inline fun coerce(point: Point): DPoint { require(point.size == Dimension.dim().toInt()) { @@ -76,7 +76,7 @@ public interface DPoint : Point { * Dimension-safe point wrapper */ @JvmInline -public value class DPointWrapper(public val point: Point) : +public value class DPointWrapper(public val point: Point) : DPoint { override val size: Int get() = point.size @@ -111,7 +111,7 @@ public value class DMatrixContext>(public val context: ): DMatrix { val rows = Dimension.dim() val cols = Dimension.dim() - return context.buildMatrix(rows.toInt(), cols.toInt(), initializer).coerce() + return context.buildMatrix(rows.toInt(), cols.toInt(), initializer).coerce() } public inline fun point(noinline initializer: A.(Int) -> T): DPoint { diff --git a/kmath-dimensions/src/commonTest/kotlin/kscience/dimensions/DMatrixContextTest.kt b/kmath-dimensions/src/commonTest/kotlin/space/kscience/dimensions/DMatrixContextTest.kt similarity index 100% rename from kmath-dimensions/src/commonTest/kotlin/kscience/dimensions/DMatrixContextTest.kt rename to kmath-dimensions/src/commonTest/kotlin/space/kscience/dimensions/DMatrixContextTest.kt diff --git a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt index 8023236ea..091b5db3f 100644 --- a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt +++ b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt @@ -184,4 +184,4 @@ public fun tan(arg: RealMatrix): RealMatrix = arg.map { kotlin.math.tan(it) } public fun ln(arg: RealMatrix): RealMatrix = arg.map { kotlin.math.ln(it) } -public fun log10(arg: RealMatrix): RealMatrix = arg.map { kotlin.math.log10(it) } \ No newline at end of file +public fun log10(arg: RealMatrix): RealMatrix = arg.map { kotlin.math.log10(it) } diff --git a/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/DoubleMatrixTest.kt b/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/DoubleMatrixTest.kt index b3e129c2e..a9c5f9e1a 100644 --- a/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/DoubleMatrixTest.kt +++ b/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/DoubleMatrixTest.kt @@ -32,7 +32,7 @@ internal class DoubleMatrixTest { @Test fun testSequenceToMatrix() { - val m = Sequence { + val m = Sequence { listOf( DoubleArray(10) { 10.0 }, DoubleArray(10) { 20.0 }, diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt index 73fa57c7b..5f35d0ab6 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt @@ -14,7 +14,7 @@ import space.kscience.kmath.operations.Ring * @param T the piece key type. * @param R the sub-function type. */ -public fun interface Piecewise { +public fun interface Piecewise { /** * Returns the appropriate sub-function for given piece key. */ @@ -23,7 +23,9 @@ public fun interface Piecewise { /** * Represents piecewise-defined function where all the sub-functions are polynomials. - * @param pieces An ordered list of range-polynomial pairs. The list does not in general guarantee that there are no "holes" in it. + * + * @property pieces An ordered list of range-polynomial pairs. The list does not in general guarantee that there are no + * "holes" in it. */ public interface PiecewisePolynomial> : Piecewise> { public val pieces: Collection, Polynomial>> @@ -45,7 +47,7 @@ public fun > PiecewisePolynomial( /** * An optimized piecewise which uses not separate pieces, but a range separated by delimiters. - * The pices search is logarithmic + * The pieces search is logarithmic */ private class OrderedPiecewisePolynomial>( override val pieces: List, Polynomial>>, diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt index ba77d7b25..f0c858b03 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt @@ -17,7 +17,7 @@ import kotlin.math.pow * * @param coefficients constant is the leftmost coefficient. */ -public class Polynomial(public val coefficients: List) { +public class Polynomial(public val coefficients: List) { override fun toString(): String = "Polynomial$coefficients" } @@ -69,7 +69,7 @@ public fun Polynomial.differentiate( public fun Polynomial.integrate( algebra: A, ): Polynomial where A : Field, A : NumericAlgebra = algebra { - val integratedCoefficients = buildList(coefficients.size + 1) { + val integratedCoefficients = buildList(coefficients.size + 1) { add(zero) coefficients.forEachIndexed{ index, t -> add(t / (number(index) + one)) } } diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt index f9c26e88b..4f565a893 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt @@ -18,7 +18,7 @@ public interface Integrand { public inline fun Integrand.getFeature(): T? = getFeature(T::class) -public class IntegrandValue(public val value: T) : IntegrandFeature { +public class IntegrandValue(public val value: T) : IntegrandFeature { override fun toString(): String = "Value($value)" } diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/UnivariateIntegrand.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/UnivariateIntegrand.kt index e265f54e8..7f68284a7 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/UnivariateIntegrand.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/UnivariateIntegrand.kt @@ -93,7 +93,7 @@ public fun UnivariateIntegrator.integrate( ): UnivariateIntegrand = integrate(UnivariateIntegrand(function, IntegrationRange(range), *features)) /** - * A shortcut method to integrate a [function] in [range] with additional [features]. + * A shortcut method to integrate a [function] in [range] with additional features. * The [function] is placed in the end position to allow passing a lambda. */ @UnstableKMathAPI diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/Interpolator.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/Interpolator.kt index c9ec0d527..f4a0abd5d 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/Interpolator.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/Interpolator.kt @@ -18,7 +18,7 @@ import space.kscience.kmath.structures.asBuffer /** * And interpolator for data with x column type [X], y column type [Y]. */ -public fun interface Interpolator { +public fun interface Interpolator { public fun interpolate(points: XYColumnarData): (X) -> Y } diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Line.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Line.kt index 5a6d23709..8c6ccb55e 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Line.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Line.kt @@ -5,7 +5,7 @@ package space.kscience.kmath.geometry -public data class Line(val base: V, val direction: V) +public data class Line(val base: V, val direction: V) public typealias Line2D = Line public typealias Line3D = Line diff --git a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Histogram.kt b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Histogram.kt index fcb5e96dc..31da4f392 100644 --- a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Histogram.kt +++ b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Histogram.kt @@ -13,14 +13,14 @@ import space.kscience.kmath.structures.asBuffer /** * The binned data element. Could be a histogram bin with a number of counts or an artificial construct */ -public interface Bin : Domain { +public interface Bin : Domain { /** * The value of this bin. */ public val value: Number } -public interface Histogram> { +public interface Histogram> { /** * Find existing bin, corresponding to given coordinates */ @@ -34,7 +34,7 @@ public interface Histogram> { public val bins: Iterable } -public fun interface HistogramBuilder { +public fun interface HistogramBuilder { /** * Increment appropriate bin diff --git a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/IndexedHistogramSpace.kt b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/IndexedHistogramSpace.kt index e5f6830c5..6d48d3738 100644 --- a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/IndexedHistogramSpace.kt +++ b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/IndexedHistogramSpace.kt @@ -18,7 +18,7 @@ import space.kscience.kmath.operations.invoke /** * A simple histogram bin based on domain */ -public data class DomainBin>( +public data class DomainBin>( public val domain: Domain, public override val value: Number, ) : Bin, Domain by domain diff --git a/kmath-histograms/src/jvmMain/kotlin/space/kscience/kmath/histogram/TreeHistogramSpace.kt b/kmath-histograms/src/jvmMain/kotlin/space/kscience/kmath/histogram/TreeHistogramSpace.kt index 8d05df68a..daea4a82e 100644 --- a/kmath-histograms/src/jvmMain/kotlin/space/kscience/kmath/histogram/TreeHistogramSpace.kt +++ b/kmath-histograms/src/jvmMain/kotlin/space/kscience/kmath/histogram/TreeHistogramSpace.kt @@ -36,9 +36,10 @@ public class TreeHistogram( } @OptIn(UnstableKMathAPI::class) -private class TreeHistogramBuilder(val binFactory: (Double) -> UnivariateDomain) : UnivariateHistogramBuilder { +@PublishedApi +internal class TreeHistogramBuilder(val binFactory: (Double) -> UnivariateDomain) : UnivariateHistogramBuilder { - private class BinCounter(val domain: UnivariateDomain, val counter: Counter = Counter.real()) : + internal class BinCounter(val domain: UnivariateDomain, val counter: Counter = Counter.real()) : ClosedFloatingPointRange by domain.range private val bins: TreeMap = TreeMap() @@ -80,10 +81,10 @@ private class TreeHistogramBuilder(val binFactory: (Double) -> UnivariateDomain) */ @UnstableKMathAPI public class TreeHistogramSpace( - private val binFactory: (Double) -> UnivariateDomain, + @PublishedApi internal val binFactory: (Double) -> UnivariateDomain, ) : Group, ScaleOperations { - public fun fill(block: UnivariateHistogramBuilder.() -> Unit): UnivariateHistogram = + public inline fun fill(block: UnivariateHistogramBuilder.() -> Unit): UnivariateHistogram = TreeHistogramBuilder(binFactory).apply(block).build() override fun add( @@ -115,8 +116,8 @@ public class TreeHistogramSpace( bin.domain.center, UnivariateBin( bin.domain, - value = bin.value * value.toDouble(), - standardDeviation = abs(bin.standardDeviation * value.toDouble()) + value = bin.value * value, + standardDeviation = abs(bin.standardDeviation * value) ) ) } diff --git a/kmath-kotlingrad/build.gradle.kts b/kmath-kotlingrad/build.gradle.kts index 01b42d7ba..d222ed7d6 100644 --- a/kmath-kotlingrad/build.gradle.kts +++ b/kmath-kotlingrad/build.gradle.kts @@ -18,14 +18,14 @@ readme { feature( "differentiable-mst-expression", - "src/main/kotlin/space/kscience/kmath/kotlingrad/DifferentiableMstExpression.kt", + "src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt", ) { "MST based DifferentiableExpression." } feature( - "differentiable-mst-expression", - "src/main/kotlin/space/kscience/kmath/kotlingrad/DifferentiableMstExpression.kt", + "scalars-adapters", + "src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt", ) { "Conversions between Kotlin∇'s SFun and MST" } diff --git a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayIterator.kt b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayIterator.kt index 140a212f8..d4cad8996 100644 --- a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayIterator.kt +++ b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayIterator.kt @@ -25,7 +25,7 @@ private class Nd4jArrayIndicesIterator(private val iterateOver: INDArray) : Iter internal fun INDArray.indicesIterator(): Iterator = Nd4jArrayIndicesIterator(this) -private sealed class Nd4jArrayIteratorBase(protected val iterateOver: INDArray) : Iterator> { +private sealed class Nd4jArrayIteratorBase(protected val iterateOver: INDArray) : Iterator> { private var i: Int = 0 final override fun hasNext(): Boolean = i < iterateOver.length() diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/optimization/Optimization.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/optimization/Optimization.kt index 4a1676412..15ae494f6 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/optimization/Optimization.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/optimization/Optimization.kt @@ -9,7 +9,7 @@ import space.kscience.kmath.expressions.Symbol public interface OptimizationFeature -public class OptimizationResult( +public class OptimizationResult( public val point: Map, public val value: T, public val features: Set = emptySet(), diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/ConstantSampler.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/ConstantSampler.kt deleted file mode 100644 index 0d38fe19b..000000000 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/ConstantSampler.kt +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2018-2021 KMath contributors. - * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. - */ - -package space.kscience.kmath.samplers - -import space.kscience.kmath.chains.BlockingBufferChain -import space.kscience.kmath.stat.RandomGenerator -import space.kscience.kmath.stat.Sampler -import space.kscience.kmath.structures.Buffer - -public class ConstantSampler(public val const: T) : Sampler { - override fun sample(generator: RandomGenerator): BlockingBufferChain = object : BlockingBufferChain { - override fun nextBufferBlocking(size: Int): Buffer = Buffer.boxing(size) { const } - override suspend fun fork(): BlockingBufferChain = this - } -} \ No newline at end of file diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/MCScope.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/MCScope.kt index 9e5c70a26..0e06fa162 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/MCScope.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/MCScope.kt @@ -6,6 +6,8 @@ package space.kscience.kmath.stat import kotlinx.coroutines.* +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.coroutineContext @@ -23,14 +25,18 @@ public class MCScope( /** * Launches a supervised Monte-Carlo scope */ -public suspend inline fun mcScope(generator: RandomGenerator, block: MCScope.() -> T): T = - MCScope(coroutineContext, generator).block() +public suspend inline fun mcScope(generator: RandomGenerator, block: MCScope.() -> T): T { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return MCScope(coroutineContext, generator).block() +} /** * Launch mc scope with a given seed */ -public suspend inline fun mcScope(seed: Long, block: MCScope.() -> T): T = - mcScope(RandomGenerator.default(seed), block) +public suspend inline fun mcScope(seed: Long, block: MCScope.() -> T): T { + contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } + return mcScope(RandomGenerator.default(seed), block) +} /** * Specialized launch for [MCScope]. Behaves the same way as regular [CoroutineScope.launch], but also stores the generator fork. diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Sampler.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Sampler.kt index 51ae78d3d..4c11fdd65 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Sampler.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Sampler.kt @@ -12,7 +12,7 @@ import space.kscience.kmath.structures.* import kotlin.jvm.JvmName /** - * Sampler that generates chains of values of type [T] in a chain of type [C]. + * Sampler that generates chains of values of type [T]. */ public fun interface Sampler { /** diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/SamplerAlgebra.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/SamplerAlgebra.kt index b3d607ab0..27465eff4 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/SamplerAlgebra.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/SamplerAlgebra.kt @@ -18,7 +18,7 @@ import space.kscience.kmath.operations.invoke * * @property value the value to sample. */ -public class ConstantSampler(public val value: T) : Sampler { +public class ConstantSampler(public val value: T) : Sampler { public override fun sample(generator: RandomGenerator): Chain = ConstantChain(value) } @@ -27,7 +27,7 @@ public class ConstantSampler(public val value: T) : Sampler { * * @property chainBuilder the provider of [Chain]. */ -public class BasicSampler(public val chainBuilder: (RandomGenerator) -> Chain) : Sampler { +public class BasicSampler(public val chainBuilder: (RandomGenerator) -> Chain) : Sampler { public override fun sample(generator: RandomGenerator): Chain = chainBuilder(generator) } @@ -36,7 +36,7 @@ public class BasicSampler(public val chainBuilder: (RandomGenerator) -> * * @property algebra the space to provide addition and scalar multiplication for [T]. */ -public class SamplerSpace(public val algebra: S) : Group>, +public class SamplerSpace(public val algebra: S) : Group>, ScaleOperations> where S : Group, S : ScaleOperations { public override val zero: Sampler = ConstantSampler(algebra.zero) diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Statistic.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Statistic.kt index 1b05aa9cd..f29b7415c 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Statistic.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Statistic.kt @@ -18,14 +18,14 @@ import space.kscience.kmath.structures.Buffer /** * A function, that transforms a buffer of random quantities to some resulting value */ -public interface Statistic { +public interface Statistic { public suspend fun evaluate(data: Buffer): R } -public interface BlockingStatistic: Statistic{ +public interface BlockingStatistic : Statistic { public fun evaluateBlocking(data: Buffer): R - override suspend fun evaluate(data: Buffer): R = evaluateBlocking(data) + override suspend fun evaluate(data: Buffer): R = evaluateBlocking(data) } /** @@ -34,7 +34,7 @@ public interface BlockingStatistic: Statistic{ * @param I - intermediate block type * @param R - result type */ -public interface ComposableStatistic : Statistic { +public interface ComposableStatistic : Statistic { //compute statistic on a single block public suspend fun computeIntermediate(data: Buffer): I diff --git a/kmath-symja/src/main/kotlin/space/kscience/kmath/symja/SymjaExpression.kt b/kmath-symja/src/main/kotlin/space/kscience/kmath/symja/SymjaExpression.kt index a6773c709..88f0c941e 100644 --- a/kmath-symja/src/main/kotlin/space/kscience/kmath/symja/SymjaExpression.kt +++ b/kmath-symja/src/main/kotlin/space/kscience/kmath/symja/SymjaExpression.kt @@ -14,7 +14,8 @@ import space.kscience.kmath.expressions.interpret import space.kscience.kmath.operations.NumericAlgebra /** - * Represents [MST] based [DifferentiableExpression] relying on [Symja](https://github.com/axkr/symja_android_library). + * Represents [MST] based [space.kscience.kmath.expressions.DifferentiableExpression] relying on + * [Symja](https://github.com/axkr/symja_android_library). * * The principle of this API is converting the [mst] to an [org.matheclipse.core.interfaces.IExpr], differentiating it * with Symja's [F.D], then converting [org.matheclipse.core.interfaces.IExpr] back to [MST]. diff --git a/kmath-tensors/README.md b/kmath-tensors/README.md index 6b991d5df..b19a55381 100644 --- a/kmath-tensors/README.md +++ b/kmath-tensors/README.md @@ -3,7 +3,7 @@ Common linear algebra operations on tensors. - [tensor algebra](src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic linear algebra operations on tensors (plus, dot, etc.) - - [tensor algebra with broadcasting](src/commonMain/kotlin/space/kscience/kmath/tensors/core/algebras/BroadcastDoubleTensorAlgebra.kt) : Basic linear algebra operations implemented with broadcasting. + - [tensor algebra with broadcasting](src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) : Basic linear algebra operations implemented with broadcasting. - [linear algebra operations](src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc. diff --git a/kmath-tensors/build.gradle.kts b/kmath-tensors/build.gradle.kts index b7f24dc6a..2eff2d821 100644 --- a/kmath-tensors/build.gradle.kts +++ b/kmath-tensors/build.gradle.kts @@ -24,20 +24,16 @@ readme { feature( id = "tensor algebra", - description = "Basic linear algebra operations on tensors (plus, dot, etc.)", ref = "src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt" - ) + ) { "Basic linear algebra operations on tensors (plus, dot, etc.)" } feature( id = "tensor algebra with broadcasting", - description = "Basic linear algebra operations implemented with broadcasting.", - ref = "src/commonMain/kotlin/space/kscience/kmath/tensors/core/algebras/BroadcastDoubleTensorAlgebra.kt" - ) + ref = "src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt" + ) { "Basic linear algebra operations implemented with broadcasting." } feature( id = "linear algebra operations", - description = "Advanced linear algebra operations like LU decomposition, SVD, etc.", ref = "src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt" - ) - -} \ No newline at end of file + ) { "Advanced linear algebra operations like LU decomposition, SVD, etc." } +} diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BufferedTensor.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BufferedTensor.kt index 315dc4505..87ac2fdf6 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BufferedTensor.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BufferedTensor.kt @@ -11,8 +11,8 @@ import space.kscience.kmath.tensors.core.internal.TensorLinearStructure */ public open class BufferedTensor internal constructor( override val shape: IntArray, - internal val mutableBuffer: MutableBuffer, - internal val bufferStart: Int + @PublishedApi internal val mutableBuffer: MutableBuffer, + @PublishedApi internal val bufferStart: Int, ) : Tensor { /** diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensor.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensor.kt index 41df50cba..8e5116336 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensor.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensor.kt @@ -11,7 +11,7 @@ import space.kscience.kmath.tensors.core.internal.toPrettyString /** * Default [BufferedTensor] implementation for [Double] values */ -public class DoubleTensor internal constructor( +public class DoubleTensor @PublishedApi internal constructor( shape: IntArray, buffer: DoubleArray, offset: Int = 0 diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt index 1fd46bd57..d182558c5 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt @@ -426,13 +426,11 @@ public open class DoubleTensorAlgebra : * @param transform the function to be applied to each element of the tensor. * @return the resulting tensor after applying the function. */ - public fun Tensor.map(transform: (Double) -> Double): DoubleTensor { - return DoubleTensor( - tensor.shape, - tensor.mutableBuffer.array().map { transform(it) }.toDoubleArray(), - tensor.bufferStart - ) - } + public inline fun Tensor.map(transform: (Double) -> Double): DoubleTensor = DoubleTensor( + tensor.shape, + tensor.mutableBuffer.array().map { transform(it) }.toDoubleArray(), + tensor.bufferStart + ) /** * Compares element-wise two tensors with a specified precision. @@ -519,14 +517,12 @@ public open class DoubleTensorAlgebra : * @param indices the [IntArray] of 1-dimensional indices * @return tensor with rows corresponding to rows by [indices] */ - public fun Tensor.rowsByIndices(indices: IntArray): DoubleTensor { - return stack(indices.map { this[it] }) - } + public fun Tensor.rowsByIndices(indices: IntArray): DoubleTensor = stack(indices.map { this[it] }) - internal fun Tensor.fold(foldFunction: (DoubleArray) -> Double): Double = + internal inline fun Tensor.fold(foldFunction: (DoubleArray) -> Double): Double = foldFunction(tensor.toDoubleArray()) - internal fun Tensor.foldDim( + internal inline fun Tensor.foldDim( foldFunction: (DoubleArray) -> Double, dim: Int, keepDim: Boolean, diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt index 7d3617547..4c9c00552 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt @@ -10,15 +10,15 @@ import space.kscience.kmath.nd.MutableStructure2D import space.kscience.kmath.nd.as1D import space.kscience.kmath.nd.as2D import space.kscience.kmath.operations.invoke -import space.kscience.kmath.tensors.core.* +import space.kscience.kmath.tensors.core.BufferedTensor +import space.kscience.kmath.tensors.core.DoubleTensor import space.kscience.kmath.tensors.core.DoubleTensorAlgebra -import space.kscience.kmath.tensors.core.DoubleTensorAlgebra.Companion.valueOrNull +import space.kscience.kmath.tensors.core.IntTensor import kotlin.math.abs import kotlin.math.min import kotlin.math.sign import kotlin.math.sqrt - internal fun BufferedTensor.vectorSequence(): Sequence> = sequence { val n = shape.size val vectorOffset = shape[n - 1] diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/tensorCastsUtils.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/tensorCastsUtils.kt index d965b6bcd..77264ff92 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/tensorCastsUtils.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/tensorCastsUtils.kt @@ -31,6 +31,7 @@ internal fun Tensor.toBufferedTensor(): BufferedTensor = when (this) { else -> this.copyToBufferedTensor() } +@PublishedApi internal val Tensor.tensor: DoubleTensor get() = when (this) { is DoubleTensor -> this diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/utils.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/utils.kt index 0ffaf39e7..e337eeef9 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/utils.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/utils.kt @@ -24,6 +24,7 @@ internal fun Buffer.array(): IntArray = when (this) { /** * Returns a reference to [DoubleArray] containing all of the elements of this [Buffer] or copy the data. */ +@PublishedApi internal fun Buffer.array(): DoubleArray = when (this) { is DoubleBuffer -> array else -> this.toDoubleArray() diff --git a/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleLinearOpsAlgebra.kt b/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleLinearOpsAlgebra.kt index 347bb683f..c525d5c83 100644 --- a/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleLinearOpsAlgebra.kt +++ b/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleLinearOpsAlgebra.kt @@ -183,7 +183,7 @@ internal class TestDoubleLinearOpsTensorAlgebra { } -private fun DoubleTensorAlgebra.testSVDFor(tensor: DoubleTensor, epsilon: Double = 1e-10): Unit { +private fun DoubleTensorAlgebra.testSVDFor(tensor: DoubleTensor, epsilon: Double = 1e-10) { val svd = tensor.svd() val tensorSVD = svd.first diff --git a/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleTensorAlgebra.kt b/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleTensorAlgebra.kt index e7e898008..85c3e74e3 100644 --- a/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleTensorAlgebra.kt +++ b/kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleTensorAlgebra.kt @@ -17,7 +17,7 @@ internal class TestDoubleTensorAlgebra { } @Test - fun TestDoubleDiv() = DoubleTensorAlgebra { + fun testDoubleDiv() = DoubleTensorAlgebra { val tensor = fromArray(intArrayOf(2), doubleArrayOf(2.0, 4.0)) val res = 2.0/tensor assertTrue(res.mutableBuffer.array() contentEquals doubleArrayOf(1.0, 0.5)) diff --git a/kmath-viktor/src/main/kotlin/space/kscience/kmath/viktor/ViktorStructureND.kt b/kmath-viktor/src/main/kotlin/space/kscience/kmath/viktor/ViktorStructureND.kt index b7abf4304..915637e2c 100644 --- a/kmath-viktor/src/main/kotlin/space/kscience/kmath/viktor/ViktorStructureND.kt +++ b/kmath-viktor/src/main/kotlin/space/kscience/kmath/viktor/ViktorStructureND.kt @@ -92,7 +92,7 @@ public class ViktorFieldND(public override val shape: IntArray) : FieldND, value: Double): ViktorStructureND = - (a.f64Buffer * value.toDouble()).asStructure() + (a.f64Buffer * value).asStructure() public override inline fun StructureND.plus(b: StructureND): ViktorStructureND = (f64Buffer + b.f64Buffer).asStructure()