From 9bc8e8fbf9ecfe3178e922f6a7ea23b92eaca207 Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Fri, 12 Mar 2021 22:52:18 +0300 Subject: [PATCH] WIP vector space refactor --- .../kscience/kmath/benchmarks/DotBenchmark.kt | 26 +-- .../benchmarks/LinearAlgebraBenchmark.kt | 13 +- .../structures/StructureWriteBenchmark.kt | 2 +- .../kscience/kmath/commons/linear/CMMatrix.kt | 15 +- .../kscience/kmath/commons/linear/CMSolver.kt | 8 +- .../kscience/kmath/linear/BufferMatrix.kt | 144 ------------ .../kscience/kmath/linear/LinearAlgebra.kt | 8 +- .../kscience/kmath/linear/LinearSpace.kt | 213 ++++++++++++++++++ .../kscience/kmath/linear/LupDecomposition.kt | 35 ++- .../kscience/kmath/linear/MatrixBuilder.kt | 52 ++--- .../kscience/kmath/linear/MatrixContext.kt | 173 -------------- .../kscience/kmath/linear/MatrixWrapper.kt | 30 +-- ...ealMatrixContext.kt => RealLinearSpace.kt} | 23 +- .../kscience/kmath/linear/VectorSpace.kt | 72 ------ .../kscience/kmath/linear/VirtualMatrix.kt | 2 - .../space/kscience/kmath/nd/NDStructure.kt | 6 +- .../space/kscience/kmath/nd/Structure1D.kt | 6 +- .../space/kscience/kmath/nd/Structure2D.kt | 12 +- .../kmath/structures/BufferAccessor2D.kt | 2 +- .../space/kscience/kmath/linear/MatrixTest.kt | 6 +- .../kscience/kmath/linear/RealLUSolverTest.kt | 8 +- .../kscience/kmath/dimensions/Wrappers.kt | 8 +- ...jmlMatrixContext.kt => EjmlLinearSpace.kt} | 16 +- .../space/kscience/kmath/real/RealMatrix.kt | 34 +-- .../kaceince/kmath/real/RealVectorTest.kt | 4 +- 25 files changed, 352 insertions(+), 566 deletions(-) delete mode 100644 kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferMatrix.kt create mode 100644 kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt delete mode 100644 kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixContext.kt rename kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/{RealMatrixContext.kt => RealLinearSpace.kt} (78%) delete mode 100644 kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VectorSpace.kt rename kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/{EjmlMatrixContext.kt => EjmlLinearSpace.kt} (80%) diff --git a/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/DotBenchmark.kt b/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/DotBenchmark.kt index 93b5c5549..8fb0c284e 100644 --- a/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/DotBenchmark.kt +++ b/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/DotBenchmark.kt @@ -4,11 +4,11 @@ import kotlinx.benchmark.Benchmark import kotlinx.benchmark.Blackhole import kotlinx.benchmark.Scope import kotlinx.benchmark.State -import space.kscience.kmath.commons.linear.CMMatrixContext -import space.kscience.kmath.ejml.EjmlMatrixContext -import space.kscience.kmath.linear.BufferMatrixContext +import space.kscience.kmath.commons.linear.CMLinearSpace +import space.kscience.kmath.ejml.EjmlLinearSpace +import space.kscience.kmath.linear.BufferLinearSpace import space.kscience.kmath.linear.Matrix -import space.kscience.kmath.linear.RealMatrixContext +import space.kscience.kmath.linear.RealLinearSpace import space.kscience.kmath.operations.RealField import space.kscience.kmath.operations.invoke import space.kscience.kmath.structures.Buffer @@ -24,44 +24,44 @@ internal class DotBenchmark { val matrix1 = Matrix.real(dim, dim) { i, j -> if (i <= j) random.nextDouble() else 0.0 } val matrix2 = Matrix.real(dim, dim) { i, j -> if (i <= j) random.nextDouble() else 0.0 } - val cmMatrix1 = CMMatrixContext { matrix1.toCM() } - val cmMatrix2 = CMMatrixContext { matrix2.toCM() } + val cmMatrix1 = CMLinearSpace { matrix1.toCM() } + val cmMatrix2 = CMLinearSpace { matrix2.toCM() } - val ejmlMatrix1 = EjmlMatrixContext { matrix1.toEjml() } - val ejmlMatrix2 = EjmlMatrixContext { matrix2.toEjml() } + val ejmlMatrix1 = EjmlLinearSpace { matrix1.toEjml() } + val ejmlMatrix2 = EjmlLinearSpace { matrix2.toEjml() } } @Benchmark fun cmDot(blackhole: Blackhole) { - CMMatrixContext { + CMLinearSpace { blackhole.consume(cmMatrix1 dot cmMatrix2) } } @Benchmark fun ejmlDot(blackhole: Blackhole) { - EjmlMatrixContext { + EjmlLinearSpace { blackhole.consume(ejmlMatrix1 dot ejmlMatrix2) } } @Benchmark fun ejmlDotWithConversion(blackhole: Blackhole) { - EjmlMatrixContext { + EjmlLinearSpace { blackhole.consume(matrix1 dot matrix2) } } @Benchmark fun bufferedDot(blackhole: Blackhole) { - BufferMatrixContext(RealField, Buffer.Companion::real).invoke { + BufferLinearSpace(RealField, Buffer.Companion::real).invoke { blackhole.consume(matrix1 dot matrix2) } } @Benchmark fun realDot(blackhole: Blackhole) { - RealMatrixContext { + RealLinearSpace { blackhole.consume(matrix1 dot matrix2) } } diff --git a/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/LinearAlgebraBenchmark.kt b/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/LinearAlgebraBenchmark.kt index 30cb6c0b9..85759d93c 100644 --- a/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/LinearAlgebraBenchmark.kt +++ b/examples/src/benchmarks/kotlin/space/kscience/kmath/benchmarks/LinearAlgebraBenchmark.kt @@ -4,13 +4,12 @@ import kotlinx.benchmark.Benchmark import kotlinx.benchmark.Blackhole import kotlinx.benchmark.Scope import kotlinx.benchmark.State -import space.kscience.kmath.commons.linear.CMMatrixContext -import space.kscience.kmath.commons.linear.CMMatrixContext.dot +import space.kscience.kmath.commons.linear.CMLinearSpace import space.kscience.kmath.commons.linear.inverse -import space.kscience.kmath.ejml.EjmlMatrixContext +import space.kscience.kmath.ejml.EjmlLinearSpace import space.kscience.kmath.ejml.inverse +import space.kscience.kmath.linear.LinearSpace import space.kscience.kmath.linear.Matrix -import space.kscience.kmath.linear.MatrixContext import space.kscience.kmath.linear.inverseWithLup import space.kscience.kmath.linear.real import kotlin.random.Random @@ -29,19 +28,19 @@ internal class LinearAlgebraBenchmark { @Benchmark fun kmathLupInversion(blackhole: Blackhole) { - blackhole.consume(MatrixContext.real.inverseWithLup(matrix)) + blackhole.consume(LinearSpace.real.inverseWithLup(matrix)) } @Benchmark fun cmLUPInversion(blackhole: Blackhole) { - with(CMMatrixContext) { + with(CMLinearSpace) { blackhole.consume(inverse(matrix)) } } @Benchmark fun ejmlInverse(blackhole: Blackhole) { - with(EjmlMatrixContext) { + with(EjmlLinearSpace) { blackhole.consume(inverse(matrix)) } } diff --git a/examples/src/main/kotlin/space/kscience/kmath/structures/StructureWriteBenchmark.kt b/examples/src/main/kotlin/space/kscience/kmath/structures/StructureWriteBenchmark.kt index 13d6f00e4..66d85edff 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/structures/StructureWriteBenchmark.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/structures/StructureWriteBenchmark.kt @@ -7,7 +7,7 @@ import kotlin.system.measureTimeMillis @Suppress("UNUSED_VARIABLE") fun main() { val n = 6000 - val structure = NDStructure.build(intArrayOf(n, n), Buffer.Companion::auto) { 1.0 } + val structure = NDStructure.buffered(intArrayOf(n, n), Buffer.Companion::auto) { 1.0 } structure.mapToBuffer { it + 1 } // warm-up val time1 = measureTimeMillis { val res = structure.mapToBuffer { it + 1 } } println("Structure mapping finished in $time1 millis") diff --git a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMMatrix.kt b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMMatrix.kt index 393b28973..53f96626d 100644 --- a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMMatrix.kt +++ b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMMatrix.kt @@ -3,6 +3,7 @@ package space.kscience.kmath.commons.linear import org.apache.commons.math3.linear.* import space.kscience.kmath.linear.* import space.kscience.kmath.misc.UnstableKMathAPI +import space.kscience.kmath.operations.RealField import space.kscience.kmath.structures.RealBuffer import kotlin.reflect.KClass import kotlin.reflect.cast @@ -55,7 +56,7 @@ public inline class CMMatrix(public val origin: RealMatrix) : Matrix { public fun RealMatrix.asMatrix(): CMMatrix = CMMatrix(this) -public class CMVector(public val origin: RealVector) : Point { +public class CMVector(public val origin: RealVector) : Vector { public override val size: Int get() = origin.dimension public override operator fun get(index: Int): Double = origin.getEntry(index) @@ -70,8 +71,8 @@ public fun Point.toCM(): CMVector = if (this is CMVector) this else { public fun RealVector.toPoint(): CMVector = CMVector(this) -public object CMMatrixContext : MatrixContext { - public override fun produce(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> Double): CMMatrix { +public object CMLinearSpace : LinearSpace { + public override fun buildMatrix(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> Double): CMMatrix { val array = Array(rows) { i -> DoubleArray(columns) { j -> initializer(i, j) } } return CMMatrix(Array2DRowRealMatrix(array)) } @@ -86,17 +87,15 @@ public object CMMatrixContext : MatrixContext { } } - override fun scale(a: Matrix, value: Double): Matrix = a.toCM().times(value) - public override fun Matrix.dot(other: Matrix): CMMatrix = CMMatrix(toCM().origin.multiply(other.toCM().origin)) - public override fun Matrix.dot(vector: Point): CMVector = + public override fun Matrix.dot(vector: Vector): CMVector = CMVector(toCM().origin.preMultiply(vector.toCM().origin)) public override operator fun Matrix.unaryMinus(): CMMatrix = - produce(rowNum, colNum) { i, j -> -get(i, j) } + buildMatrix(rowNum, colNum) { i, j -> -get(i, j) } public override fun add(a: Matrix, b: Matrix): CMMatrix = CMMatrix(a.toCM().origin.multiply(b.toCM().origin)) @@ -108,7 +107,7 @@ public object CMMatrixContext : MatrixContext { // CMMatrix(a.toCM().origin.scalarMultiply(k.toDouble())) public override operator fun Matrix.times(value: Double): CMMatrix = - produce(rowNum, colNum) { i, j -> get(i, j) * value } + buildMatrix(rowNum, colNum) { i, j -> get(i, j) * value } } public operator fun CMMatrix.plus(other: CMMatrix): CMMatrix = diff --git a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt index 3ce7ca9e6..ff4727aa2 100644 --- a/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt +++ b/kmath-commons/src/main/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt @@ -12,7 +12,7 @@ public enum class CMDecomposition { CHOLESKY } -public fun CMMatrixContext.solver( +public fun CMLinearSpace.solver( a: Matrix, decomposition: CMDecomposition = CMDecomposition.LUP ): DecompositionSolver = when (decomposition) { @@ -23,19 +23,19 @@ public fun CMMatrixContext.solver( CMDecomposition.CHOLESKY -> CholeskyDecomposition(a.toCM().origin).solver } -public fun CMMatrixContext.solve( +public fun CMLinearSpace.solve( a: Matrix, b: Matrix, decomposition: CMDecomposition = CMDecomposition.LUP ): CMMatrix = solver(a, decomposition).solve(b.toCM().origin).asMatrix() -public fun CMMatrixContext.solve( +public fun CMLinearSpace.solve( a: Matrix, b: Point, decomposition: CMDecomposition = CMDecomposition.LUP ): CMVector = solver(a, decomposition).solve(b.toCM().origin).toPoint() -public fun CMMatrixContext.inverse( +public fun CMLinearSpace.inverse( a: Matrix, decomposition: CMDecomposition = CMDecomposition.LUP ): CMMatrix = solver(a, decomposition).inverse.asMatrix() diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferMatrix.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferMatrix.kt deleted file mode 100644 index ba7b7358c..000000000 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/BufferMatrix.kt +++ /dev/null @@ -1,144 +0,0 @@ -package space.kscience.kmath.linear - -import space.kscience.kmath.nd.NDStructure -import space.kscience.kmath.nd.Structure2D -import space.kscience.kmath.operations.Ring -import space.kscience.kmath.operations.ScaleOperations -import space.kscience.kmath.operations.invoke -import space.kscience.kmath.structures.Buffer -import space.kscience.kmath.structures.BufferFactory -import space.kscience.kmath.structures.asSequence - -/** - * Alias for [Structure2D] with more familiar name. - * - * @param T the type of items. - */ -public typealias Matrix = Structure2D - -/** - * Basic implementation of Matrix space based on [NDStructure] - */ -public class BufferMatrixContext( - public override val elementContext: A, - private val bufferFactory: BufferFactory, -) : GenericMatrixContext> where A : Ring, A : ScaleOperations { - - public override fun produce(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> T): BufferMatrix { - val buffer = bufferFactory(rows * columns) { offset -> initializer(offset / columns, offset % columns) } - return BufferMatrix(rows, columns, buffer) - } - - override fun scale(a: Matrix, value: Double): Matrix = elementContext { - produce(a.rowNum, a.colNum) { i, j -> - a[i, j] * value - } - } - - public override fun point(size: Int, initializer: (Int) -> T): Point = bufferFactory(size, initializer) - - private fun Matrix.toBufferMatrix(): BufferMatrix = if (this is BufferMatrix) this else { - produce(rowNum, colNum) { i, j -> get(i, j) } - } - - public fun one(rows: Int, columns: Int): Matrix = VirtualMatrix(rows, columns) { i, j -> - if (i == j) 1.0 else 0.0 - } + DiagonalFeature - - public override infix fun Matrix.dot(other: Matrix): BufferMatrix { - require(colNum == other.rowNum) { "Matrix dot operation dimension mismatch: ($rowNum, $colNum) x (${other.rowNum}, ${other.colNum})" } - val bufferMatrix = toBufferMatrix() - val otherBufferMatrix = other.toBufferMatrix() - return elementContext { - produce(rowNum, other.colNum) { i, j -> - var res = one - for (l in 0 until colNum) { - res += bufferMatrix[i, l] * otherBufferMatrix[l, j] - } - res - } - } - } - - public override infix fun Matrix.dot(vector: Point): Point { - require(colNum == vector.size) { "Matrix dot vector operation dimension mismatch: ($rowNum, $colNum) x (${vector.size})" } - val bufferMatrix = toBufferMatrix() - return elementContext { - bufferFactory(rowNum) { i -> - var res = one - for (j in 0 until colNum) { - res += bufferMatrix[i, j] * vector[j] - } - res - } - } - } - - override fun add(a: Matrix, b: Matrix): BufferMatrix { - require(a.rowNum == b.rowNum) { "Row number mismatch in matrix addition. Left side: ${a.rowNum}, right side: ${b.rowNum}" } - require(a.colNum == b.colNum) { "Column number mismatch in matrix addition. Left side: ${a.colNum}, right side: ${b.colNum}" } - val aBufferMatrix = a.toBufferMatrix() - val bBufferMatrix = b.toBufferMatrix() - return elementContext { - produce(a.rowNum, a.colNum) { i, j -> - aBufferMatrix[i, j] + bBufferMatrix[i, j] - } - } - } - -// override fun multiply(a: Matrix, k: Number): BufferMatrix { -// val aBufferMatrix = a.toBufferMatrix() -// return elementContext { -// produce(a.rowNum, a.colNum) { i, j -> aBufferMatrix[i, j] * k.toDouble() } -// } -// } - - public companion object -} - -public class BufferMatrix( - public override val rowNum: Int, - public override val colNum: Int, - public val buffer: Buffer, -) : Matrix { - - init { - require(buffer.size == rowNum * colNum) { "Dimension mismatch for matrix structure" } - } - - override val shape: IntArray get() = intArrayOf(rowNum, colNum) - - public override operator fun get(index: IntArray): T = get(index[0], index[1]) - public override operator fun get(i: Int, j: Int): T = buffer[i * colNum + j] - - public override fun elements(): Sequence> = sequence { - for (i in 0 until rowNum) for (j in 0 until colNum) yield(intArrayOf(i, j) to get(i, j)) - } - - public override fun equals(other: Any?): Boolean { - if (this === other) return true - - return when (other) { - is NDStructure<*> -> NDStructure.contentEquals(this, other) - else -> false - } - } - - override fun hashCode(): Int { - var result = rowNum - result = 31 * result + colNum - result = 31 * result + buffer.hashCode() - return result - } - - public override fun toString(): String { - return if (rowNum <= 5 && colNum <= 5) - "Matrix(rowsNum = $rowNum, colNum = $colNum)\n" + - rows.asSequence().joinToString(prefix = "(", postfix = ")", separator = "\n ") { buffer -> - buffer.asSequence().joinToString(separator = "\t") { it.toString() } - } - else "Matrix(rowsNum = $rowNum, colNum = $colNum)" - } - - -} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearAlgebra.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearAlgebra.kt index ea871ccba..265a709e9 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearAlgebra.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearAlgebra.kt @@ -1,7 +1,7 @@ package space.kscience.kmath.linear +import space.kscience.kmath.nd.as1D import space.kscience.kmath.structures.Buffer -import space.kscience.kmath.structures.VirtualBuffer public typealias Point = Buffer @@ -10,16 +10,16 @@ public typealias Point = Buffer */ public interface LinearSolver { public fun solve(a: Matrix, b: Matrix): Matrix - public fun solve(a: Matrix, b: Point): Point = solve(a, b.asMatrix()).asPoint() + public fun solve(a: Matrix, b: Point): Point = solve(a, b.asMatrix()).asVector() public fun inverse(a: Matrix): Matrix } /** * Convert matrix to vector if it is possible */ -public fun Matrix.asPoint(): Point = +public fun Matrix.asVector(): Vector = if (this.colNum == 1) - VirtualBuffer(rowNum) { get(it, 0) } + as1D() else error("Can't convert matrix with more than one column to vector") 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 new file mode 100644 index 000000000..e0076cda9 --- /dev/null +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LinearSpace.kt @@ -0,0 +1,213 @@ +package space.kscience.kmath.linear + +import space.kscience.kmath.misc.UnstableKMathAPI +import space.kscience.kmath.nd.* +import space.kscience.kmath.operations.* +import space.kscience.kmath.structures.Buffer +import space.kscience.kmath.structures.BufferFactory +import kotlin.reflect.KClass + +/** + * Alias for [Structure2D] with more familiar name. + * + * @param T the type of items. + */ +public typealias Matrix = Structure2D + +/** + * Alias for [Structure1D] with more familiar name. + * + * @param T the type of items. + */ +public typealias Vector = Structure1D + +/** + * 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. + */ +public interface LinearSpace> { + public val elementAlgebra: A + + /** + * Produces a matrix with this context and given dimensions. + */ + public fun buildMatrix(rows: Int, columns: Int, initializer: A.(i: Int, j: Int) -> T): Matrix + + /** + * Produces a point compatible with matrix space (and possibly optimized for it). + */ + public fun buildVector(size: Int, initializer: A.(Int) -> T): Vector = + buildMatrix(1, size) { _, j -> initializer(j) }.as1D() + + public operator fun Matrix.unaryMinus(): Matrix = buildMatrix(rowNum, colNum) { i, j -> + -get(i, j) + } + + public operator fun Vector.unaryMinus(): Vector = buildVector(size) { + -get(it) + } + + /** + * Matrix sum + */ + public operator fun Matrix.plus(other: Matrix): Matrix = buildMatrix(rowNum, colNum) { i, j -> + get(i, j) + other[i, j] + } + + + /** + * Vector sum + */ + public operator fun Vector.plus(other: Vector): Vector = buildVector(size) { + get(it) + other[it] + } + + /** + * Matrix subtraction + */ + public operator fun Matrix.minus(other: Matrix): Matrix = buildMatrix(rowNum, colNum) { i, j -> + get(i, j) - other[i, j] + } + + /** + * Vector subtraction + */ + public operator fun Vector.minus(other: Vector): Vector = buildVector(size) { + get(it) - other[it] + } + + + /** + * Computes the dot product of this matrix and another one. + * + * @receiver the multiplicand. + * @param other the multiplier. + * @return the dot product. + */ + public infix fun Matrix.dot(other: Matrix): Matrix { + require(colNum == other.rowNum) { "Matrix dot operation dimension mismatch: ($rowNum, $colNum) x (${other.rowNum}, ${other.colNum})" } + return elementAlgebra { + buildMatrix(rowNum, other.colNum) { i, j -> + var res = zero + for (l in 0 until colNum) { + res += this@dot[i, l] * other[l, j] + } + res + } + } + } + + /** + * Computes the dot product of this matrix and a vector. + * + * @receiver the multiplicand. + * @param vector the multiplier. + * @return the dot product. + */ + public infix fun Matrix.dot(vector: Vector): Vector { + require(colNum == vector.size) { "Matrix dot vector operation dimension mismatch: ($rowNum, $colNum) x (${vector.size})" } + return elementAlgebra { + buildVector(rowNum) { i -> + var res = one + for (j in 0 until colNum) { + res += this@dot[i, j] * vector[j] + } + res + } + } + } + + /** + * Multiplies a matrix by its element. + * + * @receiver the multiplicand. + * @param value the multiplier. + * @receiver the product. + */ + public operator fun Matrix.times(value: T): Matrix = + buildMatrix(rowNum, colNum) { i, j -> get(i, j) * value } + + /** + * Multiplies an element by a matrix of it. + * + * @receiver the multiplicand. + * @param m the multiplier. + * @receiver the product. + */ + public operator fun T.times(m: Matrix): Matrix = m * this + + /** + * Multiplies a vector by its element. + * + * @receiver the multiplicand. + * @param value the multiplier. + * @receiver the product. + */ + public operator fun Vector.times(value: T): Vector = + buildVector(size) { i -> get(i) * value } + + /** + * Multiplies an element by a vector of it. + * + * @receiver the multiplicand. + * @param v the multiplier. + * @receiver the product. + */ + public operator fun T.times(v: Vector): Vector = v * this + + /** + * Gets a feature from the matrix. This function may return some additional features to + * [space.kscience.kmath.nd.NDStructure.getFeature]. + * + * @param F the type of feature. + * @param m the matrix. + * @param type the [KClass] instance of [F]. + * @return a feature object or `null` if it isn't present. + */ + @UnstableKMathAPI + public fun getFeature(m: Matrix, type: KClass): F? = m.getFeature(type) + + public companion object { + + /** + * A structured matrix with custom buffer + */ + public fun > buffered( + algebra: A, + bufferFactory: BufferFactory = Buffer.Companion::boxing, + ): LinearSpace = object : LinearSpace { + override val elementAlgebra: A = algebra + + override fun buildMatrix( + rows: Int, columns: Int, + initializer: A.(i: Int, j: Int) -> T, + ): Matrix = NDStructure.buffered(intArrayOf(rows, columns)) { (i, j) -> + algebra.initializer(i, j) + }.as2D() + + } + + /** + * Automatic buffered matrix, unboxed if it is possible + */ + public inline fun > auto(ring: A): LinearSpace = + buffered(ring, Buffer.Companion::auto) + } +} + +/** + * Gets a feature from the matrix. This function may return some additional features to + * [space.kscience.kmath.nd.NDStructure.getFeature]. + * + * @param T the type of items in the matrices. + * @param M the type of operated matrices. + * @param F the type of feature. + * @receiver the [LinearSpace] of [T]. + * @param m the matrix. + * @return a feature object or `null` if it isn't present. + */ +@UnstableKMathAPI +public inline fun LinearSpace.getFeature(m: Matrix): F? = getFeature(m, F::class) + diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt index a3d4cbc47..5d68534bc 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt @@ -12,7 +12,7 @@ import space.kscience.kmath.structures.MutableBufferFactory * Common implementation of [LupDecompositionFeature]. */ public class LupDecomposition( - public val context: MatrixContext>, + public val context: LinearSpace, public val elementContext: Field, public val lu: Matrix, public val pivot: IntArray, @@ -62,15 +62,14 @@ public class LupDecomposition( } @PublishedApi -internal fun , F : Field> GenericMatrixContext.abs(value: T): T = - if (value > elementContext.zero) value else elementContext { -value } +internal fun > LinearSpace>.abs(value: T): T = + if (value > elementAlgebra.zero) value else elementAlgebra { -value } /** * Create a lup decomposition of generic matrix. */ -public fun > MatrixContext>.lup( +public fun > LinearSpace>.lup( factory: MutableBufferFactory, - elementContext: Field, matrix: Matrix, checkSingular: (T) -> Boolean, ): LupDecomposition { @@ -80,7 +79,7 @@ public fun > MatrixContext>.lup( //TODO just waits for KEEP-176 BufferAccessor2D(matrix.rowNum, matrix.colNum, factory).run { - elementContext { + elementAlgebra { val lu = create(matrix) // Initialize permutation array and parity @@ -142,18 +141,18 @@ public fun > MatrixContext>.lup( for (row in col + 1 until m) lu[row, col] /= luDiag } - return LupDecomposition(this@lup, elementContext, lu.collect(), pivot, even) + return LupDecomposition(this@lup, elementAlgebra, lu.collect(), pivot, even) } } } -public inline fun , F : Field> GenericMatrixContext>.lup( +public inline fun > LinearSpace>.lup( matrix: Matrix, noinline checkSingular: (T) -> Boolean, -): LupDecomposition = lup(MutableBuffer.Companion::auto, elementContext, matrix, checkSingular) +): LupDecomposition = lup(MutableBuffer.Companion::auto, matrix, checkSingular) -public fun MatrixContext>.lup(matrix: Matrix): LupDecomposition = - lup(Buffer.Companion::real, RealField, matrix) { it < 1e-11 } +public fun LinearSpace.lup(matrix: Matrix): LupDecomposition = + lup(Buffer.Companion::real, matrix) { it < 1e-11 } public fun LupDecomposition.solveWithLup( factory: MutableBufferFactory, @@ -198,7 +197,7 @@ public fun LupDecomposition.solveWithLup( } } - return context.produce(pivot.size, matrix.colNum) { i, j -> bp[i, j] } + return context.buildMatrix(pivot.size, matrix.colNum) { i, j -> bp[i, j] } } } } @@ -210,18 +209,18 @@ public inline fun LupDecomposition.solveWithLup(matrix: Mat * Solves a system of linear equations *ax = b** using LUP decomposition. */ @OptIn(UnstableKMathAPI::class) -public inline fun , F : Field> GenericMatrixContext>.solveWithLup( +public inline fun > LinearSpace>.solveWithLup( a: Matrix, b: Matrix, noinline bufferFactory: MutableBufferFactory = MutableBuffer.Companion::auto, noinline checkSingular: (T) -> Boolean, ): Matrix { // Use existing decomposition if it is provided by matrix - val decomposition = a.getFeature() ?: lup(bufferFactory, elementContext, a, checkSingular) + val decomposition = a.getFeature() ?: lup(bufferFactory, a, checkSingular) return decomposition.solveWithLup(bufferFactory, b) } -public inline fun , F : Field> GenericMatrixContext>.inverseWithLup( +public inline fun > LinearSpace>.inverseWithLup( matrix: Matrix, noinline bufferFactory: MutableBufferFactory = MutableBuffer.Companion::auto, noinline checkSingular: (T) -> Boolean, @@ -229,15 +228,15 @@ public inline fun , F : Field> GenericMatrixContext @OptIn(UnstableKMathAPI::class) -public fun RealMatrixContext.solveWithLup(a: Matrix, b: Matrix): Matrix { +public fun RealLinearSpace.solveWithLup(a: Matrix, b: Matrix): Matrix { // Use existing decomposition if it is provided by matrix val bufferFactory: MutableBufferFactory = MutableBuffer.Companion::real - val decomposition: LupDecomposition = a.getFeature() ?: lup(bufferFactory, RealField, a) { it < 1e-11 } + val decomposition: LupDecomposition = a.getFeature() ?: lup(bufferFactory, a) { it < 1e-11 } return decomposition.solveWithLup(bufferFactory, b) } /** * Inverses a square matrix using LUP decomposition. Non square matrix will throw a error. */ -public fun RealMatrixContext.inverseWithLup(matrix: Matrix): Matrix = +public fun RealLinearSpace.inverseWithLup(matrix: Matrix): Matrix = solveWithLup(matrix, one(matrix.rowNum, matrix.colNum)) \ No newline at end of file diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixBuilder.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixBuilder.kt index c96834360..57bea5cb6 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixBuilder.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixBuilder.kt @@ -1,46 +1,30 @@ package space.kscience.kmath.linear -import space.kscience.kmath.nd.Structure2D -import space.kscience.kmath.structures.Buffer -import space.kscience.kmath.structures.BufferFactory -import space.kscience.kmath.structures.asBuffer +import space.kscience.kmath.misc.UnstableKMathAPI +import space.kscience.kmath.operations.Ring -public class MatrixBuilder(public val rows: Int, public val columns: Int) { - public operator fun invoke(vararg elements: T): Matrix { - require(rows * columns == elements.size) { "The number of elements ${elements.size} is not equal $rows * $columns" } - val buffer = elements.asBuffer() - return BufferMatrix(rows, columns, buffer) - } - //TODO add specific matrix builder functions like diagonal, etc +@UnstableKMathAPI +public fun LinearSpace>.matrix(rows: Int, columns: Int, vararg elements: T): Matrix { + require(rows * columns == elements.size) { "The number of elements ${elements.size} is not equal $rows * $columns" } + return buildMatrix(rows, columns) { i, j -> elements[i * columns + j] } } -public fun Structure2D.Companion.build(rows: Int, columns: Int): MatrixBuilder = MatrixBuilder(rows, columns) - -public fun Structure2D.Companion.row(vararg values: T): Matrix { - val buffer = values.asBuffer() - return BufferMatrix(1, values.size, buffer) +@UnstableKMathAPI +public fun LinearSpace>.vector(vararg elements: T): Vector { + return buildVector(elements.size, elements::get) } -public inline fun Structure2D.Companion.row( +public inline fun LinearSpace>.row( size: Int, - factory: BufferFactory = Buffer.Companion::auto, - noinline builder: (Int) -> T, -): Matrix { - val buffer = factory(size, builder) - return BufferMatrix(1, size, buffer) -} + crossinline builder: (Int) -> T, +): Matrix = buildMatrix(1, size) { _, j -> builder(j) } -public fun Structure2D.Companion.column(vararg values: T): Matrix { - val buffer = values.asBuffer() - return BufferMatrix(values.size, 1, buffer) -} +public fun LinearSpace>.row(vararg values: T): Matrix = row(values.size, values::get) -public inline fun Structure2D.Companion.column( +public inline fun LinearSpace>.column( size: Int, - factory: BufferFactory = Buffer.Companion::auto, - noinline builder: (Int) -> T, -): Matrix { - val buffer = factory(size, builder) - return BufferMatrix(size, 1, buffer) -} + crossinline builder: (Int) -> T, +): Matrix = buildMatrix(size, 1) { i, _ -> builder(i) } + +public fun LinearSpace>.column(vararg values: T): Matrix = column(values.size, values::get) \ No newline at end of file diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixContext.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixContext.kt deleted file mode 100644 index 6afec94e8..000000000 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixContext.kt +++ /dev/null @@ -1,173 +0,0 @@ -package space.kscience.kmath.linear - -import space.kscience.kmath.misc.UnstableKMathAPI -import space.kscience.kmath.operations.* -import space.kscience.kmath.structures.Buffer -import space.kscience.kmath.structures.BufferFactory -import space.kscience.kmath.structures.asSequence -import kotlin.reflect.KClass - -/** - * Basic operations on matrices. Operates on [Matrix]. - * - * @param T the type of items in the matrices. - * @param M the type of operated matrices. - */ -public interface MatrixContext> : GroupOperations>, ScaleOperations> { - /** - * Produces a matrix with this context and given dimensions. - */ - public fun produce(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> T): M - - /** - * Produces a point compatible with matrix space (and possibly optimized for it). - */ - public fun point(size: Int, initializer: (Int) -> T): Point = Buffer.boxing(size, initializer) - - @Suppress("UNCHECKED_CAST") - public override fun binaryOperationFunction(operation: String): (left: Matrix, right: Matrix) -> M = - when (operation) { - "dot" -> { left, right -> left dot right } - else -> super.binaryOperationFunction(operation) as (Matrix, Matrix) -> M - } - - /** - * Computes the dot product of this matrix and another one. - * - * @receiver the multiplicand. - * @param other the multiplier. - * @return the dot product. - */ - public infix fun Matrix.dot(other: Matrix): M - - /** - * Computes the dot product of this matrix and a vector. - * - * @receiver the multiplicand. - * @param vector the multiplier. - * @return the dot product. - */ - public infix fun Matrix.dot(vector: Point): Point - - /** - * Multiplies a matrix by its element. - * - * @receiver the multiplicand. - * @param value the multiplier. - * @receiver the product. - */ - public operator fun Matrix.times(value: T): M - - /** - * Multiplies an element by a matrix of it. - * - * @receiver the multiplicand. - * @param m the multiplier. - * @receiver the product. - */ - public operator fun T.times(m: Matrix): M = m * this - - /** - * Gets a feature from the matrix. This function may return some additional features to - * [kscience.kmath.nd.NDStructure.getFeature]. - * - * @param F the type of feature. - * @param m the matrix. - * @param type the [KClass] instance of [F]. - * @return a feature object or `null` if it isn't present. - */ - @UnstableKMathAPI - public fun getFeature(m: Matrix, type: KClass): F? = m.getFeature(type) - - public companion object { - - /** - * A structured matrix with custom buffer - */ - public fun buffered( - ring: A, - bufferFactory: BufferFactory = Buffer.Companion::boxing, - ): GenericMatrixContext> where A : Ring, A: ScaleOperations = BufferMatrixContext(ring, bufferFactory) - - /** - * Automatic buffered matrix, unboxed if it is possible - */ - public inline fun auto(ring: A): GenericMatrixContext> where A : Ring, A: ScaleOperations = - buffered(ring, Buffer.Companion::auto) - } -} - -/** - * Gets a feature from the matrix. This function may return some additional features to - * [kscience.kmath.nd.NDStructure.getFeature]. - * - * @param T the type of items in the matrices. - * @param M the type of operated matrices. - * @param F the type of feature. - * @receiver the [MatrixContext] of [T]. - * @param m the matrix. - * @return a feature object or `null` if it isn't present. - */ -@UnstableKMathAPI -public inline fun MatrixContext.getFeature(m: Matrix): F? = - getFeature(m, F::class) - -/** - * Partial implementation of [MatrixContext] for matrices of [Ring]. - * - * @param T the type of items in the matrices. - * @param A the type of ring of matrix elements. - * @param M the type of operated matrices. - */ -public interface GenericMatrixContext> : MatrixContext where A : Ring, A : ScaleOperations{ - /** - * The ring over matrix elements. - */ - public val elementContext: A - - public override infix fun Matrix.dot(other: Matrix): M { - //TODO add typed error - require(colNum == other.rowNum) { "Matrix dot operation dimension mismatch: ($rowNum, $colNum) x (${other.rowNum}, ${other.colNum})" } - - return produce(rowNum, other.colNum) { i, j -> - val row = rows[i] - val column = other.columns[j] - elementContext { sum(row.asSequence().zip(column.asSequence(), ::multiply)) } - } - } - - public override infix fun Matrix.dot(vector: Point): Point { - //TODO add typed error - require(colNum == vector.size) { "Matrix dot vector operation dimension mismatch: ($rowNum, $colNum) x (${vector.size})" } - - return point(rowNum) { i -> - val row = rows[i] - elementContext { sum(row.asSequence().zip(vector.asSequence(), ::multiply)) } - } - } - - public override operator fun Matrix.unaryMinus(): M = - produce(rowNum, colNum) { i, j -> elementContext { -get(i, j) } } - - public override fun add(a: Matrix, b: Matrix): M { - require(a.rowNum == b.rowNum && a.colNum == b.colNum) { - "Matrix operation dimension mismatch. [${a.rowNum},${a.colNum}] + [${b.rowNum},${b.colNum}]" - } - - return produce(a.rowNum, a.colNum) { i, j -> elementContext { a[i, j] + b[i, j] } } - } - - public override operator fun Matrix.minus(b: Matrix): M { - require(rowNum == b.rowNum && colNum == b.colNum) { - "Matrix operation dimension mismatch. [$rowNum,$colNum] - [${b.rowNum},${b.colNum}]" - } - - return produce(rowNum, colNum) { i, j -> elementContext { get(i, j) + b[i, j] } } - } -// -// public override fun multiply(a: Matrix, k: Number): M = -// produce(a.rowNum, a.colNum) { i, j -> elementContext { a[i, j] * k } } - - public override operator fun Matrix.times(value: T): M = - produce(rowNum, colNum) { i, j -> elementContext { get(i, j) * value } } -} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixWrapper.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixWrapper.kt index 69e4a916f..97f0acd61 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixWrapper.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixWrapper.kt @@ -1,14 +1,9 @@ package space.kscience.kmath.linear import space.kscience.kmath.misc.UnstableKMathAPI -import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.getFeature import space.kscience.kmath.operations.Ring -import space.kscience.kmath.operations.ScaleOperations -import space.kscience.kmath.structures.asBuffer -import kotlin.math.sqrt import kotlin.reflect.KClass -import kotlin.reflect.safeCast /** * A [Matrix] that holds [MatrixFeature] objects. @@ -24,7 +19,8 @@ public class MatrixWrapper internal constructor( * Get the first feature matching given class. Does not guarantee that matrix has only one feature matching the criteria */ @UnstableKMathAPI - override fun getFeature(type: KClass): T? = type.safeCast(features.find { type.isInstance(it) }) + @Suppress("UNCHECKED_CAST") + override fun getFeature(type: KClass): T? = features.singleOrNull { type.isInstance(it) } as? T ?: origin.getFeature(type) override fun equals(other: Any?): Boolean = origin == other @@ -61,35 +57,25 @@ public operator fun Matrix.plus(newFeatures: Collection Structure2D.Companion.square(vararg elements: T): Matrix { - val size: Int = sqrt(elements.size.toDouble()).toInt() - require(size * size == elements.size) { "The number of elements ${elements.size} is not a full square" } - val buffer = elements.asBuffer() - return BufferMatrix(size, size, buffer) -} - /** * Diagonal matrix of ones. The matrix is virtual no actual matrix is created */ -public fun GenericMatrixContext.one( +public fun LinearSpace>.one( rows: Int, columns: Int, -): Matrix where A : Ring, A : ScaleOperations = VirtualMatrix(rows, columns) { i, j -> - if (i == j) elementContext.one else elementContext.zero +): Matrix = VirtualMatrix(rows, columns) { i, j -> + if (i == j) elementAlgebra.one else elementAlgebra.zero } + UnitFeature /** * A virtual matrix of zeroes */ -public fun GenericMatrixContext.zero( +public fun LinearSpace>.zero( rows: Int, columns: Int, -): Matrix where A : Ring, A : ScaleOperations = VirtualMatrix(rows, columns) { _, _ -> - elementContext.zero +): Matrix = VirtualMatrix(rows, columns) { _, _ -> + elementAlgebra.zero } + ZeroFeature public class TransposedFeature(public val original: Matrix) : MatrixFeature diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealMatrixContext.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealLinearSpace.kt similarity index 78% rename from kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealMatrixContext.kt rename to kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealLinearSpace.kt index dbccb7536..6dc97c51e 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealMatrixContext.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/RealLinearSpace.kt @@ -1,34 +1,37 @@ package space.kscience.kmath.linear +import space.kscience.kmath.operations.RealField import space.kscience.kmath.operations.ScaleOperations import space.kscience.kmath.structures.RealBuffer -public object RealMatrixContext : MatrixContext>, ScaleOperations> { +public object RealLinearSpace : LinearSpace, ScaleOperations> { - public override fun produce( + override val elementAlgebra: RealField get() = RealField + + public override fun buildMatrix( rows: Int, columns: Int, initializer: (i: Int, j: Int) -> Double, - ): BufferMatrix { + ): Matrix { val buffer = RealBuffer(rows * columns) { offset -> initializer(offset / columns, offset % columns) } - return BufferMatrix(rows, columns, buffer) + return BufferMatrix(rows, columns, buffer) } public fun Matrix.toBufferMatrix(): BufferMatrix = if (this is BufferMatrix) this else { - produce(rowNum, colNum) { i, j -> get(i, j) } + buildMatrix(rowNum, colNum) { i, j -> get(i, j) } } public fun one(rows: Int, columns: Int): Matrix = VirtualMatrix(rows, columns) { i, j -> if (i == j) 1.0 else 0.0 } + DiagonalFeature - override fun Matrix.unaryMinus(): Matrix = produce(rowNum, colNum) { i, j -> -get(i, j) } + override fun Matrix.unaryMinus(): Matrix = buildMatrix(rowNum, colNum) { i, j -> -get(i, j) } public override infix fun Matrix.dot(other: Matrix): BufferMatrix { require(colNum == other.rowNum) { "Matrix dot operation dimension mismatch: ($rowNum, $colNum) x (${other.rowNum}, ${other.colNum})" } val bufferMatrix = toBufferMatrix() val otherBufferMatrix = other.toBufferMatrix() - return produce(rowNum, other.colNum) { i, j -> + return buildMatrix(rowNum, other.colNum) { i, j -> var res = 0.0 for (l in 0 until colNum) { res += bufferMatrix[i, l] * otherBufferMatrix[l, j] @@ -54,14 +57,14 @@ public object RealMatrixContext : MatrixContext>, S require(a.colNum == b.colNum) { "Column number mismatch in matrix addition. Left side: ${a.colNum}, right side: ${b.colNum}" } val aBufferMatrix = a.toBufferMatrix() val bBufferMatrix = b.toBufferMatrix() - return produce(a.rowNum, a.colNum) { i, j -> + return buildMatrix(a.rowNum, a.colNum) { i, j -> aBufferMatrix[i, j] + bBufferMatrix[i, j] } } override fun scale(a: Matrix, value: Double): BufferMatrix { val bufferMatrix = a.toBufferMatrix() - return produce(a.rowNum, a.colNum) { i, j -> bufferMatrix[i, j] * value } + return buildMatrix(a.rowNum, a.colNum) { i, j -> bufferMatrix[i, j] * value } } override fun Matrix.times(value: Double): BufferMatrix = scale(this, value) @@ -82,4 +85,4 @@ public object RealMatrixContext : MatrixContext>, S /** * Partially optimized real-valued matrix */ -public val MatrixContext.Companion.real: RealMatrixContext get() = RealMatrixContext +public val LinearSpace.Companion.real: RealLinearSpace get() = RealLinearSpace diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VectorSpace.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VectorSpace.kt deleted file mode 100644 index cfacf6826..000000000 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VectorSpace.kt +++ /dev/null @@ -1,72 +0,0 @@ -package space.kscience.kmath.linear - -import space.kscience.kmath.operations.Group -import space.kscience.kmath.operations.RealField -import space.kscience.kmath.operations.ScaleOperations -import space.kscience.kmath.operations.invoke -import space.kscience.kmath.structures.Buffer -import space.kscience.kmath.structures.BufferFactory - -/** - * A linear space for vectors. - * Could be used on any point-like structure - */ -public interface VectorSpace : Group>, ScaleOperations> - where A : Group, A : ScaleOperations { - public val size: Int - public val algebra: A - override val zero: Point get() = produce { algebra.zero } - - public fun produce(initializer: A.(Int) -> T): Point - - override fun add(a: Point, b: Point): Point = produce { algebra { a[it] + b[it] } } - - override fun scale(a: Point, value: Double): Point = produce { algebra.scale(a[it], value) } - - override fun Point.unaryMinus(): Point = produce { -get(it) } - - //TODO add basis - - public companion object { - private val realSpaceCache: MutableMap> = hashMapOf() - - /** - * Non-boxing double vector space - */ - public fun real(size: Int): BufferVectorSpace = realSpaceCache.getOrPut(size) { - BufferVectorSpace( - size, - RealField, - Buffer.Companion::auto - ) - } - - /** - * A structured vector space with custom buffer - */ - public fun buffered( - size: Int, - space: A, - bufferFactory: BufferFactory = Buffer.Companion::boxing, - ): BufferVectorSpace where A : Group, A : ScaleOperations = - BufferVectorSpace(size, space, bufferFactory) - - /** - * Automatic buffered vector, unboxed if it is possible - */ - public inline fun auto( - size: Int, - space: A, - ): VectorSpace where A : Group, A : ScaleOperations = - buffered(size, space, Buffer.Companion::auto) - } -} - - -public class BufferVectorSpace( - override val size: Int, - override val algebra: A, - public val bufferFactory: BufferFactory, -) : VectorSpace where A : Group, A : ScaleOperations { - override fun produce(initializer: A.(Int) -> T): Buffer = bufferFactory(size) { algebra.initializer(it) } -} diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VirtualMatrix.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VirtualMatrix.kt index 26b1899a1..11699ce2f 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VirtualMatrix.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/VirtualMatrix.kt @@ -31,6 +31,4 @@ public class VirtualMatrix( result = 31 * result + generator.hashCode() return result } - - } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/NDStructure.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/NDStructure.kt index 137772632..62e126694 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/NDStructure.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/NDStructure.kt @@ -74,7 +74,7 @@ public interface NDStructure { * * Strides should be reused if possible. */ - public fun build( + public fun buffered( strides: Strides, bufferFactory: BufferFactory = Buffer.Companion::boxing, initializer: (IntArray) -> T, @@ -94,11 +94,11 @@ public interface NDStructure { crossinline initializer: (IntArray) -> T, ): NDBuffer = NDBuffer(strides, Buffer.auto(type, strides.linearSize) { i -> initializer(strides.index(i)) }) - public fun build( + public fun buffered( shape: IntArray, bufferFactory: BufferFactory = Buffer.Companion::boxing, initializer: (IntArray) -> T, - ): NDBuffer = build(DefaultStrides(shape), bufferFactory, initializer) + ): NDBuffer = buffered(DefaultStrides(shape), bufferFactory, initializer) public inline fun auto( shape: IntArray, diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure1D.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure1D.kt index e83485ff0..c54bfeed9 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure1D.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure1D.kt @@ -46,7 +46,11 @@ private inline class Buffer1DWrapper(val buffer: Buffer) : Structure1D * Represent a [NDStructure] as [Structure1D]. Throw error in case of dimension mismatch */ public fun NDStructure.as1D(): Structure1D = if (shape.size == 1) { - if (this is NDBuffer) Buffer1DWrapper(this.buffer) else Structure1DWrapper(this) + when (this) { + is Structure1DWrapper -> this + is NDBuffer -> Buffer1DWrapper(this.buffer) + else -> Structure1DWrapper(this) + } } else error("Can't create 1d-structure from ${shape.size}d-structure") diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure2D.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure2D.kt index fcc8c0d7e..0098eeb3b 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure2D.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Structure2D.kt @@ -1,7 +1,5 @@ package space.kscience.kmath.nd -import space.kscience.kmath.linear.BufferMatrix -import space.kscience.kmath.linear.RealMatrixContext import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.VirtualBuffer @@ -54,15 +52,7 @@ public interface Structure2D : NDStructure { for (j in 0 until colNum) yield(intArrayOf(i, j) to get(i, j)) } - public companion object { - public inline fun real( - rows: Int, - columns: Int, - crossinline init: (i: Int, j: Int) -> Double, - ): BufferMatrix = RealMatrixContext.produce(rows,columns) { i, j -> - init(i, j) - } - } + public companion object } /** 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 fd440a344..d9e37ebd8 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 @@ -25,7 +25,7 @@ internal class BufferAccessor2D( public fun create(mat: Structure2D): MutableBuffer = create { i, j -> mat[i, j] } //TODO optimize wrapper - public fun MutableBuffer.collect(): Structure2D = NDStructure.build( + public fun MutableBuffer.collect(): Structure2D = NDStructure.buffered( DefaultStrides(intArrayOf(rowNum, colNum)), factory ) { (i, j) -> diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/MatrixTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/MatrixTest.kt index 75967f024..5cf83889a 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/MatrixTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/MatrixTest.kt @@ -10,7 +10,7 @@ import kotlin.test.assertEquals class MatrixTest { @Test fun testTranspose() { - val matrix = MatrixContext.real.one(3, 3) + val matrix = LinearSpace.real.one(3, 3) val transposed = matrix.transpose() assertEquals(matrix, transposed) } @@ -39,7 +39,7 @@ class MatrixTest { infix fun Matrix.pow(power: Int): Matrix { var res = this repeat(power - 1) { - res = RealMatrixContext.invoke { res dot this@pow } + res = RealLinearSpace.invoke { res dot this@pow } } return res } @@ -52,7 +52,7 @@ class MatrixTest { val firstMatrix = NDStructure.auto(2, 3) { (i, j) -> (i + j).toDouble() }.as2D() val secondMatrix = NDStructure.auto(3, 2) { (i, j) -> (i + j).toDouble() }.as2D() - MatrixContext.real.run { + LinearSpace.real.run { // val firstMatrix = produce(2, 3) { i, j -> (i + j).toDouble() } // val secondMatrix = produce(3, 2) { i, j -> (i + j).toDouble() } val result = firstMatrix dot secondMatrix diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/RealLUSolverTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/RealLUSolverTest.kt index f1289801a..4d6b8f5be 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/RealLUSolverTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/RealLUSolverTest.kt @@ -7,8 +7,8 @@ class RealLUSolverTest { @Test fun testInvertOne() { - val matrix = MatrixContext.real.one(2, 2) - val inverted = MatrixContext.real.inverseWithLup(matrix) + val matrix = LinearSpace.real.one(2, 2) + val inverted = LinearSpace.real.inverseWithLup(matrix) assertEquals(matrix, inverted) } @@ -19,7 +19,7 @@ class RealLUSolverTest { 1.0, 3.0 ) - MatrixContext.real.run { + LinearSpace.real.run { val lup = lup(matrix) //Check determinant @@ -36,7 +36,7 @@ class RealLUSolverTest { 1.0, 3.0 ) - val inverted = MatrixContext.real.inverseWithLup(matrix) + val inverted = LinearSpace.real.inverseWithLup(matrix) val expected = Matrix.square( 0.375, -0.125, 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 237824a39..89ff97f14 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 @@ -77,7 +77,7 @@ public inline class DPointWrapper(public val point: Point) /** * Basic operations on dimension-safe matrices. Operates on [Matrix] */ -public inline class DMatrixContext(public val context: MatrixContext>) { +public inline class DMatrixContext(public val context: LinearSpace>) { public inline fun Matrix.coerce(): DMatrix { require(rowNum == Dimension.dim().toInt()) { "Row number mismatch: expected ${Dimension.dim()} but found $rowNum" @@ -96,14 +96,14 @@ public inline class DMatrixContext(public val context: MatrixContext produce(noinline initializer: (i: Int, j: Int) -> T): DMatrix { val rows = Dimension.dim() val cols = Dimension.dim() - return context.produce(rows.toInt(), cols.toInt(), initializer).coerce() + return context.buildMatrix(rows.toInt(), cols.toInt(), initializer).coerce() } public inline fun point(noinline initializer: (Int) -> T): DPoint { val size = Dimension.dim() return DPoint.coerceUnsafe( - context.point( + context.buildVector( size.toInt(), initializer ) @@ -136,7 +136,7 @@ public inline class DMatrixContext(public val context: MatrixContext).transpose() }.coerce() public companion object { - public val real: DMatrixContext = DMatrixContext(MatrixContext.real) + public val real: DMatrixContext = DMatrixContext(LinearSpace.real) } } diff --git a/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrixContext.kt b/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt similarity index 80% rename from kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrixContext.kt rename to kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt index 95c465975..c3f93ca55 100644 --- a/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrixContext.kt +++ b/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt @@ -11,7 +11,7 @@ import space.kscience.kmath.operations.ScaleOperations * * @author Iaroslav Postovalov */ -public object EjmlMatrixContext : MatrixContext, ScaleOperations> { +public object EjmlLinearSpace : LinearSpace, ScaleOperations> { /** * Converts this matrix to EJML one. @@ -19,7 +19,7 @@ public object EjmlMatrixContext : MatrixContext, ScaleOperat @OptIn(UnstableKMathAPI::class) public fun Matrix.toEjml(): EjmlMatrix = when (val matrix = origin) { is EjmlMatrix -> matrix - else -> produce(rowNum, colNum) { i, j -> get(i, j) } + else -> buildMatrix(rowNum, colNum) { i, j -> get(i, j) } } /** @@ -30,14 +30,14 @@ public object EjmlMatrixContext : MatrixContext, ScaleOperat (0 until it.numRows()).forEach { row -> it[row, 0] = get(row) } }) - override fun produce(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> Double): EjmlMatrix = + override fun buildMatrix(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> Double): EjmlMatrix = EjmlMatrix(SimpleMatrix(rows, columns).also { (0 until rows).forEach { row -> (0 until columns).forEach { col -> it[row, col] = initializer(row, col) } } }) - override fun point(size: Int, initializer: (Int) -> Double): Point = + override fun buildVector(size: Int, initializer: (Int) -> Double): Point = EjmlVector(SimpleMatrix(size, 1).also { (0 until it.numRows()).forEach { row -> it[row, 0] = initializer(row) } }) @@ -58,7 +58,7 @@ public object EjmlMatrixContext : MatrixContext, ScaleOperat EjmlMatrix(toEjml().origin - b.toEjml().origin) public override fun scale(a: Matrix, value: Double): EjmlMatrix = - produce(a.rowNum, a.colNum) { i, j -> a[i, j] * value } + buildMatrix(a.rowNum, a.colNum) { i, j -> a[i, j] * value } public override operator fun Matrix.times(value: Double): EjmlMatrix = EjmlMatrix(toEjml().origin.scale(value)) @@ -72,7 +72,7 @@ public object EjmlMatrixContext : MatrixContext, ScaleOperat * @return the solution for 'x' that is n by p. * @author Iaroslav Postovalov */ -public fun EjmlMatrixContext.solve(a: Matrix, b: Matrix): EjmlMatrix = +public fun EjmlLinearSpace.solve(a: Matrix, b: Matrix): EjmlMatrix = EjmlMatrix(a.toEjml().origin.solve(b.toEjml().origin)) /** @@ -83,10 +83,10 @@ public fun EjmlMatrixContext.solve(a: Matrix, b: Matrix): EjmlMa * @return the solution for 'x' that is n by p. * @author Iaroslav Postovalov */ -public fun EjmlMatrixContext.solve(a: Matrix, b: Point): EjmlVector = +public fun EjmlLinearSpace.solve(a: Matrix, b: Point): EjmlVector = EjmlVector(a.toEjml().origin.solve(b.toEjml().origin)) @OptIn(UnstableKMathAPI::class) public fun EjmlMatrix.inverted(): EjmlMatrix = getFeature>()!!.inverse as EjmlMatrix -public fun EjmlMatrixContext.inverse(matrix: Matrix): Matrix = matrix.toEjml().inverted() \ No newline at end of file +public fun EjmlLinearSpace.inverse(matrix: Matrix): Matrix = matrix.toEjml().inverted() \ No newline at end of file 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 30d002498..b93c430f9 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 @@ -22,14 +22,14 @@ import kotlin.math.pow public typealias RealMatrix = Matrix public fun realMatrix(rowNum: Int, colNum: Int, initializer: (i: Int, j: Int) -> Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum, initializer) + LinearSpace.real.buildMatrix(rowNum, colNum, initializer) public fun Array.toMatrix(): RealMatrix { - return MatrixContext.real.produce(size, this[0].size) { row, col -> this[row][col] } + return LinearSpace.real.buildMatrix(size, this[0].size) { row, col -> this[row][col] } } public fun Sequence.toMatrix(): RealMatrix = toList().let { - MatrixContext.real.produce(it.size, it[0].size) { row, col -> it[row][col] } + LinearSpace.real.buildMatrix(it.size, it[0].size) { row, col -> it[row][col] } } public fun RealMatrix.repeatStackVertical(n: Int): RealMatrix = @@ -42,37 +42,37 @@ public fun RealMatrix.repeatStackVertical(n: Int): RealMatrix = */ public operator fun RealMatrix.times(double: Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] * double } public operator fun RealMatrix.plus(double: Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] + double } public operator fun RealMatrix.minus(double: Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] - double } public operator fun RealMatrix.div(double: Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] / double } public operator fun Double.times(matrix: RealMatrix): RealMatrix = - MatrixContext.real.produce(matrix.rowNum, matrix.colNum) { row, col -> + LinearSpace.real.buildMatrix(matrix.rowNum, matrix.colNum) { row, col -> this * matrix[row, col] } public operator fun Double.plus(matrix: RealMatrix): RealMatrix = - MatrixContext.real.produce(matrix.rowNum, matrix.colNum) { row, col -> + LinearSpace.real.buildMatrix(matrix.rowNum, matrix.colNum) { row, col -> this + matrix[row, col] } public operator fun Double.minus(matrix: RealMatrix): RealMatrix = - MatrixContext.real.produce(matrix.rowNum, matrix.colNum) { row, col -> + LinearSpace.real.buildMatrix(matrix.rowNum, matrix.colNum) { row, col -> this - matrix[row, col] } @@ -87,20 +87,20 @@ public operator fun Double.minus(matrix: RealMatrix): RealMatrix = @UnstableKMathAPI public operator fun RealMatrix.times(other: RealMatrix): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> this[row, col] * other[row, col] } + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] * other[row, col] } public operator fun RealMatrix.plus(other: RealMatrix): RealMatrix = - MatrixContext.real.add(this, other) + LinearSpace.real.add(this, other) public operator fun RealMatrix.minus(other: RealMatrix): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { row, col -> this[row, col] - other[row, col] } + LinearSpace.real.buildMatrix(rowNum, colNum) { row, col -> this[row, col] - other[row, col] } /* * Operations on columns */ public inline fun RealMatrix.appendColumn(crossinline mapper: (Buffer) -> Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum + 1) { row, col -> + LinearSpace.real.buildMatrix(rowNum, colNum + 1) { row, col -> if (col < colNum) this[row, col] else @@ -108,7 +108,7 @@ public inline fun RealMatrix.appendColumn(crossinline mapper: (Buffer) - } public fun RealMatrix.extractColumns(columnRange: IntRange): RealMatrix = - MatrixContext.real.produce(rowNum, columnRange.count()) { row, col -> + LinearSpace.real.buildMatrix(rowNum, columnRange.count()) { row, col -> this[row, columnRange.first + col] } @@ -141,14 +141,14 @@ public fun RealMatrix.max(): Double? = elements().map { (_, value) -> value }.ma public fun RealMatrix.average(): Double = elements().map { (_, value) -> value }.average() public inline fun RealMatrix.map(crossinline transform: (Double) -> Double): RealMatrix = - MatrixContext.real.produce(rowNum, colNum) { i, j -> + LinearSpace.real.buildMatrix(rowNum, colNum) { i, j -> transform(get(i, j)) } /** * Inverse a square real matrix using LUP decomposition */ -public fun RealMatrix.inverseWithLup(): RealMatrix = MatrixContext.real.inverseWithLup(this) +public fun RealMatrix.inverseWithLup(): RealMatrix = LinearSpace.real.inverseWithLup(this) //extended operations diff --git a/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/RealVectorTest.kt b/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/RealVectorTest.kt index 463c68681..5d032de67 100644 --- a/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/RealVectorTest.kt +++ b/kmath-for-real/src/commonTest/kotlin/kaceince/kmath/real/RealVectorTest.kt @@ -1,6 +1,6 @@ package kaceince.kmath.real -import space.kscience.kmath.linear.MatrixContext +import space.kscience.kmath.linear.LinearSpace import space.kscience.kmath.linear.asMatrix import space.kscience.kmath.linear.real import space.kscience.kmath.linear.transpose @@ -32,7 +32,7 @@ internal class RealVectorTest { val vector2 = Buffer.real(5) { 5 - it.toDouble() } val matrix1 = vector1.asMatrix() val matrix2 = vector2.asMatrix().transpose() - val product = MatrixContext.real { matrix1 dot matrix2 } + val product = LinearSpace.real { matrix1 dot matrix2 } assertEquals(5.0, product[1, 0]) assertEquals(6.0, product[2, 2]) }