diff --git a/CHANGELOG.md b/CHANGELOG.md index 2396c6b27..f4d279362 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ - Refactor histograms. They are marked as prototype - `Complex` and related features moved to a separate module `kmath-complex` - Refactor AlgebraElement +- Add `out` projection to `Buffer` generic ### Deprecated diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts index 054945eb7..5439d46dc 100644 --- a/examples/build.gradle.kts +++ b/examples/build.gradle.kts @@ -76,6 +76,14 @@ benchmark { iterationTimeUnit = "ms" // time unity for iterationTime, default is seconds include("DotBenchmark") } + + configurations.register("expressions") { + warmups = 1 // number of warmup iterations + iterations = 3 // number of iterations + iterationTime = 500 // time in seconds per iteration + iterationTimeUnit = "ms" // time unity for iterationTime, default is seconds + include("ExpressionsInterpretersBenchmark") + } } kotlin.sourceSets.all { diff --git a/kmath-ast/src/commonMain/kotlin/kscience/kmath/ast/MstExpression.kt b/kmath-ast/src/commonMain/kotlin/kscience/kmath/ast/MstExpression.kt index 03d33aa2b..8da96f770 100644 --- a/kmath-ast/src/commonMain/kotlin/kscience/kmath/ast/MstExpression.kt +++ b/kmath-ast/src/commonMain/kotlin/kscience/kmath/ast/MstExpression.kt @@ -21,8 +21,17 @@ public class MstExpression>(public val algebra: A, public null } ?: arguments.getValue(StringSymbol(value)) - override fun unaryOperationFunction(operation: String): (arg: T) -> T = algebra.unaryOperationFunction(operation) - override fun binaryOperationFunction(operation: String): (left: T, right: T) -> T = algebra.binaryOperationFunction(operation) + override fun unaryOperation(operation: String, arg: T): T = + algebra.unaryOperation(operation, arg) + + override fun binaryOperation(operation: String, left: T, right: T): T = + algebra.binaryOperation(operation, left, right) + + override fun unaryOperationFunction(operation: String): (arg: T) -> T = + algebra.unaryOperationFunction(operation) + + override fun binaryOperationFunction(operation: String): (left: T, right: T) -> T = + algebra.binaryOperationFunction(operation) @Suppress("UNCHECKED_CAST") override fun number(value: Number): T = if (algebra is NumericAlgebra<*>) diff --git a/kmath-core/api/kmath-core.api b/kmath-core/api/kmath-core.api index e58e5d45d..1bfc13c3b 100644 --- a/kmath-core/api/kmath-core.api +++ b/kmath-core/api/kmath-core.api @@ -4,7 +4,7 @@ public abstract interface class kscience/kmath/domains/Domain { } public final class kscience/kmath/domains/HyperSquareDomain : kscience/kmath/domains/RealDomain { - public synthetic fun ([D[DLkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lkscience/kmath/structures/Buffer;Lkscience/kmath/structures/Buffer;)V public fun contains (Lkscience/kmath/structures/Buffer;)Z public fun getDimension ()I public fun getLowerBound (I)Ljava/lang/Double; diff --git a/kmath-core/src/commonMain/kotlin/kscience/kmath/domains/HyperSquareDomain.kt b/kmath-core/src/commonMain/kotlin/kscience/kmath/domains/HyperSquareDomain.kt index b45cf6bf5..20f19864f 100644 --- a/kmath-core/src/commonMain/kotlin/kscience/kmath/domains/HyperSquareDomain.kt +++ b/kmath-core/src/commonMain/kotlin/kscience/kmath/domains/HyperSquareDomain.kt @@ -16,6 +16,7 @@ package kscience.kmath.domains import kscience.kmath.linear.Point +import kscience.kmath.structures.Buffer import kscience.kmath.structures.RealBuffer import kscience.kmath.structures.indices @@ -25,20 +26,20 @@ import kscience.kmath.structures.indices * * @author Alexander Nozik */ -public class HyperSquareDomain(private val lower: RealBuffer, private val upper: RealBuffer) : RealDomain { +public class HyperSquareDomain(private val lower: Buffer, private val upper: Buffer) : RealDomain { public override val dimension: Int get() = lower.size public override operator fun contains(point: Point): Boolean = point.indices.all { i -> point[i] in lower[i]..upper[i] } - public override fun getLowerBound(num: Int, point: Point): Double? = lower[num] + public override fun getLowerBound(num: Int, point: Point): Double = lower[num] - public override fun getLowerBound(num: Int): Double? = lower[num] + public override fun getLowerBound(num: Int): Double = lower[num] - public override fun getUpperBound(num: Int, point: Point): Double? = upper[num] + public override fun getUpperBound(num: Int, point: Point): Double = upper[num] - public override fun getUpperBound(num: Int): Double? = upper[num] + public override fun getUpperBound(num: Int): Double = upper[num] public override fun nearestInDomain(point: Point): Point { val res = DoubleArray(point.size) { i -> diff --git a/kmath-core/src/commonMain/kotlin/kscience/kmath/nd/NDStructure.kt b/kmath-core/src/commonMain/kotlin/kscience/kmath/nd/NDStructure.kt index 4aa1c7d52..c3de02925 100644 --- a/kmath-core/src/commonMain/kotlin/kscience/kmath/nd/NDStructure.kt +++ b/kmath-core/src/commonMain/kotlin/kscience/kmath/nd/NDStructure.kt @@ -78,8 +78,7 @@ public interface NDStructure { strides: Strides, bufferFactory: BufferFactory = Buffer.Companion::boxing, initializer: (IntArray) -> T, - ): NDBuffer = - NDBuffer(strides, bufferFactory(strides.linearSize) { i -> initializer(strides.index(i)) }) + ): NDBuffer = NDBuffer(strides, bufferFactory(strides.linearSize) { i -> initializer(strides.index(i)) }) /** * Inline create NDStructure with non-boxing buffer implementation if it is possible @@ -87,15 +86,13 @@ public interface NDStructure { public inline fun auto( strides: Strides, crossinline initializer: (IntArray) -> T, - ): NDBuffer = - NDBuffer(strides, Buffer.auto(strides.linearSize) { i -> initializer(strides.index(i)) }) + ): NDBuffer = NDBuffer(strides, Buffer.auto(strides.linearSize) { i -> initializer(strides.index(i)) }) public inline fun auto( type: KClass, strides: Strides, crossinline initializer: (IntArray) -> T, - ): NDBuffer = - NDBuffer(strides, Buffer.auto(type, strides.linearSize) { i -> initializer(strides.index(i)) }) + ): NDBuffer = NDBuffer(strides, Buffer.auto(type, strides.linearSize) { i -> initializer(strides.index(i)) }) public fun build( shape: IntArray, @@ -106,8 +103,7 @@ public interface NDStructure { public inline fun auto( shape: IntArray, crossinline initializer: (IntArray) -> T, - ): NDBuffer = - auto(DefaultStrides(shape), initializer) + ): NDBuffer = auto(DefaultStrides(shape), initializer) @JvmName("autoVarArg") public inline fun auto( @@ -120,8 +116,7 @@ public interface NDStructure { type: KClass, vararg shape: Int, crossinline initializer: (IntArray) -> T, - ): NDBuffer = - auto(type, DefaultStrides(shape), initializer) + ): NDBuffer = auto(type, DefaultStrides(shape), initializer) } } diff --git a/kmath-core/src/commonMain/kotlin/kscience/kmath/structures/Buffer.kt b/kmath-core/src/commonMain/kotlin/kscience/kmath/structures/Buffer.kt index be48055c7..d214eeba1 100644 --- a/kmath-core/src/commonMain/kotlin/kscience/kmath/structures/Buffer.kt +++ b/kmath-core/src/commonMain/kotlin/kscience/kmath/structures/Buffer.kt @@ -21,7 +21,7 @@ public typealias MutableBufferFactory = (Int, (Int) -> T) -> MutableBuffer * * @param T the type of elements contained in the buffer. */ -public interface Buffer { +public interface Buffer { /** * The size of this buffer. */ diff --git a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Counters.kt b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Counters.kt index a7a42873f..bdc03cc1d 100644 --- a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Counters.kt +++ b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Counters.kt @@ -2,16 +2,18 @@ package kscience.kmath.histogram import kotlinx.atomicfu.atomic import kotlinx.atomicfu.getAndUpdate +import kscience.kmath.operations.RealField import kscience.kmath.operations.Space -/* +/** * Common representation for atomic counters - * TODO replace with atomics */ - public interface Counter { public fun add(delta: T) public val value: T + public companion object{ + public fun real(): ObjectCounter = ObjectCounter(RealField) + } } public class IntCounter : Counter { diff --git a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Histogram.kt b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Histogram.kt index 2bc40af85..91032fc31 100644 --- a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Histogram.kt +++ b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/Histogram.kt @@ -13,8 +13,6 @@ public interface Bin : Domain { * The value of this bin. */ public val value: Number - - public val center: Point } public interface Histogram> { @@ -28,29 +26,30 @@ public interface Histogram> { */ public val dimension: Int - public val bins: Collection + public val bins: Iterable } -public interface HistogramBuilder> : Histogram { +public fun interface HistogramBuilder { /** * Increment appropriate bin */ - public fun putWithWeight(point: Point, weight: Double) + public fun putValue(point: Point, value: Number) - public fun put(point: Point): Unit = putWithWeight(point, 1.0) } -public fun HistogramBuilder.put(vararg point: T): Unit = put(ArrayBuffer(point)) +public fun > HistogramBuilder.put(point: Point): Unit = putValue(point, 1.0) -public fun HistogramBuilder.put(vararg point: Number): Unit = +public fun HistogramBuilder.put(vararg point: T): Unit = put(ArrayBuffer(point)) + +public fun HistogramBuilder.put(vararg point: Number): Unit = put(RealBuffer(point.map { it.toDouble() }.toDoubleArray())) -public fun HistogramBuilder.put(vararg point: Double): Unit = put(RealBuffer(point)) -public fun HistogramBuilder.fill(sequence: Iterable>): Unit = sequence.forEach { put(it) } +public fun HistogramBuilder.put(vararg point: Double): Unit = put(RealBuffer(point)) +public fun HistogramBuilder.fill(sequence: Iterable>): Unit = sequence.forEach { put(it) } /** * Pass a sequence builder into histogram */ -public fun HistogramBuilder.fill(block: suspend SequenceScope>.() -> Unit): Unit = +public fun HistogramBuilder.fill(block: suspend SequenceScope>.() -> Unit): Unit = fill(sequence(block).asIterable()) diff --git a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/IndexedHistogramSpace.kt b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/IndexedHistogramSpace.kt new file mode 100644 index 000000000..53761452f --- /dev/null +++ b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/IndexedHistogramSpace.kt @@ -0,0 +1,76 @@ +package kscience.kmath.histogram + +import kscience.kmath.domains.Domain +import kscience.kmath.linear.Point +import kscience.kmath.misc.UnstableKMathAPI +import kscience.kmath.nd.NDSpace +import kscience.kmath.nd.NDStructure +import kscience.kmath.nd.Strides +import kscience.kmath.operations.Space +import kscience.kmath.operations.SpaceElement +import kscience.kmath.operations.invoke + +/** + * A simple histogram bin based on domain + */ +public data class DomainBin>( + public val domain: Domain, + public override val value: Number, +) : Bin, Domain by domain + +@OptIn(UnstableKMathAPI::class) +public class IndexedHistogram, V : Any>( + override val context: IndexedHistogramSpace, + public val values: NDStructure, +) : Histogram>, SpaceElement, IndexedHistogramSpace> { + + override fun get(point: Point): Bin? { + val index = context.getIndex(point) ?: return null + return context.produceBin(index, values[index]) + } + + override val dimension: Int get() = context.strides.shape.size + + override val bins: Iterable> + get() = context.strides.indices().map { + context.produceBin(it, values[it]) + }.asIterable() + +} + +/** + * A space for producing histograms with values in a NDStructure + */ +public interface IndexedHistogramSpace, V : Any> : Space> { + //public val valueSpace: Space + public val strides: Strides + public val histogramValueSpace: NDSpace //= NDAlgebra.space(valueSpace, Buffer.Companion::boxing, *shape), + + /** + * Resolve index of the bin including given [point] + */ + public fun getIndex(point: Point): IntArray? + + /** + * Get a bin domain represented by given index + */ + public fun getDomain(index: IntArray): Domain? + + public fun produceBin(index: IntArray, value: V): Bin + + public fun produce(builder: HistogramBuilder.() -> Unit): IndexedHistogram + + override fun add(a: IndexedHistogram, b: IndexedHistogram): IndexedHistogram { + require(a.context == this) { "Can't operate on a histogram produced by external space" } + require(b.context == this) { "Can't operate on a histogram produced by external space" } + return IndexedHistogram(this, histogramValueSpace.invoke { a.values + b.values }) + } + + override fun multiply(a: IndexedHistogram, k: Number): IndexedHistogram { + require(a.context == this) { "Can't operate on a histogram produced by external space" } + return IndexedHistogram(this, histogramValueSpace.invoke { a.values * k }) + } + + override val zero: IndexedHistogram get() = produce { } +} + diff --git a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogram.kt b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogram.kt deleted file mode 100644 index c8f9958e0..000000000 --- a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogram.kt +++ /dev/null @@ -1,166 +0,0 @@ -package kscience.kmath.histogram - -import kscience.kmath.linear.Point -import kscience.kmath.nd.DefaultStrides -import kscience.kmath.nd.NDStructure -import kscience.kmath.operations.SpaceOperations -import kscience.kmath.operations.invoke -import kscience.kmath.structures.* -import kotlin.math.floor - -public data class MultivariateBinDefinition>( - public val space: SpaceOperations>, - public val center: Point, - public val sizes: Point, -) { - public fun contains(vector: Point): Boolean { - require(vector.size == center.size) { "Dimension mismatch for input vector. Expected ${center.size}, but found ${vector.size}" } - val upper = space { center + sizes / 2.0 } - val lower = space { center - sizes / 2.0 } - return vector.asSequence().mapIndexed { i, value -> value in lower[i]..upper[i] }.all { it } - } -} - - -public class MultivariateBin>( - public val definition: MultivariateBinDefinition, - public val count: Long, - public override val value: Double, -) : Bin { - public override val dimension: Int - get() = definition.center.size - - public override val center: Point - get() = definition.center - - public override operator fun contains(point: Point): Boolean = definition.contains(point) -} - -/** - * Uniform multivariate histogram with fixed borders. Based on NDStructure implementation with complexity of m for bin search, where m is the number of dimensions. - */ -public class RealHistogram( - private val lower: Buffer, - private val upper: Buffer, - private val binNums: IntArray = IntArray(lower.size) { 20 }, -) : HistogramBuilder> { - private val strides = DefaultStrides(IntArray(binNums.size) { binNums[it] + 2 }) - private val counts: NDStructure = NDStructure.auto(strides) { LongCounter() } - private val values: NDStructure = NDStructure.auto(strides) { DoubleCounter() } - public override val dimension: Int get() = lower.size - private val binSize = RealBuffer(dimension) { (upper[it] - lower[it]) / binNums[it] } - - init { - // argument checks - require(lower.size == upper.size) { "Dimension mismatch in histogram lower and upper limits." } - require(lower.size == binNums.size) { "Dimension mismatch in bin count." } - require(!(0 until dimension).any { upper[it] - lower[it] < 0 }) { "Range for one of axis is not strictly positive" } - } - - /** - * Get internal [NDStructure] bin index for given axis - */ - private fun getIndex(axis: Int, value: Double): Int = when { - value >= upper[axis] -> binNums[axis] + 1 // overflow - value < lower[axis] -> 0 // underflow - else -> floor((value - lower[axis]) / binSize[axis]).toInt() + 1 - } - - private fun getIndex(point: Buffer): IntArray = IntArray(dimension) { getIndex(it, point[it]) } - - private fun getCount(index: IntArray): Long = counts[index].sum() - - public fun getCount(point: Buffer): Long = getCount(getIndex(point)) - - private fun getValue(index: IntArray): Double = values[index].sum() - - public fun getValue(point: Buffer): Double = getValue(getIndex(point)) - - private fun getBinDefinition(index: IntArray): MultivariateBinDefinition { - val center = index.mapIndexed { axis, i -> - when (i) { - 0 -> Double.NEGATIVE_INFINITY - strides.shape[axis] - 1 -> Double.POSITIVE_INFINITY - else -> lower[axis] + (i.toDouble() - 0.5) * binSize[axis] - } - }.asBuffer() - - return MultivariateBinDefinition(RealBufferFieldOperations, center, binSize) - } - - public fun getBinDefinition(point: Buffer): MultivariateBinDefinition = - getBinDefinition(getIndex(point)) - - public override operator fun get(point: Buffer): MultivariateBin? { - val index = getIndex(point) - return MultivariateBin(getBinDefinition(index), getCount(index), getValue(index)) - } - -// fun put(point: Point){ -// val index = getIndex(point) -// values[index].increment() -// } - - public override fun putWithWeight(point: Buffer, weight: Double) { - val index = getIndex(point) - counts[index].increment() - values[index].add(weight) - } - - override val bins: Collection> - get() = strides.indices().map { index -> - MultivariateBin(getBinDefinition(index), counts[index].sum(), values[index].sum()) - }.toList() - - /** - * NDStructure containing number of events in bins without weights - */ - public fun counts(): NDStructure = NDStructure.auto(counts.shape) { counts[it].sum() } - - /** - * NDStructure containing values of bins including weights - */ - public fun values(): NDStructure = NDStructure.auto(values.shape) { values[it].sum() } - - public companion object { - /** - * Use it like - * ``` - *FastHistogram.fromRanges( - * (-1.0..1.0), - * (-1.0..1.0) - *) - *``` - */ - public fun fromRanges(vararg ranges: ClosedFloatingPointRange): RealHistogram = RealHistogram( - ranges.map(ClosedFloatingPointRange::start).asBuffer(), - ranges.map(ClosedFloatingPointRange::endInclusive).asBuffer() - ) - - /** - * Use it like - * ``` - *FastHistogram.fromRanges( - * (-1.0..1.0) to 50, - * (-1.0..1.0) to 32 - *) - *``` - */ - public fun fromRanges(vararg ranges: Pair, Int>): RealHistogram = - RealHistogram( - ListBuffer( - ranges - .map(Pair, Int>::first) - .map(ClosedFloatingPointRange::start) - ), - - ListBuffer( - ranges - .map(Pair, Int>::first) - .map(ClosedFloatingPointRange::endInclusive) - ), - - ranges.map(Pair, Int>::second).toIntArray() - ) - } -} diff --git a/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogramSpace.kt b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogramSpace.kt new file mode 100644 index 000000000..ef2d9771b --- /dev/null +++ b/kmath-histograms/src/commonMain/kotlin/kscience/kmath/histogram/RealHistogramSpace.kt @@ -0,0 +1,121 @@ +package kscience.kmath.histogram + +import kscience.kmath.domains.Domain +import kscience.kmath.domains.HyperSquareDomain +import kscience.kmath.nd.* +import kscience.kmath.structures.* +import kotlin.math.floor + +public class RealHistogramSpace( + private val lower: Buffer, + private val upper: Buffer, + private val binNums: IntArray = IntArray(lower.size) { 20 }, +) : IndexedHistogramSpace { + + init { + // argument checks + require(lower.size == upper.size) { "Dimension mismatch in histogram lower and upper limits." } + require(lower.size == binNums.size) { "Dimension mismatch in bin count." } + require(!lower.indices.any { upper[it] - lower[it] < 0 }) { "Range for one of axis is not strictly positive" } + } + + public val dimension: Int get() = lower.size + + private val shape = IntArray(binNums.size) { binNums[it] + 2 } + override val histogramValueSpace: RealNDField = NDAlgebra.real(*shape) + + override val strides: Strides get() = histogramValueSpace.strides + private val binSize = RealBuffer(dimension) { (upper[it] - lower[it]) / binNums[it] } + + /** + * Get internal [NDStructure] bin index for given axis + */ + private fun getIndex(axis: Int, value: Double): Int = when { + value >= upper[axis] -> binNums[axis] + 1 // overflow + value < lower[axis] -> 0 // underflow + else -> floor((value - lower[axis]) / binSize[axis]).toInt() + } + + override fun getIndex(point: Buffer): IntArray = IntArray(dimension) { + getIndex(it, point[it]) + } + + override fun getDomain(index: IntArray): Domain { + val lowerBoundary = index.mapIndexed { axis, i -> + when (i) { + 0 -> Double.NEGATIVE_INFINITY + strides.shape[axis] - 1 -> upper[axis] + else -> lower[axis] + (i.toDouble()) * binSize[axis] + } + }.asBuffer() + + val upperBoundary = index.mapIndexed { axis, i -> + when (i) { + 0 -> lower[axis] + strides.shape[axis] - 1 -> Double.POSITIVE_INFINITY + else -> lower[axis] + (i.toDouble() + 1) * binSize[axis] + } + }.asBuffer() + + return HyperSquareDomain(lowerBoundary, upperBoundary) + } + + + override fun produceBin(index: IntArray, value: Double): Bin { + val domain = getDomain(index) + return DomainBin(domain, value) + } + + override fun produce(builder: HistogramBuilder.() -> Unit): IndexedHistogram { + val ndCounter = NDStructure.auto(strides) { Counter.real() } + val hBuilder = HistogramBuilder { point, value -> + val index = getIndex(point) + ndCounter[index].add(1.0) + } + hBuilder.apply(builder) + val values: NDBuffer = ndCounter.mapToBuffer { it.value } + return IndexedHistogram(this, values) + } + + public companion object{ + /** + * Use it like + * ``` + *FastHistogram.fromRanges( + * (-1.0..1.0), + * (-1.0..1.0) + *) + *``` + */ + public fun fromRanges(vararg ranges: ClosedFloatingPointRange): RealHistogramSpace = RealHistogramSpace( + ranges.map(ClosedFloatingPointRange::start).asBuffer(), + ranges.map(ClosedFloatingPointRange::endInclusive).asBuffer() + ) + + /** + * Use it like + * ``` + *FastHistogram.fromRanges( + * (-1.0..1.0) to 50, + * (-1.0..1.0) to 32 + *) + *``` + */ + public fun fromRanges(vararg ranges: Pair, Int>): RealHistogramSpace = + RealHistogramSpace( + ListBuffer( + ranges + .map(Pair, Int>::first) + .map(ClosedFloatingPointRange::start) + ), + + ListBuffer( + ranges + .map(Pair, Int>::first) + .map(ClosedFloatingPointRange::endInclusive) + ), + + ranges.map(Pair, Int>::second).toIntArray() + ) + } +} \ No newline at end of file diff --git a/kmath-histograms/src/commonTest/kotlin/scietifik/kmath/histogram/MultivariateHistogramTest.kt b/kmath-histograms/src/commonTest/kotlin/scietifik/kmath/histogram/MultivariateHistogramTest.kt index ef2c1445a..860b047ae 100644 --- a/kmath-histograms/src/commonTest/kotlin/scietifik/kmath/histogram/MultivariateHistogramTest.kt +++ b/kmath-histograms/src/commonTest/kotlin/scietifik/kmath/histogram/MultivariateHistogramTest.kt @@ -1,6 +1,6 @@ package scietifik.kmath.histogram -import kscience.kmath.histogram.RealHistogram +import kscience.kmath.histogram.RealHistogramSpace import kscience.kmath.histogram.fill import kscience.kmath.histogram.put import kscience.kmath.real.RealVector @@ -11,11 +11,13 @@ import kotlin.test.* internal class MultivariateHistogramTest { @Test fun testSinglePutHistogram() { - val histogram = RealHistogram.fromRanges( + val hSpace = RealHistogramSpace.fromRanges( (-1.0..1.0), (-1.0..1.0) ) - histogram.put(0.55, 0.55) + val histogram = hSpace.produce { + put(0.55, 0.55) + } val bin = histogram.bins.find { it.value.toInt() > 0 } ?: fail() assertTrue { bin.contains(RealVector(0.55, 0.55)) } assertTrue { bin.contains(RealVector(0.6, 0.5)) } @@ -24,7 +26,7 @@ internal class MultivariateHistogramTest { @Test fun testSequentialPut() { - val histogram = RealHistogram.fromRanges( + val hSpace = RealHistogramSpace.fromRanges( (-1.0..1.0), (-1.0..1.0), (-1.0..1.0) @@ -34,10 +36,11 @@ internal class MultivariateHistogramTest { fun nextDouble() = random.nextDouble(-1.0, 1.0) val n = 10000 - - histogram.fill { - repeat(n) { - yield(RealVector(nextDouble(), nextDouble(), nextDouble())) + val histogram = hSpace.produce { + fill { + repeat(n) { + yield(RealVector(nextDouble(), nextDouble(), nextDouble())) + } } } assertEquals(n, histogram.bins.sumBy { it.value.toInt() }) diff --git a/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogram.kt b/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogram.kt index 1fb5172ce..7d8f874a2 100644 --- a/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogram.kt +++ b/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogram.kt @@ -30,7 +30,7 @@ public interface UnivariateBin : Bin { */ public val standardDeviation: Double - public override val center: Point get() = doubleArrayOf(position).asBuffer() + public val center: Point get() = doubleArrayOf(position).asBuffer() public override val dimension: Int get() = 1 @@ -44,7 +44,7 @@ public operator fun UnivariateBin.contains(value: Double): Boolean = public interface UnivariateHistogram : Histogram, SpaceElement { public operator fun get(value: Double): UnivariateBin? - public override operator fun get(point: Buffer): UnivariateBin? = get(point[0]) + public override operator fun get(point: Buffer): UnivariateBin? = get(point[0]) public companion object { /** @@ -67,12 +67,14 @@ public interface UnivariateHistogram : Histogram, } } -public interface UnivariateHistogramBuilder { +public interface UnivariateHistogramBuilder: HistogramBuilder { + /** * Thread safe put operation */ public fun put(value: Double, weight: Double = 1.0) - public fun putWithWeight(point: Buffer, weight: Double) + + override fun putValue(point: Buffer, value: Number) /** * Put several items into a single bin diff --git a/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogramSpace.kt b/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogramSpace.kt index b18835b7b..3d1bd20c0 100644 --- a/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogramSpace.kt +++ b/kmath-histograms/src/jvmMain/kotlin/kscience/kmath/histogram/UnivariateHistogramSpace.kt @@ -31,19 +31,19 @@ private class UnivariateBinCounter( override val def: UnivariateHistogramBinDefinition, ) : UnivariateBin { val counter: LongCounter = LongCounter() - val valueCounter: DoubleCounter = DoubleCounter() + val valueCounter: ObjectCounter = Counter.real() /** * The precise number of events ignoring weighting */ - val count: Long get() = counter.sum() + val count: Long get() = counter.value override val standardDeviation: Double get() = sqrt(count.toDouble()) / count * value /** * The value of histogram including weighting */ - override val value: Double get() = valueCounter.sum() + override val value: Double get() = valueCounter.value public fun increment(count: Long, value: Double) { counter.add(count) @@ -83,8 +83,8 @@ public class UnivariateHistogramSpace( } } - override fun putWithWeight(point: Buffer, weight: Double) { - put(point[0], weight) + override fun putValue(point: Buffer, value: Number) { + put(point[0], value.toDouble()) } /**