Added Levenberg-Marquardt algorithm and svd Golub-Kahan #513

Merged
margarita0303 merged 35 commits from dev into dev 2023-06-19 16:11:59 +03:00
260 changed files with 2194 additions and 1500 deletions
Showing only changes of commit a9627071ff - Show all commits

View File

@ -15,7 +15,7 @@ jobs:
runs-on: ${{matrix.os}} runs-on: ${{matrix.os}}
steps: steps:
- uses: actions/checkout@v3.0.0 - uses: actions/checkout@v3.0.0
- uses: actions/setup-java@v3.0.0 - uses: actions/setup-java@v3.10.0
with: with:
java-version: 11 java-version: 11
distribution: liberica distribution: liberica
@ -26,26 +26,25 @@ jobs:
key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle.kts') }} key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle.kts') }}
restore-keys: | restore-keys: |
${{ runner.os }}-gradle- ${{ runner.os }}-gradle-
- uses: gradle/wrapper-validation-action@v1.0.4
- name: Publish Windows Artifacts - name: Publish Windows Artifacts
if: matrix.os == 'windows-latest' if: matrix.os == 'windows-latest'
uses: gradle/gradle-build-action@v2.1.5 uses: gradle/gradle-build-action@v2.4.0
with: with:
arguments: | arguments: |
releaseAll publishAllPublicationsToSpaceRepository
-Ppublishing.enabled=true -Ppublishing.targets=all
-Ppublishing.sonatype=false
-Ppublishing.space.user=${{ secrets.SPACE_APP_ID }} -Ppublishing.space.user=${{ secrets.SPACE_APP_ID }}
-Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }} -Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }}
- name: Publish Mac Artifacts - name: Publish Mac Artifacts
if: matrix.os == 'macOS-latest' if: matrix.os == 'macOS-latest'
uses: gradle/gradle-build-action@v2.1.5 uses: gradle/gradle-build-action@v2.4.0
with: with:
arguments: | arguments: |
releaseMacosX64 publishMacosX64PublicationToSpaceRepository
releaseIosArm64 publishMacosArm64PublicationToSpaceRepository
releaseIosX64 publishIosX64PublicationToSpaceRepository
-Ppublishing.enabled=true publishIosArm64PublicationToSpaceRepository
-Ppublishing.sonatype=false publishIosSimulatorArm64PublicationToSpaceRepository
-Ppublishing.targets=all
-Ppublishing.space.user=${{ secrets.SPACE_APP_ID }} -Ppublishing.space.user=${{ secrets.SPACE_APP_ID }}
-Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }} -Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }}

6
.gitignore vendored
View File

@ -3,10 +3,9 @@ build/
out/ out/
.idea/ .idea/
.vscode/ .vscode/
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar !gradle-wrapper.jar
@ -19,4 +18,5 @@ out/
!/.idea/copyright/ !/.idea/copyright/
!/.idea/scopes/ !/.idea/scopes/
/kotlin-js-store/yarn.lock /gradle/yarn.lock

View File

@ -1,32 +1,47 @@
# KMath # KMath
## [Unreleased] ## Unreleased
### Added ### Added
- Type-aliases for numbers like `Float64`
- 2D optimal trajectory computation in a separate module `kmath-trajectory`
- Autodiff for generic algebra elements in core!
- Algebra now has an obligatory `bufferFactory` (#477).
### Changed ### Changed
- Tensor operations switched to prefix notation
- Row-wise and column-wise ND shapes in the core
- Shape is read-only
- Major refactor of tensors (only minor API changes)
- Kotlin 1.7.20
- `LazyStructure` `deffered` -> `async` to comply with coroutines code style
- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added to `DoubleTensorAlgebra`.
- Multik went MPP
### Deprecated ### Deprecated
### Removed ### Removed
- Polynomials moved to https://github.com/SciProgCentre/kmath-polynomial
### Fixed ### Fixed
### Security ### Security
## [0.3.0] ## 0.3.1-dev-RC - 2023-04-09
### Added
- Wasm support for `memory`, `core`, `complex` and `functions` modules.
- Generic builders for `BufferND` and `MutableBufferND`
- `NamedMatrix` - matrix with symbol-based indexing
- `Expression` with default arguments
- Type-aliases for numbers like `Float64`
- Autodiff for generic algebra elements in core!
- Algebra now has an obligatory `bufferFactory` (#477).
### Changed
- Geometry uses type-safe angles
- Tensor operations switched to prefix notation
- Row-wise and column-wise ND shapes in the core
- Shape is read-only
- Major refactor of tensors (only minor API changes)
- Kotlin 1.8.20
- `LazyStructure` `deffered` -> `async` to comply with coroutines code style
- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added to `DoubleTensorAlgebra`.
- Multik went MPP
### Removed
- Trajectory moved to https://github.com/SciProgCentre/maps-kt
- Polynomials moved to https://github.com/SciProgCentre/kmath-polynomial
## 0.3.0
### Added ### Added
- `ScaleOperations` interface - `ScaleOperations` interface
- `Field` extends `ScaleOperations` - `Field` extends `ScaleOperations`
@ -51,8 +66,8 @@
- `contentEquals` with tolerance: #364 - `contentEquals` with tolerance: #364
- Compilation to TeX for MST: #254 - Compilation to TeX for MST: #254
### Changed ### Changed
- Annotations moved to `space.kscience.kmath`
- Exponential operations merged with hyperbolic functions - Exponential operations merged with hyperbolic functions
- Space is replaced by Group. Space is reserved for vector spaces. - Space is replaced by Group. Space is reserved for vector spaces.
- VectorSpace is now a vector space - VectorSpace is now a vector space
@ -84,11 +99,9 @@
- Rework of histograms. - Rework of histograms.
- `UnivariateFunction` -> `Function1D`, `MultivariateFunction` -> `FunctionND` - `UnivariateFunction` -> `Function1D`, `MultivariateFunction` -> `FunctionND`
### Deprecated ### Deprecated
- Specialized `DoubleBufferAlgebra` - Specialized `DoubleBufferAlgebra`
### Removed ### Removed
- Nearest in Domain. To be implemented in geometry package. - Nearest in Domain. To be implemented in geometry package.
- Number multiplication and division in main Algebra chain - Number multiplication and division in main Algebra chain
@ -99,15 +112,12 @@
- Second generic from DifferentiableExpression - Second generic from DifferentiableExpression
- Algebra elements are completely removed. Use algebra contexts instead. - Algebra elements are completely removed. Use algebra contexts instead.
### Fixed ### Fixed
- Ring inherits RingOperations, not GroupOperations - Ring inherits RingOperations, not GroupOperations
- Univariate histogram filling - Univariate histogram filling
## 0.2.0
### Security
## [0.2.0]
### Added ### Added
- `fun` annotation for SAM interfaces in library - `fun` annotation for SAM interfaces in library
- Explicit `public` visibility for all public APIs - Explicit `public` visibility for all public APIs
@ -127,7 +137,6 @@
- New `MatrixFeature` interfaces for matrix decompositions - New `MatrixFeature` interfaces for matrix decompositions
- Basic Quaternion vector support in `kmath-complex`. - Basic Quaternion vector support in `kmath-complex`.
### Changed ### Changed
- Package changed from `scientifik` to `space.kscience` - Package changed from `scientifik` to `space.kscience`
- Gradle version: 6.6 -> 6.8.2 - Gradle version: 6.6 -> 6.8.2
@ -152,7 +161,6 @@
- `symbol` method in `Algebra` renamed to `bindSymbol` to avoid ambiguity - `symbol` method in `Algebra` renamed to `bindSymbol` to avoid ambiguity
- Add `out` projection to `Buffer` generic - Add `out` projection to `Buffer` generic
### Removed ### Removed
- `kmath-koma` module because it doesn't support Kotlin 1.4. - `kmath-koma` module because it doesn't support Kotlin 1.4.
- Support of `legacy` JS backend (we will support only IR) - Support of `legacy` JS backend (we will support only IR)
@ -161,11 +169,11 @@
- `Real` class - `Real` class
- StructureND identity and equals - StructureND identity and equals
### Fixed ### Fixed
- `symbol` method in `MstExtendedField` (https://github.com/mipt-npm/kmath/pull/140) - `symbol` method in `MstExtendedField` (https://github.com/mipt-npm/kmath/pull/140)
## [0.1.4] ## 0.1.4
### Added ### Added
- Functional Expressions API - Functional Expressions API
- Mathematical Syntax Tree, its interpreter and API - Mathematical Syntax Tree, its interpreter and API
@ -183,7 +191,6 @@
- Full hyperbolic functions support and default implementations within `ExtendedField` - Full hyperbolic functions support and default implementations within `ExtendedField`
- Norm support for `Complex` - Norm support for `Complex`
### Changed ### Changed
- `readAsMemory` now has `throws IOException` in JVM signature. - `readAsMemory` now has `throws IOException` in JVM signature.
- Several functions taking functional types were made `inline`. - Several functions taking functional types were made `inline`.
@ -195,10 +202,9 @@
- Gradle version: 6.3 -> 6.6 - Gradle version: 6.3 -> 6.6
- Moved probability distributions to commons-rng and to `kmath-prob` - Moved probability distributions to commons-rng and to `kmath-prob`
### Fixed ### Fixed
- Missing copy method in Memory implementation on JS (https://github.com/mipt-npm/kmath/pull/106) - Missing copy method in Memory implementation on JS (https://github.com/mipt-npm/kmath/pull/106)
- D3.dim value in `kmath-dimensions` - D3.dim value in `kmath-dimensions`
- Multiplication in integer rings in `kmath-core` (https://github.com/mipt-npm/kmath/pull/101) - Multiplication in integer rings in `kmath-core` (https://github.com/mipt-npm/kmath/pull/101)
- Commons RNG compatibility (https://github.com/mipt-npm/kmath/issues/93) - Commons RNG compatibility (https://github.com/mipt-npm/kmath/issues/93)
- Multiplication of BigInt by scalar - Multiplication of BigInt by scalar

View File

@ -214,28 +214,6 @@ One can still use generic algebras though.
> >
> **Maturity**: EXPERIMENTAL > **Maturity**: EXPERIMENTAL
### [kmath-polynomial](kmath-polynomial)
>
>
> **Maturity**: PROTOTYPE
>
> **Features:**
> - [polynomial abstraction](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Abstraction for polynomial spaces.
> - [rational function abstraction](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/RationalFunction.kt) : Abstraction for rational functions spaces.
> - ["list" polynomials](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/ListRationalFunction.kt) : List implementation of univariate polynomials.
> - ["list" rational functions](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/ListPolynomial.kt) : List implementation of univariate rational functions.
> - ["list" polynomials and rational functions constructors](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/listConstructors.kt) : Constructors for list polynomials and rational functions.
> - ["list" polynomials and rational functions utilities](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/listUtil.kt) : Utilities for list polynomials and rational functions.
> - ["numbered" polynomials](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/NumberedRationalFunction.kt) : Numbered implementation of multivariate polynomials.
> - ["numbered" rational functions](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/NumberedPolynomial.kt) : Numbered implementation of multivariate rational functions.
> - ["numbered" polynomials and rational functions constructors](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/numberedConstructors.kt) : Constructors for numbered polynomials and rational functions.
> - ["numbered" polynomials and rational functions utilities](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/numberedUtil.kt) : Utilities for numbered polynomials and rational functions.
> - ["labeled" polynomials](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/LabeledRationalFunction.kt) : Labeled implementation of multivariate polynomials.
> - ["labeled" rational functions](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/LabeledPolynomial.kt) : Labeled implementation of multivariate rational functions.
> - ["labeled" polynomials and rational functions constructors](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/labeledConstructors.kt) : Constructors for labeled polynomials and rational functions.
> - ["labeled" polynomials and rational functions utilities](kmath-polynomial/src/commonMain/kotlin/space/kscience/kmath/functions/labeledUtil.kt) : Utilities for labeled polynomials and rational functions.
### [kmath-stat](kmath-stat) ### [kmath-stat](kmath-stat)
> >
> >
@ -262,11 +240,6 @@ One can still use generic algebras though.
> - [linear algebra operations](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc. > - [linear algebra operations](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc.
### [kmath-trajectory](kmath-trajectory)
> Path and trajectory optimization
>
> **Maturity**: PROTOTYPE
### [kmath-viktor](kmath-viktor) ### [kmath-viktor](kmath-viktor)
> >
> >
@ -325,4 +298,4 @@ Gradle `6.0+` is required for multiplatform artifacts.
The project requires a lot of additional work. The most important thing we need is a feedback about what features are The project requires a lot of additional work. The most important thing we need is a feedback about what features are
required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues
marked with marked with
[waiting for a hero](https://github.com/SciProgCentre/kmath/labels/waiting%20for%20a%20hero) label. [waiting for a hero](https://github.com/mipt-npm/kmath/labels/waiting%20for%20a%20hero) label.

View File

@ -5,7 +5,7 @@ import space.kscience.kmath.benchmarks.addBenchmarkProperties
plugins { plugins {
kotlin("multiplatform") kotlin("multiplatform")
kotlin("plugin.allopen") alias(spclibs.plugins.kotlin.plugin.allopen)
id("org.jetbrains.kotlinx.benchmark") id("org.jetbrains.kotlinx.benchmark")
} }
@ -44,7 +44,7 @@ kotlin {
implementation(project(":kmath-tensors")) implementation(project(":kmath-tensors"))
implementation(project(":kmath-multik")) implementation(project(":kmath-multik"))
implementation("org.jetbrains.kotlinx:multik-default:$multikVersion") implementation("org.jetbrains.kotlinx:multik-default:$multikVersion")
implementation(npmlibs.kotlinx.benchmark.runtime) implementation(spclibs.kotlinx.benchmark.runtime)
} }
} }
@ -142,12 +142,10 @@ benchmark {
commonConfiguration() commonConfiguration()
include("ViktorLogBenchmark") include("ViktorLogBenchmark")
} }
}
// Fix kotlinx-benchmarks bug configurations.register("integration") {
afterEvaluate { commonConfiguration()
val jvmBenchmarkJar by tasks.getting(org.gradle.jvm.tasks.Jar::class) { include("IntegrationBenchmark")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
} }
} }

View File

@ -9,8 +9,8 @@ import kotlinx.benchmark.Benchmark
import kotlinx.benchmark.Blackhole import kotlinx.benchmark.Blackhole
import kotlinx.benchmark.Scope import kotlinx.benchmark.Scope
import kotlinx.benchmark.State import kotlinx.benchmark.State
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.bindSymbol import space.kscience.kmath.operations.bindSymbol
import space.kscience.kmath.operations.invoke import space.kscience.kmath.operations.invoke
@ -94,6 +94,7 @@ class ExpressionsInterpretersBenchmark {
} }
private val mst = node.toExpression(DoubleField) private val mst = node.toExpression(DoubleField)
@OptIn(UnstableKMathAPI::class)
private val wasm = node.wasmCompileToExpression(DoubleField) private val wasm = node.wasmCompileToExpression(DoubleField)
private val estree = node.estreeCompileToExpression(DoubleField) private val estree = node.estreeCompileToExpression(DoubleField)

View File

@ -10,7 +10,7 @@ import kotlinx.benchmark.Blackhole
import org.openjdk.jmh.annotations.Benchmark import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.State
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.BigIntField import space.kscience.kmath.operations.BigIntField
import space.kscience.kmath.operations.JBigIntegerField import space.kscience.kmath.operations.JBigIntegerField
import space.kscience.kmath.operations.invoke import space.kscience.kmath.operations.invoke

View File

@ -0,0 +1,40 @@
/*
* Copyright 2018-2023 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.benchmarks
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.infra.Blackhole
import space.kscience.kmath.complex.Complex
import space.kscience.kmath.complex.algebra
import space.kscience.kmath.integration.gaussIntegrator
import space.kscience.kmath.integration.integrate
import space.kscience.kmath.integration.value
import space.kscience.kmath.operations.algebra
@State(Scope.Benchmark)
internal class IntegrationBenchmark {
@Benchmark
fun doubleIntegration(blackhole: Blackhole) {
val res = Double.algebra.gaussIntegrator.integrate(0.0..1.0, intervals = 1000) { x: Double ->
//sin(1 / x)
1/x
}.value
blackhole.consume(res)
}
@Benchmark
fun complexIntegration(blackhole: Blackhole) = with(Complex.algebra) {
val res = gaussIntegrator.integrate(0.0..1.0, intervals = 1000) { x: Double ->
// sin(1 / x) + i * cos(1 / x)
1/x - i/x
}.value
blackhole.consume(res)
}
}

View File

@ -13,7 +13,7 @@ import org.jetbrains.kotlinx.multik.api.Multik
import org.jetbrains.kotlinx.multik.api.ones import org.jetbrains.kotlinx.multik.api.ones
import org.jetbrains.kotlinx.multik.ndarray.data.DN import org.jetbrains.kotlinx.multik.ndarray.data.DN
import org.jetbrains.kotlinx.multik.ndarray.data.DataType import org.jetbrains.kotlinx.multik.ndarray.data.DataType
import space.kscience.kmath.misc.UnsafeKMathAPI import space.kscience.kmath.UnsafeKMathAPI
import space.kscience.kmath.nd.* import space.kscience.kmath.nd.*
import space.kscience.kmath.nd4j.nd4j import space.kscience.kmath.nd4j.nd4j
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField

View File

@ -15,7 +15,7 @@ allprojects {
} }
group = "space.kscience" group = "space.kscience"
version = "0.3.1-dev-7" version = "0.3.1-dev-RC"
} }
subprojects { subprojects {
@ -55,18 +55,6 @@ subprojects {
} }
} }
} }
plugins.withId("org.jetbrains.kotlin.multiplatform") {
configure<org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension> {
sourceSets {
val commonTest by getting {
dependencies {
implementation(projects.testUtils)
}
}
}
}
}
} }
readme.readmeTemplate = file("docs/templates/README-TEMPLATE.md") readme.readmeTemplate = file("docs/templates/README-TEMPLATE.md")

View File

@ -1,7 +1,6 @@
plugins { plugins {
`kotlin-dsl` `kotlin-dsl`
`version-catalog` `version-catalog`
kotlin("plugin.serialization") version "1.6.21"
} }
java.targetCompatibility = JavaVersion.VERSION_11 java.targetCompatibility = JavaVersion.VERSION_11
@ -13,18 +12,18 @@ repositories {
gradlePluginPortal() gradlePluginPortal()
} }
val toolsVersion = npmlibs.versions.tools.get() val toolsVersion = spclibs.versions.tools.get()
val kotlinVersion = npmlibs.versions.kotlin.asProvider().get() val kotlinVersion = spclibs.versions.kotlin.asProvider().get()
val benchmarksVersion = npmlibs.versions.kotlinx.benchmark.get() val benchmarksVersion = spclibs.versions.kotlinx.benchmark.get()
dependencies { dependencies {
api("space.kscience:gradle-tools:$toolsVersion") api("space.kscience:gradle-tools:$toolsVersion")
api(npmlibs.atomicfu.gradle)
//plugins form benchmarks //plugins form benchmarks
api("org.jetbrains.kotlinx:kotlinx-benchmark-plugin:$benchmarksVersion") api("org.jetbrains.kotlinx:kotlinx-benchmark-plugin:0.4.7")
api("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion") //api("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
//to be used inside build-script only //to be used inside build-script only
implementation(npmlibs.kotlinx.serialization.json) //implementation(spclibs.kotlinx.serialization.json)
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.+")
} }
kotlin.sourceSets.all { kotlin.sourceSets.all {

View File

@ -26,7 +26,7 @@ dependencyResolutionManagement {
} }
versionCatalogs { versionCatalogs {
create("npmlibs") { create("spclibs") {
from("space.kscience:version-catalog:$toolsVersion") from("space.kscience:version-catalog:$toolsVersion")
} }
} }

View File

@ -5,9 +5,6 @@
package space.kscience.kmath.benchmarks package space.kscience.kmath.benchmarks
import kotlinx.serialization.Serializable
@Serializable
data class JmhReport( data class JmhReport(
val jmhVersion: String, val jmhVersion: String,
val benchmark: String, val benchmark: String,
@ -37,7 +34,6 @@ data class JmhReport(
val scoreUnit: String val scoreUnit: String
} }
@Serializable
data class PrimaryMetric( data class PrimaryMetric(
override val score: Double, override val score: Double,
override val scoreError: Double, override val scoreError: Double,
@ -48,7 +44,6 @@ data class JmhReport(
val rawData: List<List<Double>>? = null, val rawData: List<List<Double>>? = null,
) : Metric ) : Metric
@Serializable
data class SecondaryMetric( data class SecondaryMetric(
override val score: Double, override val score: Double,
override val scoreError: Double, override val scoreError: Double,

View File

@ -6,8 +6,8 @@
package space.kscience.kmath.benchmarks package space.kscience.kmath.benchmarks
import kotlinx.benchmark.gradle.BenchmarksExtension import kotlinx.benchmark.gradle.BenchmarksExtension
import kotlinx.serialization.decodeFromString import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import kotlinx.serialization.json.Json import com.fasterxml.jackson.module.kotlin.readValue
import org.gradle.api.Project import org.gradle.api.Project
import space.kscience.gradle.KScienceReadmeExtension import space.kscience.gradle.KScienceReadmeExtension
import java.time.LocalDateTime import java.time.LocalDateTime
@ -45,6 +45,8 @@ private val ISO_DATE_TIME: DateTimeFormatter = DateTimeFormatterBuilder().run {
private fun noun(number: Number, singular: String, plural: String) = if (number.toLong() == 1L) singular else plural private fun noun(number: Number, singular: String, plural: String) = if (number.toLong() == 1L) singular else plural
private val jsonMapper = jacksonObjectMapper()
fun Project.addBenchmarkProperties() { fun Project.addBenchmarkProperties() {
val benchmarksProject = this val benchmarksProject = this
rootProject.subprojects.forEach { p -> rootProject.subprojects.forEach { p ->
@ -60,8 +62,7 @@ fun Project.addBenchmarkProperties() {
if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) { if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) {
"> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**." "> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**."
} else { } else {
val reports = val reports: List<JmhReport> = jsonMapper.readValue<List<JmhReport>>(resDirectory.resolve("jvm.json"))
Json.decodeFromString<List<JmhReport>>(resDirectory.resolve("jvm.json").readText())
buildString { buildString {
appendLine("<details>") appendLine("<details>")

View File

@ -385,7 +385,7 @@ import org.ejml.sparse.csc.factory.LinearSolverFactory_DSCC
import org.ejml.sparse.csc.factory.LinearSolverFactory_FSCC import org.ejml.sparse.csc.factory.LinearSolverFactory_FSCC
import space.kscience.kmath.linear.* import space.kscience.kmath.linear.*
import space.kscience.kmath.linear.Matrix import space.kscience.kmath.linear.Matrix
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.nd.StructureFeature import space.kscience.kmath.nd.StructureFeature
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.FloatField import space.kscience.kmath.operations.FloatField

View File

@ -1,3 +1,5 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
plugins { plugins {
kotlin("jvm") kotlin("jvm")
} }
@ -33,6 +35,8 @@ dependencies {
implementation(project(":kmath-multik")) implementation(project(":kmath-multik"))
implementation("org.jetbrains.kotlinx:multik-default:$multikVersion") implementation("org.jetbrains.kotlinx:multik-default:$multikVersion")
//datetime
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
implementation("org.nd4j:nd4j-native:1.0.0-beta7") implementation("org.nd4j:nd4j-native:1.0.0-beta7")
@ -46,25 +50,24 @@ dependencies {
// } else // } else
implementation("org.nd4j:nd4j-native-platform:1.0.0-beta7") implementation("org.nd4j:nd4j-native-platform:1.0.0-beta7")
// multik implementation
implementation("org.jetbrains.kotlinx:multik-default:0.1.0")
implementation("org.slf4j:slf4j-simple:1.7.32") implementation("org.slf4j:slf4j-simple:1.7.32")
// plotting // plotting
implementation("space.kscience:plotlykt-server:0.5.0") implementation("space.kscience:plotlykt-server:0.5.0")
} }
kotlin.sourceSets.all { kotlin {
with(languageSettings) { jvmToolchain(11)
optIn("kotlin.contracts.ExperimentalContracts") sourceSets.all {
optIn("kotlin.ExperimentalUnsignedTypes") with(languageSettings) {
optIn("space.kscience.kmath.misc.UnstableKMathAPI") optIn("kotlin.contracts.ExperimentalContracts")
optIn("kotlin.ExperimentalUnsignedTypes")
optIn("space.kscience.kmath.misc.UnstableKMathAPI")
}
} }
} }
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> { tasks.withType<KotlinJvmCompile> {
kotlinOptions { kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = freeCompilerArgs + "-Xjvm-default=all" + "-Xopt-in=kotlin.RequiresOptIn" + "-Xlambdas=indy" freeCompilerArgs = freeCompilerArgs + "-Xjvm-default=all" + "-Xopt-in=kotlin.RequiresOptIn" + "-Xlambdas=indy"
} }
} }

View File

@ -0,0 +1,418 @@
{
"cells": [
{
"cell_type": "code",
"source": [
"%use kmath(0.3.1-dev-5)\n",
"%use plotly(0.5.0)\n",
"@file:DependsOn(\"space.kscience:kmath-commons:0.3.1-dev-5\")"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "lQbSB87rNAn9lV6poArVWW",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"//Uncomment to work in Jupyter classic or DataLore\n",
"//Plotly.jupyter.notebook()"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "0UP158hfccGgjQtHz0wAi6",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"# The model\n",
"\n",
"Defining the input data format, the statistic abstraction and the statistic implementation based on a weighted sum of elements."
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"class XYValues(val xValues: DoubleArray, val yValues: DoubleArray) {\n",
" init {\n",
" require(xValues.size == yValues.size)\n",
" }\n",
"}\n",
"\n",
"fun interface XYStatistic {\n",
" operator fun invoke(values: XYValues): Double\n",
"}\n",
"\n",
"class ConvolutionalXYStatistic(val weights: DoubleArray) : XYStatistic {\n",
" override fun invoke(values: XYValues): Double {\n",
" require(weights.size == values.yValues.size)\n",
" val norm = values.yValues.sum()\n",
" return values.yValues.zip(weights) { value, weight -> value * weight }.sum()/norm\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "Zhgz1Ui91PWz0meJiQpHol",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"# Generator\n",
"Generate sample data for parabolas and hyperbolas"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"fun generateParabolas(xValues: DoubleArray, a: Double, b: Double, c: Double): XYValues {\n",
" val yValues = xValues.map { x -> a * x * x + b * x + c }.toDoubleArray()\n",
" return XYValues(xValues, yValues)\n",
"}\n",
"\n",
"fun generateHyperbols(xValues: DoubleArray, gamma: Double, x0: Double, y0: Double): XYValues {\n",
" val yValues = xValues.map { x -> y0 + gamma / (x - x0) }.toDoubleArray()\n",
" return XYValues(xValues, yValues)\n",
"}"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"val xValues = (1.0..10.0).step(1.0).toDoubleArray()\n",
"\n",
"val xy = generateHyperbols(xValues, 1.0, 0.0, 0.0)\n",
"\n",
"Plotly.plot {\n",
" scatter {\n",
" this.x.doubles = xValues\n",
" this.y.doubles = xy.yValues\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "ZE2atNvFzQsCvpAF8KK4ch",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"Create a default statistic with uniform weights"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"val statistic = ConvolutionalXYStatistic(DoubleArray(xValues.size){1.0})\n",
"statistic(xy)"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "EA5HaydTddRKYrtAUwd29h",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"import kotlin.random.Random\n",
"\n",
"val random = Random(1288)\n",
"\n",
"val parabolas = buildList{\n",
" repeat(500){\n",
" add(\n",
" generateParabolas(\n",
" xValues, \n",
" random.nextDouble(), \n",
" random.nextDouble(), \n",
" random.nextDouble()\n",
" )\n",
" )\n",
" }\n",
"}\n",
"\n",
"val hyperbolas: List<XYValues> = buildList{\n",
" repeat(500){\n",
" add(\n",
" generateHyperbols(\n",
" xValues, \n",
" random.nextDouble()*10, \n",
" random.nextDouble(), \n",
" random.nextDouble()\n",
" )\n",
" )\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "t5t6IYmD7Q1ykeo9uijFfQ",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"Plotly.plot { \n",
" scatter { \n",
" x.doubles = xValues\n",
" y.doubles = parabolas[257].yValues\n",
" }\n",
" scatter { \n",
" x.doubles = xValues\n",
" y.doubles = hyperbolas[252].yValues\n",
" }\n",
" }"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "oXB8lmju7YVYjMRXITKnhO",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"Plotly.plot { \n",
" histogram { \n",
" name = \"parabolae\"\n",
" x.numbers = parabolas.map { statistic(it) }\n",
" }\n",
" histogram { \n",
" name = \"hyperbolae\"\n",
" x.numbers = hyperbolas.map { statistic(it) }\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "8EIIecUZrt2NNrOkhxG5P0",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"val lossFunction: (XYStatistic) -> Double = { statistic ->\n",
" - abs(parabolas.sumOf { statistic(it) } - hyperbolas.sumOf { statistic(it) })\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "h7UmglJW5zXkAfKHK40oIL",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"Using commons-math optimizer to optimize weights"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"import org.apache.commons.math3.optim.*\n",
"import org.apache.commons.math3.optim.nonlinear.scalar.*\n",
"import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.*\n",
"\n",
"val optimizer = SimplexOptimizer(1e-1, Double.MAX_VALUE)\n",
"\n",
"val result = optimizer.optimize(\n",
" ObjectiveFunction { point ->\n",
" lossFunction(ConvolutionalXYStatistic(point))\n",
" },\n",
" NelderMeadSimplex(xValues.size),\n",
" InitialGuess(DoubleArray(xValues.size){ 1.0 }),\n",
" GoalType.MINIMIZE,\n",
" MaxEval(100000)\n",
")"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "0EG3K4aCUciMlgGQKPvJ57",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"Print resulting weights of optimization"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"result.point"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "LelUlY0ZSlJEO9yC6SLk5B",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"source": [
"Plotly.plot { \n",
" scatter { \n",
" y.doubles = result.point\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "AuFOq5t9KpOIkGrOLsVXNf",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "markdown",
"source": [
"# The resulting statistic distribution"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"source": [
"val resultStatistic = ConvolutionalXYStatistic(result.point)\n",
"Plotly.plot { \n",
" histogram { \n",
" name = \"parabolae\"\n",
" x.numbers = parabolas.map { resultStatistic(it) }\n",
" }\n",
" histogram { \n",
" name = \"hyperbolae\"\n",
" x.numbers = hyperbolas.map { resultStatistic(it) }\n",
" }\n",
"}"
],
"execution_count": null,
"outputs": [],
"metadata": {
"datalore": {
"node_id": "zvmq42DRdM5mZ3SpzviHwI",
"type": "CODE",
"hide_input_from_viewers": false,
"hide_output_from_viewers": false
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Kotlin",
"language": "kotlin",
"name": "kotlin"
},
"datalore": {
"version": 1,
"computation_mode": "JUPYTER",
"package_manager": "pip",
"base_environment": "default",
"packages": []
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@ -0,0 +1,91 @@
/*
* Copyright 2018-2023 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.expressions
import space.kscience.kmath.UnstableKMathAPI
// Only kmath-core is needed.
// Let's declare some variables
val x by symbol
val y by symbol
val z by symbol
@OptIn(UnstableKMathAPI::class)
fun main() {
// Let's define some random expression.
val someExpression = Double.autodiff.differentiate {
// We bind variables `x` and `y` to the builder scope,
val x = bindSymbol(x)
val y = bindSymbol(y)
// Then we use the bindings to define expression `xy + x + y - 1`
x * y + x + y - 1
}
// Then we can evaluate it at any point ((-1, -1) in the case):
println(someExpression(mapOf(x to -1.0, y to -1.0)))
// >>> -2.0
// We can also construct its partial derivatives:
val dxExpression = someExpression.derivative(x) // ∂/∂x. Must be `y+1`
val dyExpression = someExpression.derivative(y) // ∂/∂y. Must be `x+1`
val dxdxExpression = someExpression.derivative(x, x) // ∂^2/∂x^2. Must be `0`
// We can evaluate them as well
println(dxExpression(mapOf(x to 57.0, y to 6.0)))
// >>> 7.0
println(dyExpression(mapOf(x to -1.0, y to 179.0)))
// >>> 0.0
println(dxdxExpression(mapOf(x to 239.0, y to 30.0)))
// >>> 0.0
// You can also provide extra arguments that obviously won't affect the result:
println(dxExpression(mapOf(x to 57.0, y to 6.0, z to 42.0)))
// >>> 7.0
println(dyExpression(mapOf(x to -1.0, y to 179.0, z to 0.0)))
// >>> 0.0
println(dxdxExpression(mapOf(x to 239.0, y to 30.0, z to 100_000.0)))
// >>> 0.0
// But in case you forgot to specify bound symbol's value, exception is thrown:
println( runCatching { someExpression(mapOf(z to 4.0)) } )
// >>> Failure(java.lang.IllegalStateException: Symbol 'x' is not supported in ...)
// The reason is that the expression is evaluated lazily,
// and each `bindSymbol` operation actually substitutes the provided symbol with the corresponding value.
// For example, let there be an expression
val simpleExpression = Double.autodiff.differentiate {
val x = bindSymbol(x)
x pow 2
}
// When you evaluate it via
simpleExpression(mapOf(x to 1.0, y to 57.0, z to 179.0))
// lambda above has the context of map `{x: 1.0, y: 57.0, z: 179.0}`.
// When x is bound, you can think of it as substitution `x -> 1.0`.
// Other values are unused which does not make any problem to us.
// But in the case the corresponding value is not provided,
// we cannot bind the variable. Thus, exception is thrown.
// There is also a function `bindSymbolOrNull` that fixes the problem:
val fixedExpression = Double.autodiff.differentiate {
val x = bindSymbolOrNull(x) ?: const(8.0)
x pow -2
}
println(fixedExpression())
// >>> 0.015625
// It works!
// The expression provides a bunch of operations:
// 1. Constant bindings (via `const` and `number`).
// 2. Variable bindings (via `bindVariable`, `bindVariableOrNull`).
// 3. Arithmetic operations (via `+`, `-`, `*`, and `-`).
// 4. Exponentiation (via `pow` or `power`).
// 5. `exp` and `ln`.
// 6. Trigonometrical functions (`sin`, `cos`, `tan`, `cot`).
// 7. Inverse trigonometrical functions (`asin`, `acos`, `atan`, `acot`).
// 8. Hyperbolic functions and inverse hyperbolic functions.
}

View File

@ -7,10 +7,9 @@ package space.kscience.kmath.fit
import kotlinx.html.br import kotlinx.html.br
import kotlinx.html.h3 import kotlinx.html.h3
import space.kscience.kmath.commons.expressions.DSProcessor
import space.kscience.kmath.commons.optimization.CMOptimizer import space.kscience.kmath.commons.optimization.CMOptimizer
import space.kscience.kmath.distributions.NormalDistribution import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.expressions.chiSquaredExpression import space.kscience.kmath.expressions.autodiff
import space.kscience.kmath.expressions.symbol import space.kscience.kmath.expressions.symbol
import space.kscience.kmath.operations.asIterable import space.kscience.kmath.operations.asIterable
import space.kscience.kmath.operations.toList import space.kscience.kmath.operations.toList
@ -22,6 +21,7 @@ import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.real.DoubleVector import space.kscience.kmath.real.DoubleVector
import space.kscience.kmath.real.map import space.kscience.kmath.real.map
import space.kscience.kmath.real.step import space.kscience.kmath.real.step
import space.kscience.kmath.stat.chiSquaredExpression
import space.kscience.plotly.* import space.kscience.plotly.*
import space.kscience.plotly.models.ScatterMode import space.kscience.plotly.models.ScatterMode
import space.kscience.plotly.models.TraceValues import space.kscience.plotly.models.TraceValues
@ -67,7 +67,7 @@ suspend fun main() {
val yErr = y.map { sqrt(it) }//RealVector.same(x.size, sigma) val yErr = y.map { sqrt(it) }//RealVector.same(x.size, sigma)
// compute differentiable chi^2 sum for given model ax^2 + bx + c // compute differentiable chi^2 sum for given model ax^2 + bx + c
val chi2 = DSProcessor.chiSquaredExpression(x, y, yErr) { arg -> val chi2 = Double.autodiff.chiSquaredExpression(x, y, yErr) { arg ->
//bind variables to autodiff context //bind variables to autodiff context
val a = bindSymbol(a) val a = bindSymbol(a)
val b = bindSymbol(b) val b = bindSymbol(b)

View File

@ -7,18 +7,15 @@ package space.kscience.kmath.fit
import kotlinx.html.br import kotlinx.html.br
import kotlinx.html.h3 import kotlinx.html.h3
import space.kscience.kmath.commons.expressions.DSProcessor
import space.kscience.kmath.data.XYErrorColumnarData import space.kscience.kmath.data.XYErrorColumnarData
import space.kscience.kmath.distributions.NormalDistribution import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.expressions.autodiff
import space.kscience.kmath.expressions.binding import space.kscience.kmath.expressions.binding
import space.kscience.kmath.expressions.symbol import space.kscience.kmath.expressions.symbol
import space.kscience.kmath.operations.asIterable import space.kscience.kmath.operations.asIterable
import space.kscience.kmath.operations.toList import space.kscience.kmath.operations.toList
import space.kscience.kmath.optimization.QowOptimizer import space.kscience.kmath.optimization.*
import space.kscience.kmath.optimization.chiSquaredOrNull
import space.kscience.kmath.optimization.fitWith
import space.kscience.kmath.optimization.resultPoint
import space.kscience.kmath.random.RandomGenerator import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.real.map import space.kscience.kmath.real.map
import space.kscience.kmath.real.step import space.kscience.kmath.real.step
@ -32,6 +29,8 @@ import kotlin.math.sqrt
private val a by symbol private val a by symbol
private val b by symbol private val b by symbol
private val c by symbol private val c by symbol
private val d by symbol
private val e by symbol
/** /**
@ -63,17 +62,23 @@ suspend fun main() {
val result = XYErrorColumnarData.of(x, y, yErr).fitWith( val result = XYErrorColumnarData.of(x, y, yErr).fitWith(
QowOptimizer, QowOptimizer,
DSProcessor, Double.autodiff,
mapOf(a to 0.9, b to 1.2, c to 2.0) mapOf(a to 0.9, b to 1.2, c to 2.0, e to 1.0, d to 1.0, e to 0.0),
OptimizationParameters(a, b, c, d)
) { arg -> ) { arg ->
//bind variables to autodiff context //bind variables to autodiff context
val a by binding val a by binding
val b by binding val b by binding
//Include default value for c if it is not provided as a parameter //Include default value for c if it is not provided as a parameter
val c = bindSymbolOrNull(c) ?: one val c = bindSymbolOrNull(c) ?: one
a * arg.pow(2) + b * arg + c val d by binding
val e by binding
a * arg.pow(2) + b * arg + c + d * arg.pow(3) + e / arg
} }
println("Resulting chi2/dof: ${result.chiSquaredOrNull}/${result.dof}")
//display a page with plot and numerical results //display a page with plot and numerical results
val page = Plotly.page { val page = Plotly.page {
plot { plot {
@ -89,7 +94,7 @@ suspend fun main() {
scatter { scatter {
mode = ScatterMode.lines mode = ScatterMode.lines
x(x) x(x)
y(x.map { result.model(result.resultPoint + (Symbol.x to it)) }) y(x.map { result.model(result.startPoint + result.resultPoint + (Symbol.x to it)) })
name = "fit" name = "fit"
} }
} }
@ -98,7 +103,7 @@ suspend fun main() {
+"Fit result: ${result.resultPoint}" +"Fit result: ${result.resultPoint}"
} }
h3 { h3 {
+"Chi2/dof = ${result.chiSquaredOrNull!! / (x.size - 3)}" +"Chi2/dof = ${result.chiSquaredOrNull!! / result.dof}"
} }
} }

View File

@ -5,6 +5,11 @@
package space.kscience.kmath.functions package space.kscience.kmath.functions
import space.kscience.kmath.complex.Complex
import space.kscience.kmath.complex.ComplexField
import space.kscience.kmath.complex.ComplexField.div
import space.kscience.kmath.complex.ComplexField.minus
import space.kscience.kmath.complex.algebra
import space.kscience.kmath.integration.gaussIntegrator import space.kscience.kmath.integration.gaussIntegrator
import space.kscience.kmath.integration.integrate import space.kscience.kmath.integration.integrate
import space.kscience.kmath.integration.value import space.kscience.kmath.integration.value
@ -20,4 +25,12 @@ fun main() {
//the value is nullable because in some cases the integration could not succeed //the value is nullable because in some cases the integration could not succeed
println(result.value) println(result.value)
repeat(100000) {
Complex.algebra.gaussIntegrator.integrate(0.0..1.0, intervals = 1000) { x: Double ->
// sin(1 / x) + i * cos(1 / x)
1 / x - ComplexField.i / x
}.value
}
} }

View File

@ -12,23 +12,21 @@ import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.nd.structureND import space.kscience.kmath.nd.structureND
import space.kscience.kmath.nd.withNdAlgebra import space.kscience.kmath.nd.withNdAlgebra
import space.kscience.kmath.operations.algebra import space.kscience.kmath.operations.algebra
import space.kscience.kmath.operations.invoke import kotlin.math.pow
fun main(): Unit = Double.algebra { fun main(): Unit = Double.algebra.withNdAlgebra(2, 2) {
withNdAlgebra(2, 2) {
//Produce a diagonal StructureND //Produce a diagonal StructureND
fun diagonal(v: Double) = structureND { (i, j) -> fun diagonal(v: Double) = structureND { (i, j) ->
if (i == j) v else 0.0 if (i == j) v else 0.0
}
//Define a function in a nd space
val function: (Double) -> StructureND<Double> = { x: Double -> 3 * x.pow(2) + 2 * diagonal(x) + 1 }
//get the result of the integration
val result = gaussIntegrator.integrate(0.0..10.0, function = function)
//the value is nullable because in some cases the integration could not succeed
println(result.value)
} }
}
//Define a function in a nd space
val function: (Double) -> StructureND<Double> = { x: Double -> 3 * x.pow(2) + 2 * diagonal(x) + 1 }
//get the result of the integration
val result = gaussIntegrator.integrate(0.0..10.0, function = function)
//the value is nullable because in some cases the integration could not succeed
println(result.value)
}

View File

@ -7,8 +7,10 @@ package space.kscience.kmath.linear
import space.kscience.kmath.operations.algebra import space.kscience.kmath.operations.algebra
import kotlin.random.Random import kotlin.random.Random
import kotlin.system.measureTimeMillis import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@OptIn(ExperimentalTime::class)
fun main() { fun main() {
val random = Random(12224) val random = Random(12224)
val dim = 1000 val dim = 1000
@ -21,7 +23,7 @@ fun main() {
if (i <= j) random.nextDouble() else 0.0 if (i <= j) random.nextDouble() else 0.0
} }
val time = measureTimeMillis { val time = measureTime {
with(Double.algebra.linearSpace) { with(Double.algebra.linearSpace) {
repeat(10) { repeat(10) {
matrix1 dot matrix2 matrix1 dot matrix2

View File

@ -0,0 +1,17 @@
/*
* Copyright 2018-2023 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.series
import kotlinx.datetime.Instant
import space.kscience.kmath.operations.algebra
import space.kscience.kmath.operations.bufferAlgebra
import kotlin.time.Duration
fun SeriesAlgebra.Companion.time(zero: Instant, step: Duration) = MonotonicSeriesAlgebra(
bufferAlgebra = Double.algebra.bufferAlgebra,
offsetToLabel = { zero + step * it },
labelToOffset = { (it - zero) / step }
)

View File

@ -1,9 +1,8 @@
package space.kscience.kmath.series package space.kscience.kmath.series
import kotlinx.html.FlowContent
import kotlinx.html.h1 import kotlinx.html.h1
import space.kscience.kmath.operations.DoubleBufferOps import kotlinx.html.p
import space.kscience.kmath.operations.algebra import space.kscience.kmath.operations.algebra
import space.kscience.kmath.operations.bufferAlgebra import space.kscience.kmath.operations.bufferAlgebra
import space.kscience.kmath.operations.toList import space.kscience.kmath.operations.toList
@ -15,35 +14,43 @@ import space.kscience.plotly.*
import kotlin.math.PI import kotlin.math.PI
fun main() = with(Double.algebra.bufferAlgebra.seriesAlgebra()) { fun main() = with(Double.algebra.bufferAlgebra.seriesAlgebra()) {
fun FlowContent.plotSeries(buffer: Buffer<Double>) {
val ls = buffer.labels
plot { fun Plot.plotSeries(name: String, buffer: Buffer<Double>) {
scatter { scatter {
x.numbers = ls this.name = name
y.numbers = buffer.toList() x.numbers = buffer.labels
} y.numbers = buffer.toList()
}
}
val s1 = series(100) { sin(2 * PI * it / 100) + 1.0 }
val s2 = s1.slice(20..50).moveTo(40)
val s3: Buffer<Double> = s1.zip(s2) { l, r -> l + r } //s1 + s2
val s4 = s3.map { ln(it) }
val kmTest: KMComparisonResult<Double> = ksComparisonStatistic(s1, s2)
Plotly.page {
h1 { +"This is my plot" }
p{
+"Kolmogorov-smirnov test for s1 and s2: ${kmTest.value}"
}
plot{
plotSeries("s1", s1)
plotSeries("s2", s2)
plotSeries("s3", s3)
plotSeries("s4", s4)
layout { layout {
xaxis { xaxis {
range(0.0..100.0) range(0.0..100.0)
} }
} }
} }
}
val s1 = series(100) { sin(2 * PI * it / 100) + 1.0 }
val s2 = s1.slice(20..50).moveTo(40)
val s3: Buffer<Double> = s1.zip(s2) { l, r -> l + r } //s1 + s2
val s4 = DoubleBufferOps.ln(s3)
val kmTest: KMComparisonResult<Double> = ksComparisonStatistic(s1, s2)
Plotly.page {
h1 { +"This is my plot" }
plotSeries(s1)
plotSeries(s2)
plotSeries(s4)
}.makeFile() }.makeFile()
} }

View File

@ -36,7 +36,7 @@ private suspend fun runKMathChained(): Duration {
return Duration.between(startTime, Instant.now()) return Duration.between(startTime, Instant.now())
} }
private fun runApacheDirect(): Duration { private fun runCMDirect(): Duration {
val rng = RandomSource.create(RandomSource.MT, 123L) val rng = RandomSource.create(RandomSource.MT, 123L)
val sampler = CMGaussianSampler.of( val sampler = CMGaussianSampler.of(
@ -65,7 +65,7 @@ private fun runApacheDirect(): Duration {
* Comparing chain sampling performance with direct sampling performance * Comparing chain sampling performance with direct sampling performance
*/ */
fun main(): Unit = runBlocking(Dispatchers.Default) { fun main(): Unit = runBlocking(Dispatchers.Default) {
val directJob = async { runApacheDirect() } val directJob = async { runCMDirect() }
val chainJob = async { runKMathChained() } val chainJob = async { runKMathChained() }
println("KMath Chained: ${chainJob.await()}") println("KMath Chained: ${chainJob.await()}")
println("Apache Direct: ${directJob.await()}") println("Apache Direct: ${directJob.await()}")

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.structures package space.kscience.kmath.structures
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.nd.* import space.kscience.kmath.nd.*
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.ExtendedField import space.kscience.kmath.operations.ExtendedField

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.structures package space.kscience.kmath.structures
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.nd.BufferND import space.kscience.kmath.nd.BufferND
import space.kscience.kmath.nd.ColumnStrides import space.kscience.kmath.nd.ColumnStrides
import space.kscience.kmath.nd.ShapeND import space.kscience.kmath.nd.ShapeND

View File

@ -5,12 +5,11 @@
kotlin.code.style=official kotlin.code.style=official
kotlin.mpp.stability.nowarn=true kotlin.mpp.stability.nowarn=true
kotlin.native.ignoreDisabledTargets=true kotlin.native.ignoreDisabledTargets=true
kotlin.incremental.js.ir=true
org.gradle.configureondemand=true org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx4096m org.gradle.jvmargs=-Xmx4096m
toolsVersion=0.13.1-kotlin-1.7.20 toolsVersion=0.14.6-kotlin-1.8.20
org.gradle.parallel=true org.gradle.parallel=true

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

View File

@ -10,7 +10,7 @@ Extensions to MST API: transformations, dynamic compilation and visualization.
## Artifact: ## Artifact:
The Maven coordinates of this project are `space.kscience:kmath-ast:0.3.1-dev-1`. The Maven coordinates of this project are `space.kscience:kmath-ast:0.4.0-dev-1`.
**Gradle Groovy:** **Gradle Groovy:**
```groovy ```groovy
@ -20,7 +20,7 @@ repositories {
} }
dependencies { dependencies {
implementation 'space.kscience:kmath-ast:0.3.1-dev-1' implementation 'space.kscience:kmath-ast:0.4.0-dev-1'
} }
``` ```
**Gradle Kotlin DSL:** **Gradle Kotlin DSL:**
@ -31,7 +31,7 @@ repositories {
} }
dependencies { dependencies {
implementation("space.kscience:kmath-ast:0.3.1-dev-1") implementation("space.kscience:kmath-ast:0.4.0-dev-1")
} }
``` ```

View File

@ -3,65 +3,58 @@ plugins {
} }
kscience{ kscience{
jvm()
js()
native() native()
dependencies {
api(projects.kmathCore)
api("com.github.h0tk3y.betterParse:better-parse:0.4.4")
}
testDependencies {
implementation(projects.kmathComplex)
}
dependencies(jsMain) {
implementation(npm("astring", "1.7.5"))
implementation(npm("binaryen", "101.0.0"))
implementation(npm("js-base64", "3.6.1"))
}
dependencies(jvmMain){
implementation("org.ow2.asm:asm-commons:9.2")
}
} }
kotlin.js { kotlin {
nodejs { js {
testTask { nodejs {
useMocha().timeout = "0" testTask {
useMocha().timeout = "0"
}
}
browser {
testTask {
useMocha().timeout = "0"
}
} }
} }
browser { sourceSets {
testTask { filter { it.name.contains("test", true) }
useMocha().timeout = "0" .map(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::languageSettings)
} .forEach { it.optIn("space.kscience.kmath.misc.UnstableKMathAPI") }
} }
} }
kotlin.sourceSets { if (System.getProperty("space.kscience.kmath.ast.dump.generated.classes") == "1") {
filter { it.name.contains("test", true) } tasks.withType<org.jetbrains.kotlin.gradle.targets.jvm.tasks.KotlinJvmTest> {
.map(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::languageSettings)
.forEach { it.optIn("space.kscience.kmath.misc.UnstableKMathAPI") }
commonMain {
dependencies {
api("com.github.h0tk3y.betterParse:better-parse:0.4.4")
api(project(":kmath-core"))
}
}
commonTest {
dependencies {
implementation(project(":kmath-complex"))
}
}
jsMain {
dependencies {
implementation(npm("astring", "1.7.5"))
implementation(npm("binaryen", "101.0.0"))
implementation(npm("js-base64", "3.6.1"))
}
}
jvmMain {
dependencies {
implementation("org.ow2.asm:asm-commons:9.2")
}
}
}
//Workaround for https://github.com/Kotlin/dokka/issues/1455
tasks.dokkaHtml {
dependsOn(tasks.build)
}
if (System.getProperty("space.kscience.kmath.ast.dump.generated.classes") == "1")
tasks.jvmTest {
jvmArgs("-Dspace.kscience.kmath.ast.dump.generated.classes=1") jvmArgs("-Dspace.kscience.kmath.ast.dump.generated.classes=1")
} }
}
readme { readme {
maturity = space.kscience.gradle.Maturity.EXPERIMENTAL maturity = space.kscience.gradle.Maturity.EXPERIMENTAL

View File

@ -7,7 +7,6 @@ package space.kscience.kmath.ast
import space.kscience.kmath.expressions.Expression import space.kscience.kmath.expressions.Expression
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.Algebra import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.NumericAlgebra import space.kscience.kmath.operations.NumericAlgebra
@ -16,7 +15,6 @@ import space.kscience.kmath.operations.NumericAlgebra
* *
* @param T the type. * @param T the type.
*/ */
@UnstableKMathAPI
public sealed interface TypedMst<T> { public sealed interface TypedMst<T> {
/** /**
* A node containing a unary operation. * A node containing a unary operation.
@ -133,7 +131,6 @@ public sealed interface TypedMst<T> {
/** /**
* Interprets the [TypedMst] node with this [Algebra] and [arguments]. * Interprets the [TypedMst] node with this [Algebra] and [arguments].
*/ */
@UnstableKMathAPI
public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, arguments: Map<Symbol, T>): T = when (this) { public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, arguments: Map<Symbol, T>): T = when (this) {
is TypedMst.Unary -> algebra.unaryOperation(operation, interpret(algebra, arguments)) is TypedMst.Unary -> algebra.unaryOperation(operation, interpret(algebra, arguments))
@ -158,7 +155,6 @@ public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, arguments: Map<Symbol,
/** /**
* Interprets the [TypedMst] node with this [Algebra] and optional [arguments]. * Interprets the [TypedMst] node with this [Algebra] and optional [arguments].
*/ */
@UnstableKMathAPI
public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, vararg arguments: Pair<Symbol, T>): T = interpret( public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, vararg arguments: Pair<Symbol, T>): T = interpret(
algebra, algebra,
when (arguments.size) { when (arguments.size) {
@ -171,7 +167,6 @@ public fun <T> TypedMst<T>.interpret(algebra: Algebra<T>, vararg arguments: Pair
/** /**
* Interpret this [TypedMst] node as expression. * Interpret this [TypedMst] node as expression.
*/ */
@UnstableKMathAPI
public fun <T : Any> TypedMst<T>.toExpression(algebra: Algebra<T>): Expression<T> = Expression { arguments -> public fun <T : Any> TypedMst<T>.toExpression(algebra: Algebra<T>): Expression<T> = Expression { arguments ->
interpret(algebra, arguments) interpret(algebra, arguments)
} }

View File

@ -7,7 +7,6 @@ package space.kscience.kmath.ast
import space.kscience.kmath.expressions.MST import space.kscience.kmath.expressions.MST
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.Algebra import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.NumericAlgebra import space.kscience.kmath.operations.NumericAlgebra
import space.kscience.kmath.operations.bindSymbolOrNull import space.kscience.kmath.operations.bindSymbolOrNull
@ -15,7 +14,6 @@ import space.kscience.kmath.operations.bindSymbolOrNull
/** /**
* Evaluates constants in given [MST] for given [algebra] at the same time with converting to [TypedMst]. * Evaluates constants in given [MST] for given [algebra] at the same time with converting to [TypedMst].
*/ */
@UnstableKMathAPI
public fun <T> MST.evaluateConstants(algebra: Algebra<T>): TypedMst<T> = when (this) { public fun <T> MST.evaluateConstants(algebra: Algebra<T>): TypedMst<T> = when (this) {
is MST.Numeric -> TypedMst.Constant( is MST.Numeric -> TypedMst.Constant(
(algebra as? NumericAlgebra<T>)?.number(value) ?: error("Numeric nodes are not supported by $algebra"), (algebra as? NumericAlgebra<T>)?.number(value) ?: error("Numeric nodes are not supported by $algebra"),

View File

@ -5,8 +5,6 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* [SyntaxRenderer] implementation for LaTeX. * [SyntaxRenderer] implementation for LaTeX.
* *
@ -25,7 +23,6 @@ import space.kscience.kmath.misc.UnstableKMathAPI
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public object LatexSyntaxRenderer : SyntaxRenderer { public object LatexSyntaxRenderer : SyntaxRenderer {
override fun render(node: MathSyntax, output: Appendable): Unit = output.run { override fun render(node: MathSyntax, output: Appendable): Unit = output.run {
fun render(syntax: MathSyntax) = render(syntax, output) fun render(syntax: MathSyntax) = render(syntax, output)

View File

@ -5,8 +5,6 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* [SyntaxRenderer] implementation for MathML. * [SyntaxRenderer] implementation for MathML.
* *
@ -14,7 +12,6 @@ import space.kscience.kmath.misc.UnstableKMathAPI
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public object MathMLSyntaxRenderer : SyntaxRenderer { public object MathMLSyntaxRenderer : SyntaxRenderer {
override fun render(node: MathSyntax, output: Appendable) { override fun render(node: MathSyntax, output: Appendable) {
output.append("<math xmlns=\"https://www.w3.org/1998/Math/MathML\"><mrow>") output.append("<math xmlns=\"https://www.w3.org/1998/Math/MathML\"><mrow>")

View File

@ -6,14 +6,12 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.expressions.MST import space.kscience.kmath.expressions.MST
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* Renders [MST] to [MathSyntax]. * Renders [MST] to [MathSyntax].
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public fun interface MathRenderer { public fun interface MathRenderer {
/** /**
* Renders [MST] to [MathSyntax]. * Renders [MST] to [MathSyntax].
@ -27,7 +25,6 @@ public fun interface MathRenderer {
* @property features The applied features. * @property features The applied features.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public open class FeaturedMathRenderer(public val features: List<RenderFeature>) : MathRenderer { public open class FeaturedMathRenderer(public val features: List<RenderFeature>) : MathRenderer {
override fun render(mst: MST): MathSyntax { override fun render(mst: MST): MathSyntax {
for (feature in features) feature.render(this, mst)?.let { return it } for (feature in features) feature.render(this, mst)?.let { return it }
@ -51,7 +48,6 @@ public open class FeaturedMathRenderer(public val features: List<RenderFeature>)
* @property stages The applied stages. * @property stages The applied stages.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public open class FeaturedMathRendererWithPostProcess( public open class FeaturedMathRendererWithPostProcess(
features: List<RenderFeature>, features: List<RenderFeature>,
public val stages: List<PostProcessPhase>, public val stages: List<PostProcessPhase>,

View File

@ -5,14 +5,11 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* Syntax node for mathematical typography. * Syntax node for mathematical typography.
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public sealed class MathSyntax { public sealed class MathSyntax {
/** /**
* The parent node of this syntax node. * The parent node of this syntax node.
@ -25,7 +22,6 @@ public sealed class MathSyntax {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public sealed class TerminalSyntax : MathSyntax() public sealed class TerminalSyntax : MathSyntax()
/** /**
@ -33,7 +29,6 @@ public sealed class TerminalSyntax : MathSyntax()
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public sealed class OperationSyntax : MathSyntax() { public sealed class OperationSyntax : MathSyntax() {
/** /**
* The operation token. * The operation token.
@ -46,7 +41,6 @@ public sealed class OperationSyntax : MathSyntax() {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public sealed class UnarySyntax : OperationSyntax() { public sealed class UnarySyntax : OperationSyntax() {
/** /**
* The operand of this node. * The operand of this node.
@ -59,7 +53,6 @@ public sealed class UnarySyntax : OperationSyntax() {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public sealed class BinarySyntax : OperationSyntax() { public sealed class BinarySyntax : OperationSyntax() {
/** /**
* The left-hand side operand. * The left-hand side operand.
@ -78,7 +71,6 @@ public sealed class BinarySyntax : OperationSyntax() {
* @property string The digits of number. * @property string The digits of number.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class NumberSyntax(public var string: String) : TerminalSyntax() public data class NumberSyntax(public var string: String) : TerminalSyntax()
/** /**
@ -87,7 +79,6 @@ public data class NumberSyntax(public var string: String) : TerminalSyntax()
* @property string The symbol. * @property string The symbol.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class SymbolSyntax(public var string: String) : TerminalSyntax() public data class SymbolSyntax(public var string: String) : TerminalSyntax()
/** /**
@ -98,7 +89,6 @@ public data class SymbolSyntax(public var string: String) : TerminalSyntax()
* @see UnaryOperatorSyntax * @see UnaryOperatorSyntax
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class OperatorNameSyntax(public var name: String) : TerminalSyntax() public data class OperatorNameSyntax(public var name: String) : TerminalSyntax()
/** /**
@ -107,7 +97,6 @@ public data class OperatorNameSyntax(public var name: String) : TerminalSyntax()
* @property kind The kind of symbol. * @property kind The kind of symbol.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class SpecialSymbolSyntax(public var kind: Kind) : TerminalSyntax() { public data class SpecialSymbolSyntax(public var kind: Kind) : TerminalSyntax() {
/** /**
* The kind of symbol. * The kind of symbol.
@ -132,7 +121,6 @@ public data class SpecialSymbolSyntax(public var kind: Kind) : TerminalSyntax()
* @property parentheses Whether the operand should be wrapped with parentheses. * @property parentheses Whether the operand should be wrapped with parentheses.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class OperandSyntax( public data class OperandSyntax(
public val operand: MathSyntax, public val operand: MathSyntax,
public var parentheses: Boolean, public var parentheses: Boolean,
@ -148,7 +136,6 @@ public data class OperandSyntax(
* @property prefix The prefix. * @property prefix The prefix.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class UnaryOperatorSyntax( public data class UnaryOperatorSyntax(
override val operation: String, override val operation: String,
public var prefix: MathSyntax, public var prefix: MathSyntax,
@ -164,7 +151,6 @@ public data class UnaryOperatorSyntax(
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class UnaryPlusSyntax( public data class UnaryPlusSyntax(
override val operation: String, override val operation: String,
override val operand: OperandSyntax, override val operand: OperandSyntax,
@ -179,7 +165,6 @@ public data class UnaryPlusSyntax(
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class UnaryMinusSyntax( public data class UnaryMinusSyntax(
override val operation: String, override val operation: String,
override val operand: OperandSyntax, override val operand: OperandSyntax,
@ -195,7 +180,6 @@ public data class UnaryMinusSyntax(
* @property operand The radicand. * @property operand The radicand.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class RadicalSyntax( public data class RadicalSyntax(
override val operation: String, override val operation: String,
override val operand: MathSyntax, override val operand: MathSyntax,
@ -213,7 +197,6 @@ public data class RadicalSyntax(
* (*e<sup>x</sup>*). * (*e<sup>x</sup>*).
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class ExponentSyntax( public data class ExponentSyntax(
override val operation: String, override val operation: String,
override val operand: OperandSyntax, override val operand: OperandSyntax,
@ -231,7 +214,6 @@ public data class ExponentSyntax(
* @property right The superscript. * @property right The superscript.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class SuperscriptSyntax( public data class SuperscriptSyntax(
override val operation: String, override val operation: String,
override val left: MathSyntax, override val left: MathSyntax,
@ -250,7 +232,6 @@ public data class SuperscriptSyntax(
* @property right The subscript. * @property right The subscript.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class SubscriptSyntax( public data class SubscriptSyntax(
override val operation: String, override val operation: String,
override val left: MathSyntax, override val left: MathSyntax,
@ -268,7 +249,6 @@ public data class SubscriptSyntax(
* @property prefix The prefix. * @property prefix The prefix.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class BinaryOperatorSyntax( public data class BinaryOperatorSyntax(
override val operation: String, override val operation: String,
public var prefix: MathSyntax, public var prefix: MathSyntax,
@ -288,7 +268,6 @@ public data class BinaryOperatorSyntax(
* @param right The addend. * @param right The addend.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class BinaryPlusSyntax( public data class BinaryPlusSyntax(
override val operation: String, override val operation: String,
override val left: OperandSyntax, override val left: OperandSyntax,
@ -307,7 +286,6 @@ public data class BinaryPlusSyntax(
* @param right The subtrahend. * @param right The subtrahend.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class BinaryMinusSyntax( public data class BinaryMinusSyntax(
override val operation: String, override val operation: String,
override val left: OperandSyntax, override val left: OperandSyntax,
@ -327,7 +305,6 @@ public data class BinaryMinusSyntax(
* @property infix Whether infix (*1 / 2*) or normal (*&frac12;*) fraction should be made. * @property infix Whether infix (*1 / 2*) or normal (*&frac12;*) fraction should be made.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class FractionSyntax( public data class FractionSyntax(
override val operation: String, override val operation: String,
override val left: OperandSyntax, override val left: OperandSyntax,
@ -347,7 +324,6 @@ public data class FractionSyntax(
* @property right The radicand. * @property right The radicand.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class RadicalWithIndexSyntax( public data class RadicalWithIndexSyntax(
override val operation: String, override val operation: String,
override val left: MathSyntax, override val left: MathSyntax,
@ -367,7 +343,6 @@ public data class RadicalWithIndexSyntax(
* @property times Whether the times (&times;) symbol should be used. * @property times Whether the times (&times;) symbol should be used.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public data class MultiplicationSyntax( public data class MultiplicationSyntax(
override val operation: String, override val operation: String,
override val left: OperandSyntax, override val left: OperandSyntax,

View File

@ -5,15 +5,12 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* Abstraction of writing [MathSyntax] as a string of an actual markup language. Typical implementation should * Abstraction of writing [MathSyntax] as a string of an actual markup language. Typical implementation should
* involve traversal of MathSyntax with handling each subtype. * involve traversal of MathSyntax with handling each subtype.
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public fun interface SyntaxRenderer { public fun interface SyntaxRenderer {
/** /**
* Renders the [MathSyntax] to [output]. * Renders the [MathSyntax] to [output].
@ -26,7 +23,6 @@ public fun interface SyntaxRenderer {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public fun SyntaxRenderer.renderWithStringBuilder(node: MathSyntax): String { public fun SyntaxRenderer.renderWithStringBuilder(node: MathSyntax): String {
val sb = StringBuilder() val sb = StringBuilder()
render(node, sb) render(node, sb)

View File

@ -8,7 +8,6 @@ package space.kscience.kmath.ast.rendering
import space.kscience.kmath.ast.rendering.FeaturedMathRenderer.RenderFeature import space.kscience.kmath.ast.rendering.FeaturedMathRenderer.RenderFeature
import space.kscience.kmath.expressions.MST import space.kscience.kmath.expressions.MST
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import kotlin.reflect.KClass import kotlin.reflect.KClass
@ -17,7 +16,6 @@ import kotlin.reflect.KClass
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public val PrintSymbol: RenderFeature = RenderFeature { _, node -> public val PrintSymbol: RenderFeature = RenderFeature { _, node ->
if (node !is Symbol) null if (node !is Symbol) null
else SymbolSyntax(string = node.identity) else SymbolSyntax(string = node.identity)
@ -28,7 +26,6 @@ public val PrintSymbol: RenderFeature = RenderFeature { _, node ->
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public val PrintNumeric: RenderFeature = RenderFeature { _, node -> public val PrintNumeric: RenderFeature = RenderFeature { _, node ->
if (node !is MST.Numeric) if (node !is MST.Numeric)
null null
@ -36,7 +33,6 @@ public val PrintNumeric: RenderFeature = RenderFeature { _, node ->
NumberSyntax(string = node.value.toString()) NumberSyntax(string = node.value.toString())
} }
@UnstableKMathAPI
private fun printSignedNumberString(s: String): MathSyntax = if (s.startsWith('-')) private fun printSignedNumberString(s: String): MathSyntax = if (s.startsWith('-'))
UnaryMinusSyntax( UnaryMinusSyntax(
operation = GroupOps.MINUS_OPERATION, operation = GroupOps.MINUS_OPERATION,
@ -55,7 +51,6 @@ else
* @property types The suitable types. * @property types The suitable types.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class PrettyPrintFloats(public val types: Set<KClass<out Number>>) : RenderFeature { public class PrettyPrintFloats(public val types: Set<KClass<out Number>>) : RenderFeature {
override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? { override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? {
if (node !is MST.Numeric || node.value::class !in types) return null if (node !is MST.Numeric || node.value::class !in types) return null
@ -115,7 +110,6 @@ public class PrettyPrintFloats(public val types: Set<KClass<out Number>>) : Rend
* @property types The suitable types. * @property types The suitable types.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class PrettyPrintIntegers(public val types: Set<KClass<out Number>>) : RenderFeature { public class PrettyPrintIntegers(public val types: Set<KClass<out Number>>) : RenderFeature {
override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? = override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? =
if (node !is MST.Numeric || node.value::class !in types) if (node !is MST.Numeric || node.value::class !in types)
@ -138,7 +132,6 @@ public class PrettyPrintIntegers(public val types: Set<KClass<out Number>>) : Re
* @property symbols The allowed symbols. * @property symbols The allowed symbols.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class PrettyPrintPi(public val symbols: Set<String>) : RenderFeature { public class PrettyPrintPi(public val symbols: Set<String>) : RenderFeature {
override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? = override fun render(renderer: FeaturedMathRenderer, node: MST): MathSyntax? =
if (node !is Symbol || node.identity !in symbols) if (node !is Symbol || node.identity !in symbols)
@ -161,7 +154,6 @@ public class PrettyPrintPi(public val symbols: Set<String>) : RenderFeature {
* @param operations the allowed operations. If `null`, any operation is accepted. * @param operations the allowed operations. If `null`, any operation is accepted.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public abstract class Unary(public val operations: Collection<String>?) : RenderFeature { public abstract class Unary(public val operations: Collection<String>?) : RenderFeature {
/** /**
* The actual render function specialized for [MST.Unary]. * The actual render function specialized for [MST.Unary].
@ -182,7 +174,6 @@ public abstract class Unary(public val operations: Collection<String>?) : Render
* @property operations the allowed operations. If `null`, any operation is accepted. * @property operations the allowed operations. If `null`, any operation is accepted.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public abstract class Binary(public val operations: Collection<String>?) : RenderFeature { public abstract class Binary(public val operations: Collection<String>?) : RenderFeature {
/** /**
* The actual render function specialized for [MST.Binary]. * The actual render function specialized for [MST.Binary].
@ -200,7 +191,6 @@ public abstract class Binary(public val operations: Collection<String>?) : Rende
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class BinaryPlus(operations: Collection<String>?) : Binary(operations) { public class BinaryPlus(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax =
BinaryPlusSyntax( BinaryPlusSyntax(
@ -222,7 +212,6 @@ public class BinaryPlus(operations: Collection<String>?) : Binary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class BinaryMinus(operations: Collection<String>?) : Binary(operations) { public class BinaryMinus(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax =
BinaryMinusSyntax( BinaryMinusSyntax(
@ -244,7 +233,6 @@ public class BinaryMinus(operations: Collection<String>?) : Binary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class UnaryPlus(operations: Collection<String>?) : Unary(operations) { public class UnaryPlus(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = UnaryPlusSyntax( override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = UnaryPlusSyntax(
operation = node.operation, operation = node.operation,
@ -264,7 +252,6 @@ public class UnaryPlus(operations: Collection<String>?) : Unary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class UnaryMinus(operations: Collection<String>?) : Unary(operations) { public class UnaryMinus(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = UnaryMinusSyntax( override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = UnaryMinusSyntax(
operation = node.operation, operation = node.operation,
@ -284,7 +271,6 @@ public class UnaryMinus(operations: Collection<String>?) : Unary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class Fraction(operations: Collection<String>?) : Binary(operations) { public class Fraction(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = FractionSyntax( override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = FractionSyntax(
operation = node.operation, operation = node.operation,
@ -306,7 +292,6 @@ public class Fraction(operations: Collection<String>?) : Binary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class BinaryOperator(operations: Collection<String>?) : Binary(operations) { public class BinaryOperator(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax =
BinaryOperatorSyntax( BinaryOperatorSyntax(
@ -329,7 +314,6 @@ public class BinaryOperator(operations: Collection<String>?) : Binary(operations
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class UnaryOperator(operations: Collection<String>?) : Unary(operations) { public class UnaryOperator(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax =
UnaryOperatorSyntax( UnaryOperatorSyntax(
@ -351,7 +335,6 @@ public class UnaryOperator(operations: Collection<String>?) : Unary(operations)
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class Power(operations: Collection<String>?) : Binary(operations) { public class Power(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax =
SuperscriptSyntax( SuperscriptSyntax(
@ -371,7 +354,6 @@ public class Power(operations: Collection<String>?) : Binary(operations) {
/** /**
* Handles binary nodes by producing [RadicalSyntax] with no index. * Handles binary nodes by producing [RadicalSyntax] with no index.
*/ */
@UnstableKMathAPI
public class SquareRoot(operations: Collection<String>?) : Unary(operations) { public class SquareRoot(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax =
RadicalSyntax(operation = node.operation, operand = parent.render(node.value)) RadicalSyntax(operation = node.operation, operand = parent.render(node.value))
@ -389,7 +371,6 @@ public class SquareRoot(operations: Collection<String>?) : Unary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class Exponent(operations: Collection<String>?) : Unary(operations) { public class Exponent(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = ExponentSyntax( override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = ExponentSyntax(
operation = node.operation, operation = node.operation,
@ -410,7 +391,6 @@ public class Exponent(operations: Collection<String>?) : Unary(operations) {
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class Multiplication(operations: Collection<String>?) : Binary(operations) { public class Multiplication(operations: Collection<String>?) : Binary(operations) {
override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax = override fun renderBinary(parent: FeaturedMathRenderer, node: MST.Binary): MathSyntax =
MultiplicationSyntax( MultiplicationSyntax(
@ -433,7 +413,6 @@ public class Multiplication(operations: Collection<String>?) : Binary(operations
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class InverseTrigonometricOperations(operations: Collection<String>?) : Unary(operations) { public class InverseTrigonometricOperations(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax =
UnaryOperatorSyntax( UnaryOperatorSyntax(
@ -460,7 +439,6 @@ public class InverseTrigonometricOperations(operations: Collection<String>?) : U
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class InverseHyperbolicOperations(operations: Collection<String>?) : Unary(operations) { public class InverseHyperbolicOperations(operations: Collection<String>?) : Unary(operations) {
override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax = override fun renderUnary(parent: FeaturedMathRenderer, node: MST.Unary): MathSyntax =
UnaryOperatorSyntax( UnaryOperatorSyntax(

View File

@ -6,7 +6,6 @@
package space.kscience.kmath.ast.rendering package space.kscience.kmath.ast.rendering
import space.kscience.kmath.ast.rendering.FeaturedMathRendererWithPostProcess.PostProcessPhase import space.kscience.kmath.ast.rendering.FeaturedMathRendererWithPostProcess.PostProcessPhase
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.FieldOps import space.kscience.kmath.operations.FieldOps
import space.kscience.kmath.operations.GroupOps import space.kscience.kmath.operations.GroupOps
import space.kscience.kmath.operations.PowerOperations import space.kscience.kmath.operations.PowerOperations
@ -17,7 +16,6 @@ import space.kscience.kmath.operations.RingOps
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public val BetterMultiplication: PostProcessPhase = PostProcessPhase { node -> public val BetterMultiplication: PostProcessPhase = PostProcessPhase { node ->
fun perform(node: MathSyntax): Unit = when (node) { fun perform(node: MathSyntax): Unit = when (node) {
is NumberSyntax -> Unit is NumberSyntax -> Unit
@ -91,7 +89,6 @@ public val BetterMultiplication: PostProcessPhase = PostProcessPhase { node ->
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public val BetterFraction: PostProcessPhase = PostProcessPhase { node -> public val BetterFraction: PostProcessPhase = PostProcessPhase { node ->
fun perform(node: MathSyntax, infix: Boolean = false): Unit = when (node) { fun perform(node: MathSyntax, infix: Boolean = false): Unit = when (node) {
is NumberSyntax -> Unit is NumberSyntax -> Unit
@ -162,7 +159,6 @@ public val BetterFraction: PostProcessPhase = PostProcessPhase { node ->
* *
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public val BetterExponent: PostProcessPhase = PostProcessPhase { node -> public val BetterExponent: PostProcessPhase = PostProcessPhase { node ->
fun perform(node: MathSyntax): Boolean { fun perform(node: MathSyntax): Boolean {
return when (node) { return when (node) {
@ -202,7 +198,6 @@ public val BetterExponent: PostProcessPhase = PostProcessPhase { node ->
* @property precedenceFunction Returns the precedence number for syntax node. Higher number is lower priority. * @property precedenceFunction Returns the precedence number for syntax node. Higher number is lower priority.
* @author Iaroslav Postovalov * @author Iaroslav Postovalov
*/ */
@UnstableKMathAPI
public class SimplifyParentheses(public val precedenceFunction: (MathSyntax) -> Int) : public class SimplifyParentheses(public val precedenceFunction: (MathSyntax) -> Int) :
PostProcessPhase { PostProcessPhase {
override fun perform(node: MathSyntax): Unit = when (node) { override fun perform(node: MathSyntax): Unit = when (node) {

View File

@ -5,6 +5,7 @@
package space.kscience.kmath.estree package space.kscience.kmath.estree
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.ast.TypedMst import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.ast.evaluateConstants import space.kscience.kmath.ast.evaluateConstants
import space.kscience.kmath.estree.internal.ESTreeBuilder import space.kscience.kmath.estree.internal.ESTreeBuilder
@ -13,7 +14,6 @@ import space.kscience.kmath.expressions.MST
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.expressions.invoke import space.kscience.kmath.expressions.invoke
import space.kscience.kmath.internal.estree.BaseExpression import space.kscience.kmath.internal.estree.BaseExpression
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.Algebra import space.kscience.kmath.operations.Algebra
/** /**

View File

@ -5,11 +5,11 @@
package space.kscience.kmath.wasm.internal package space.kscience.kmath.wasm.internal
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.ast.TypedMst import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.internal.binaryen.* import space.kscience.kmath.internal.binaryen.*
import space.kscience.kmath.internal.webassembly.Instance import space.kscience.kmath.internal.webassembly.Instance
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.internal.binaryen.Module as BinaryenModule import space.kscience.kmath.internal.binaryen.Module as BinaryenModule
import space.kscience.kmath.internal.webassembly.Module as WasmModule import space.kscience.kmath.internal.webassembly.Module as WasmModule

View File

@ -7,10 +7,10 @@
package space.kscience.kmath.wasm package space.kscience.kmath.wasm
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.ast.TypedMst import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.ast.evaluateConstants import space.kscience.kmath.ast.evaluateConstants
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.IntRing import space.kscience.kmath.operations.IntRing
import space.kscience.kmath.wasm.internal.DoubleWasmBuilder import space.kscience.kmath.wasm.internal.DoubleWasmBuilder

View File

@ -7,11 +7,11 @@
package space.kscience.kmath.asm package space.kscience.kmath.asm
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.asm.internal.* import space.kscience.kmath.asm.internal.*
import space.kscience.kmath.ast.TypedMst import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.ast.evaluateConstants import space.kscience.kmath.ast.evaluateConstants
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.Algebra import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.IntRing import space.kscience.kmath.operations.IntRing

View File

@ -11,9 +11,9 @@ import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type import org.objectweb.asm.Type
import org.objectweb.asm.Type.* import org.objectweb.asm.Type.*
import org.objectweb.asm.commons.InstructionAdapter import org.objectweb.asm.commons.InstructionAdapter
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.ast.TypedMst import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import java.lang.invoke.MethodHandles import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType import java.lang.invoke.MethodType

View File

@ -6,7 +6,7 @@ Commons math binding for kmath
## Artifact: ## Artifact:
The Maven coordinates of this project are `space.kscience:kmath-commons:0.3.1-dev-1`. The Maven coordinates of this project are `space.kscience:kmath-commons:0.4.0-dev-1`.
**Gradle Groovy:** **Gradle Groovy:**
```groovy ```groovy
@ -16,7 +16,7 @@ repositories {
} }
dependencies { dependencies {
implementation 'space.kscience:kmath-commons:0.3.1-dev-1' implementation 'space.kscience:kmath-commons:0.4.0-dev-1'
} }
``` ```
**Gradle Kotlin DSL:** **Gradle Kotlin DSL:**
@ -27,6 +27,6 @@ repositories {
} }
dependencies { dependencies {
implementation("space.kscience:kmath-commons:0.3.1-dev-1") implementation("space.kscience:kmath-commons:0.4.0-dev-1")
} }
``` ```

View File

@ -3,11 +3,13 @@
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. * 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("DEPRECATION")
package space.kscience.kmath.commons.expressions package space.kscience.kmath.commons.expressions
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure import org.apache.commons.math3.analysis.differentiation.DerivativeStructure
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.ExtendedField import space.kscience.kmath.operations.ExtendedField
import space.kscience.kmath.operations.NumbersAddOps import space.kscience.kmath.operations.NumbersAddOps
@ -18,7 +20,8 @@ import space.kscience.kmath.operations.NumbersAddOps
* @param 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) @OptIn(UnstableKMathAPI::class)
public class DerivativeStructureField( @Deprecated("Use generic DSAlgebra from the core")
public class CmDsField(
public val order: Int, public val order: Int,
bindings: Map<Symbol, Double>, bindings: Map<Symbol, Double>,
) : ExtendedField<DerivativeStructure>, ExpressionAlgebra<Double, DerivativeStructure>, ) : ExtendedField<DerivativeStructure>, ExpressionAlgebra<Double, DerivativeStructure>,
@ -108,25 +111,27 @@ public class DerivativeStructureField(
/** /**
* Auto-diff processor based on Commons-math [DerivativeStructure] * Auto-diff processor based on Commons-math [DerivativeStructure]
*/ */
public object DSProcessor : AutoDiffProcessor<Double, DerivativeStructure, DerivativeStructureField> { @Deprecated("Use generic DSAlgebra from the core")
public object CmDsProcessor : AutoDiffProcessor<Double, DerivativeStructure, CmDsField> {
override fun differentiate( override fun differentiate(
function: DerivativeStructureField.() -> DerivativeStructure, function: CmDsField.() -> DerivativeStructure,
): DerivativeStructureExpression = DerivativeStructureExpression(function) ): CmDsExpression = CmDsExpression(function)
} }
/** /**
* A constructs that creates a derivative structure with required order on-demand * A constructs that creates a derivative structure with required order on-demand
*/ */
public class DerivativeStructureExpression( @Deprecated("Use generic DSAlgebra from the core")
public val function: DerivativeStructureField.() -> DerivativeStructure, public class CmDsExpression(
public val function: CmDsField.() -> DerivativeStructure,
) : DifferentiableExpression<Double> { ) : DifferentiableExpression<Double> {
override operator fun invoke(arguments: Map<Symbol, Double>): Double = override operator fun invoke(arguments: Map<Symbol, Double>): Double =
DerivativeStructureField(0, arguments).function().value CmDsField(0, arguments).function().value
/** /**
* Get the derivative expression with given orders * Get the derivative expression with given orders
*/ */
override fun derivativeOrNull(symbols: List<Symbol>): Expression<Double> = Expression { arguments -> override fun derivativeOrNull(symbols: List<Symbol>): Expression<Double> = Expression { arguments ->
with(DerivativeStructureField(symbols.size, arguments)) { function().derivative(symbols) } with(CmDsField(symbols.size, arguments)) { function().derivative(symbols) }
} }
} }

View File

@ -7,8 +7,8 @@ package space.kscience.kmath.commons.integration
import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator
import org.apache.commons.math3.analysis.integration.SimpsonIntegrator import org.apache.commons.math3.analysis.integration.SimpsonIntegrator
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.integration.* import space.kscience.kmath.integration.*
import space.kscience.kmath.misc.UnstableKMathAPI
/** /**
* Integration wrapper for Common-maths UnivariateIntegrator * Integration wrapper for Common-maths UnivariateIntegrator

View File

@ -6,8 +6,8 @@
package space.kscience.kmath.commons.linear package space.kscience.kmath.commons.linear
import org.apache.commons.math3.linear.* import org.apache.commons.math3.linear.*
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.* import space.kscience.kmath.linear.*
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.nd.StructureFeature import space.kscience.kmath.nd.StructureFeature
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -13,11 +13,11 @@ import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunctionGradient
import org.apache.commons.math3.optim.nonlinear.scalar.gradient.NonLinearConjugateGradientOptimizer import org.apache.commons.math3.optim.nonlinear.scalar.gradient.NonLinearConjugateGradientOptimizer
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.expressions.SymbolIndexer import space.kscience.kmath.expressions.SymbolIndexer
import space.kscience.kmath.expressions.derivative import space.kscience.kmath.expressions.derivative
import space.kscience.kmath.expressions.withSymbols import space.kscience.kmath.expressions.withSymbols
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.misc.log import space.kscience.kmath.misc.log
import space.kscience.kmath.optimization.* import space.kscience.kmath.optimization.*
import kotlin.collections.set import kotlin.collections.set

View File

@ -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. * 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("DEPRECATION")
package space.kscience.kmath.commons.expressions package space.kscience.kmath.commons.expressions
import space.kscience.kmath.expressions.* import space.kscience.kmath.expressions.*
@ -15,10 +17,10 @@ import kotlin.test.assertFails
internal inline fun diff( internal inline fun diff(
order: Int, order: Int,
vararg parameters: Pair<Symbol, Double>, vararg parameters: Pair<Symbol, Double>,
block: DerivativeStructureField.() -> Unit, block: CmDsField.() -> Unit,
) { ) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
DerivativeStructureField(order, mapOf(*parameters)).run(block) CmDsField(order, mapOf(*parameters)).run(block)
} }
internal class AutoDiffTest { internal class AutoDiffTest {
@ -41,7 +43,7 @@ internal class AutoDiffTest {
@Test @Test
fun autoDifTest() { fun autoDifTest() {
val f = DerivativeStructureExpression { val f = CmDsExpression {
val x by binding val x by binding
val y by binding val y by binding
x.pow(2) + 2 * x * y + y.pow(2) + 1 x.pow(2) + 2 * x * y + y.pow(2) + 1

View File

@ -6,9 +6,9 @@
package space.kscience.kmath.commons.integration package space.kscience.kmath.commons.integration
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.integration.integrate import space.kscience.kmath.integration.integrate
import space.kscience.kmath.integration.value import space.kscience.kmath.integration.value
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.DoubleField.sin import space.kscience.kmath.operations.DoubleField.sin
import kotlin.math.PI import kotlin.math.PI
import kotlin.math.abs import kotlin.math.abs

View File

@ -6,22 +6,25 @@
package space.kscience.kmath.commons.optimization package space.kscience.kmath.commons.optimization
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import space.kscience.kmath.commons.expressions.DSProcessor import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.commons.expressions.DerivativeStructureExpression
import space.kscience.kmath.distributions.NormalDistribution import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.expressions.DSFieldExpression
import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.Symbol.Companion.x
import space.kscience.kmath.expressions.Symbol.Companion.y import space.kscience.kmath.expressions.Symbol.Companion.y
import space.kscience.kmath.expressions.chiSquaredExpression import space.kscience.kmath.expressions.autodiff
import space.kscience.kmath.expressions.symbol import space.kscience.kmath.expressions.symbol
import space.kscience.kmath.operations.DoubleBufferOps.Companion.map import space.kscience.kmath.operations.DoubleBufferOps.Companion.map
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.optimization.* import space.kscience.kmath.optimization.*
import space.kscience.kmath.random.RandomGenerator import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.stat.chiSquaredExpression
import space.kscience.kmath.structures.DoubleBuffer import space.kscience.kmath.structures.DoubleBuffer
import space.kscience.kmath.structures.asBuffer import space.kscience.kmath.structures.asBuffer
import kotlin.test.Test import kotlin.test.Test
@OptIn(UnstableKMathAPI::class)
internal class OptimizeTest { internal class OptimizeTest {
val normal = DerivativeStructureExpression { val normal = DSFieldExpression(DoubleField) {
exp(-bindSymbol(x).pow(2) / 2) + exp(-bindSymbol(y).pow(2) / 2) exp(-bindSymbol(x).pow(2) / 2) + exp(-bindSymbol(y).pow(2) / 2)
} }
@ -60,7 +63,7 @@ internal class OptimizeTest {
val yErr = DoubleBuffer(x.size) { sigma } val yErr = DoubleBuffer(x.size) { sigma }
val chi2 = DSProcessor.chiSquaredExpression( val chi2 = Double.autodiff.chiSquaredExpression(
x, y, yErr x, y, yErr
) { arg -> ) { arg ->
val cWithDefault = bindSymbolOrNull(c) ?: one val cWithDefault = bindSymbolOrNull(c) ?: one

View File

@ -8,7 +8,7 @@ Complex and hypercomplex number systems in KMath.
## Artifact: ## Artifact:
The Maven coordinates of this project are `space.kscience:kmath-complex:0.3.1-dev-1`. The Maven coordinates of this project are `space.kscience:kmath-complex:0.4.0-dev-1`.
**Gradle Groovy:** **Gradle Groovy:**
```groovy ```groovy
@ -18,7 +18,7 @@ repositories {
} }
dependencies { dependencies {
implementation 'space.kscience:kmath-complex:0.3.1-dev-1' implementation 'space.kscience:kmath-complex:0.4.0-dev-1'
} }
``` ```
**Gradle Kotlin DSL:** **Gradle Kotlin DSL:**
@ -29,6 +29,6 @@ repositories {
} }
dependencies { dependencies {
implementation("space.kscience:kmath-complex:0.3.1-dev-1") implementation("space.kscience:kmath-complex:0.4.0-dev-1")
} }
``` ```

View File

@ -3,15 +3,35 @@ plugins {
} }
kscience { kscience {
jvm()
js()
native() native()
}
kotlin.sourceSets { wasm{
commonMain { browser {
dependencies { testTask {
api(project(":kmath-core")) useKarma {
this.webpackConfig.experiments.add("topLevelAwait")
useChromeHeadless()
useConfigDirectory(project.projectDir.resolve("karma.config.d").resolve("wasm"))
}
}
} }
} }
wasmTest{
dependencies {
implementation(kotlin("test"))
}
}
dependencies {
api(projects.kmathCore)
}
testDependencies {
implementation(projects.testUtils)
}
} }
readme { readme {

View File

@ -5,10 +5,10 @@
package space.kscience.kmath.complex package space.kscience.kmath.complex
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.memory.MemoryReader import space.kscience.kmath.memory.MemoryReader
import space.kscience.kmath.memory.MemorySpec import space.kscience.kmath.memory.MemorySpec
import space.kscience.kmath.memory.MemoryWriter import space.kscience.kmath.memory.MemoryWriter
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.* import space.kscience.kmath.structures.*
import kotlin.math.* import kotlin.math.*
@ -80,6 +80,8 @@ public object ComplexField :
override fun add(left: Complex, right: Complex): Complex = Complex(left.re + right.re, left.im + right.im) override fun add(left: Complex, right: Complex): Complex = Complex(left.re + right.re, left.im + right.im)
// override fun multiply(a: Complex, k: Number): Complex = Complex(a.re * k.toDouble(), a.im * k.toDouble()) // override fun multiply(a: Complex, k: Number): Complex = Complex(a.re * k.toDouble(), a.im * k.toDouble())
// override fun Complex.minus(arg: Complex): Complex = Complex(re - arg.re, im - arg.im)
override fun multiply(left: Complex, right: Complex): Complex = override fun multiply(left: Complex, right: Complex): Complex =
Complex(left.re * right.re - left.im * right.im, left.re * right.im + left.im * right.re) Complex(left.re * right.re - left.im * right.im, left.re * right.im + left.im * right.re)

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.complex package space.kscience.kmath.complex
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.nd.* import space.kscience.kmath.nd.*
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -5,10 +5,10 @@
package space.kscience.kmath.complex package space.kscience.kmath.complex
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.memory.MemoryReader import space.kscience.kmath.memory.MemoryReader
import space.kscience.kmath.memory.MemorySpec import space.kscience.kmath.memory.MemorySpec
import space.kscience.kmath.memory.MemoryWriter import space.kscience.kmath.memory.MemoryWriter
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MemoryBuffer import space.kscience.kmath.structures.MemoryBuffer

View File

@ -15,7 +15,7 @@ performance calculations to code generation.
## Artifact: ## Artifact:
The Maven coordinates of this project are `space.kscience:kmath-core:0.3.1-dev-1`. The Maven coordinates of this project are `space.kscience:kmath-core:0.4.0-dev-1`.
**Gradle Groovy:** **Gradle Groovy:**
```groovy ```groovy
@ -25,7 +25,7 @@ repositories {
} }
dependencies { dependencies {
implementation 'space.kscience:kmath-core:0.3.1-dev-1' implementation 'space.kscience:kmath-core:0.4.0-dev-1'
} }
``` ```
**Gradle Kotlin DSL:** **Gradle Kotlin DSL:**
@ -36,6 +36,6 @@ repositories {
} }
dependencies { dependencies {
implementation("space.kscience:kmath-core:0.3.1-dev-1") implementation("space.kscience:kmath-core:0.4.0-dev-1")
} }
``` ```

View File

@ -3,10 +3,33 @@ plugins {
} }
kscience{ kscience{
jvm()
js()
native() native()
wasm{
browser {
testTask {
useKarma {
this.webpackConfig.experiments.add("topLevelAwait")
useChromeHeadless()
useConfigDirectory(project.projectDir.resolve("karma.config.d").resolve("wasm"))
}
}
}
}
wasmTest{
dependencies {
implementation(kotlin("test"))
}
}
dependencies { dependencies {
api(project(":kmath-memory")) api(projects.kmathMemory)
}
testDependencies {
implementation(projects.testUtils)
} }
} }

View File

@ -5,9 +5,9 @@
package space.kscience.kmath.data package space.kscience.kmath.data
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -5,9 +5,9 @@
package space.kscience.kmath.data package space.kscience.kmath.data
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import kotlin.math.max import kotlin.math.max

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.data package space.kscience.kmath.data
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.data package space.kscience.kmath.data
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.expressions.Symbol import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
/** /**

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.domains package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
@UnstableKMathAPI @UnstableKMathAPI
public abstract class Domain1D<T : Comparable<T>>(public val range: ClosedRange<T>) : Domain<T> { public abstract class Domain1D<T : Comparable<T>>(public val range: ClosedRange<T>) : Domain<T> {

View File

@ -4,7 +4,7 @@
*/ */
package space.kscience.kmath.domains package space.kscience.kmath.domains
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
/** /**
* n-dimensional volume * n-dimensional volume

View File

@ -4,8 +4,8 @@
*/ */
package space.kscience.kmath.domains package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.DoubleBuffer import space.kscience.kmath.structures.DoubleBuffer
import space.kscience.kmath.structures.indices import space.kscience.kmath.structures.indices

View File

@ -4,8 +4,8 @@
*/ */
package space.kscience.kmath.domains package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
@UnstableKMathAPI @UnstableKMathAPI
public class UnconstrainedDomain(override val dimension: Int) : DoubleDomain { public class UnconstrainedDomain(override val dimension: Int) : DoubleDomain {

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.expressions package space.kscience.kmath.expressions
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer
@ -80,7 +80,6 @@ public abstract class DSAlgebra<T, A : Ring<T>>(
public val algebra: A, public val algebra: A,
public val order: Int, public val order: Int,
bindings: Map<Symbol, T>, bindings: Map<Symbol, T>,
public val valueBufferFactory: MutableBufferFactory<T> = algebra.bufferFactory,
) : ExpressionAlgebra<T, DS<T, A>>, SymbolIndexer { ) : ExpressionAlgebra<T, DS<T, A>>, SymbolIndexer {
/** /**
@ -116,7 +115,6 @@ public abstract class DSAlgebra<T, A : Ring<T>>(
newCache[p][o] = DSCompiler( newCache[p][o] = DSCompiler(
algebra, algebra,
valueBufferFactory,
p, p,
o, o,
valueCompiler, valueCompiler,
@ -141,7 +139,7 @@ public abstract class DSAlgebra<T, A : Ring<T>>(
override val symbols: List<Symbol> = bindings.map { it.key } override val symbols: List<Symbol> = bindings.map { it.key }
private fun bufferForVariable(index: Int, value: T): Buffer<T> { private fun bufferForVariable(index: Int, value: T): Buffer<T> {
val buffer = valueBufferFactory(compiler.size) { algebra.zero } val buffer = algebra.bufferFactory(compiler.size) { algebra.zero }
buffer[0] = value buffer[0] = value
if (compiler.order > 0) { if (compiler.order > 0) {
// the derivative of the variable with respect to itself is 1. // the derivative of the variable with respect to itself is 1.
@ -207,7 +205,7 @@ public abstract class DSAlgebra<T, A : Ring<T>>(
} }
public override fun const(value: T): DS<T, A> { public override fun const(value: T): DS<T, A> {
val buffer = valueBufferFactory(compiler.size) { algebra.zero } val buffer = algebra.bufferFactory(compiler.size) { algebra.zero }
buffer[0] = value buffer[0] = value
return DS(buffer) return DS(buffer)
@ -245,11 +243,14 @@ public open class DSRing<T, A>(
algebra: A, algebra: A,
order: Int, order: Int,
bindings: Map<Symbol, T>, bindings: Map<Symbol, T>,
valueBufferFactory: MutableBufferFactory<T>, ) : DSAlgebra<T, A>(algebra, order, bindings),
) : DSAlgebra<T, A>(algebra, order, bindings, valueBufferFactory), Ring<DS<T, A>>,
Ring<DS<T, A>>, ScaleOperations<DS<T, A>>, ScaleOperations<DS<T, A>>,
NumericAlgebra<DS<T, A>>, NumericAlgebra<DS<T, A>>,
NumbersAddOps<DS<T, A>> where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> { NumbersAddOps<DS<T, A>>
where A : Ring<T>, A : NumericAlgebra<T>, A : ScaleOperations<T> {
public val elementBufferFactory: MutableBufferFactory<T> = algebra.bufferFactory
override fun bindSymbolOrNull(value: String): DSSymbol? = override fun bindSymbolOrNull(value: String): DSSymbol? =
super<DSAlgebra>.bindSymbolOrNull(value) super<DSAlgebra>.bindSymbolOrNull(value)
@ -261,14 +262,14 @@ public open class DSRing<T, A>(
*/ */
protected inline fun DS<T, A>.transformDataBuffer(block: A.(MutableBuffer<T>) -> Unit): DS<T, A> { protected inline fun DS<T, A>.transformDataBuffer(block: A.(MutableBuffer<T>) -> Unit): DS<T, A> {
require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" } require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" }
val newData = valueBufferFactory(compiler.size) { data[it] } val newData = elementBufferFactory(compiler.size) { data[it] }
algebra.block(newData) algebra.block(newData)
return DS(newData) return DS(newData)
} }
protected fun DS<T, A>.mapData(block: A.(T) -> T): DS<T, A> { protected fun DS<T, A>.mapData(block: A.(T) -> T): DS<T, A> {
require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" } require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" }
val newData: Buffer<T> = data.mapToBuffer(valueBufferFactory) { val newData: Buffer<T> = data.mapToBuffer(elementBufferFactory) {
algebra.block(it) algebra.block(it)
} }
return DS(newData) return DS(newData)
@ -276,7 +277,7 @@ public open class DSRing<T, A>(
protected fun DS<T, A>.mapDataIndexed(block: (Int, T) -> T): DS<T, A> { protected fun DS<T, A>.mapDataIndexed(block: (Int, T) -> T): DS<T, A> {
require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" } require(derivativeAlgebra == this@DSRing) { "All derivative operations should be done in the same algebra" }
val newData: Buffer<T> = data.mapIndexedToBuffer(valueBufferFactory, block) val newData: Buffer<T> = data.mapIndexedToBuffer(elementBufferFactory, block)
return DS(newData) return DS(newData)
} }
@ -329,22 +330,21 @@ public class DerivativeStructureRingExpression<T, A>(
public val function: DSRing<T, A>.() -> DS<T, A>, public val function: DSRing<T, A>.() -> DS<T, A>,
) : DifferentiableExpression<T> where A : Ring<T>, A : ScaleOperations<T>, A : NumericAlgebra<T> { ) : DifferentiableExpression<T> where A : Ring<T>, A : ScaleOperations<T>, A : NumericAlgebra<T> {
override operator fun invoke(arguments: Map<Symbol, T>): T = override operator fun invoke(arguments: Map<Symbol, T>): T =
DSRing(algebra, 0, arguments, elementBufferFactory).function().value DSRing(algebra, 0, arguments).function().value
override fun derivativeOrNull(symbols: List<Symbol>): Expression<T> = Expression { arguments -> override fun derivativeOrNull(symbols: List<Symbol>): Expression<T> = Expression { arguments ->
with( with(
DSRing( DSRing(
algebra, algebra,
symbols.size, symbols.size,
arguments, arguments
elementBufferFactory
) )
) { function().derivative(symbols) } ) { function().derivative(symbols) }
} }
} }
/** /**
* A field over commons-math [DerivativeStructure]. * A field over [DS].
* *
* @property order The derivation order. * @property order The derivation order.
* @param 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.
@ -354,8 +354,7 @@ public class DSField<T, A : ExtendedField<T>>(
algebra: A, algebra: A,
order: Int, order: Int,
bindings: Map<Symbol, T>, bindings: Map<Symbol, T>,
valueBufferFactory: MutableBufferFactory<T>, ) : DSRing<T, A>(algebra, order, bindings), ExtendedField<DS<T, A>> {
) : DSRing<T, A>(algebra, order, bindings, valueBufferFactory), ExtendedField<DS<T, A>> {
override fun number(value: Number): DS<T, A> = const(algebra.number(value)) override fun number(value: Number): DS<T, A> = const(algebra.number(value))
override fun divide(left: DS<T, A>, right: DS<T, A>): DS<T, A> = left.transformDataBuffer { result -> override fun divide(left: DS<T, A>, right: DS<T, A>): DS<T, A> = left.transformDataBuffer { result ->
@ -414,6 +413,7 @@ public class DSField<T, A : ExtendedField<T>>(
is Int -> arg.transformDataBuffer { result -> is Int -> arg.transformDataBuffer { result ->
compiler.pow(arg.data, 0, pow, result, 0) compiler.pow(arg.data, 0, pow, result, 0)
} }
else -> arg.transformDataBuffer { result -> else -> arg.transformDataBuffer { result ->
compiler.pow(arg.data, 0, pow.toDouble(), result, 0) compiler.pow(arg.data, 0, pow.toDouble(), result, 0)
} }
@ -439,18 +439,29 @@ public class DSField<T, A : ExtendedField<T>>(
@UnstableKMathAPI @UnstableKMathAPI
public class DSFieldExpression<T, A : ExtendedField<T>>( public class DSFieldExpression<T, A : ExtendedField<T>>(
public val algebra: A, public val algebra: A,
private val valueBufferFactory: MutableBufferFactory<T> = algebra.bufferFactory,
public val function: DSField<T, A>.() -> DS<T, A>, public val function: DSField<T, A>.() -> DS<T, A>,
) : DifferentiableExpression<T> { ) : DifferentiableExpression<T> {
override operator fun invoke(arguments: Map<Symbol, T>): T = override operator fun invoke(arguments: Map<Symbol, T>): T =
DSField(algebra, 0, arguments, valueBufferFactory).function().value DSField(algebra, 0, arguments).function().value
override fun derivativeOrNull(symbols: List<Symbol>): Expression<T> = Expression { arguments -> override fun derivativeOrNull(symbols: List<Symbol>): Expression<T> = Expression { arguments ->
DSField( DSField(
algebra, algebra,
symbols.size, symbols.size,
arguments, arguments,
valueBufferFactory,
).run { function().derivative(symbols) } ).run { function().derivative(symbols) }
} }
} }
@UnstableKMathAPI
public class DSFieldProcessor<T, A : ExtendedField<T>>(
public val algebra: A,
) : AutoDiffProcessor<T, DS<T, A>, DSField<T, A>> {
override fun differentiate(
function: DSField<T, A>.() -> DS<T, A>,
): DifferentiableExpression<T> = DSFieldExpression(algebra, function)
}
@UnstableKMathAPI
public val Double.Companion.autodiff: DSFieldProcessor<Double, DoubleField> get() = DSFieldProcessor(DoubleField)

View File

@ -9,7 +9,6 @@ package space.kscience.kmath.expressions
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableBufferFactory
import kotlin.math.min import kotlin.math.min
internal fun <T> MutableBuffer<T>.fill(element: T, fromIndex: Int = 0, toIndex: Int = size) { internal fun <T> MutableBuffer<T>.fill(element: T, fromIndex: Int = 0, toIndex: Int = size) {
@ -56,7 +55,6 @@ internal fun <T> MutableBuffer<T>.fill(element: T, fromIndex: Int = 0, toIndex:
*/ */
public class DSCompiler<T, out A : Algebra<T>> internal constructor( public class DSCompiler<T, out A : Algebra<T>> internal constructor(
public val algebra: A, public val algebra: A,
public val bufferFactory: MutableBufferFactory<T>,
public val freeParameters: Int, public val freeParameters: Int,
public val order: Int, public val order: Int,
valueCompiler: DSCompiler<T, A>?, valueCompiler: DSCompiler<T, A>?,

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.expressions package space.kscience.kmath.expressions
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.Algebra import space.kscience.kmath.operations.Algebra
import kotlin.jvm.JvmName import kotlin.jvm.JvmName
import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadOnlyProperty
@ -48,6 +48,10 @@ public interface DoubleExpression : Expression<Double> {
* @return the value. * @return the value.
*/ */
public operator fun invoke(arguments: DoubleArray): Double public operator fun invoke(arguments: DoubleArray): Double
public companion object{
internal val EMPTY_DOUBLE_ARRAY = DoubleArray(0)
}
} }
/** /**
@ -73,6 +77,10 @@ public interface IntExpression : Expression<Int> {
* @return the value. * @return the value.
*/ */
public operator fun invoke(arguments: IntArray): Int public operator fun invoke(arguments: IntArray): Int
public companion object{
internal val EMPTY_INT_ARRAY = IntArray(0)
}
} }
/** /**
@ -98,6 +106,10 @@ public interface LongExpression : Expression<Long> {
* @return the value. * @return the value.
*/ */
public operator fun invoke(arguments: LongArray): Long public operator fun invoke(arguments: LongArray): Long
public companion object{
internal val EMPTY_LONG_ARRAY = LongArray(0)
}
} }
/** /**
@ -145,7 +157,7 @@ public operator fun <T> Expression<T>.invoke(vararg pairs: Pair<String, T>): T =
} }
) )
private val EMPTY_DOUBLE_ARRAY = DoubleArray(0)
/** /**
* Calls this expression without providing any arguments. * Calls this expression without providing any arguments.
@ -153,7 +165,7 @@ private val EMPTY_DOUBLE_ARRAY = DoubleArray(0)
* @return a value. * @return a value.
*/ */
@UnstableKMathAPI @UnstableKMathAPI
public operator fun DoubleExpression.invoke(): Double = this(EMPTY_DOUBLE_ARRAY) public operator fun DoubleExpression.invoke(): Double = this(DoubleExpression.EMPTY_DOUBLE_ARRAY)
/** /**
* Calls this expression from arguments. * Calls this expression from arguments.
@ -164,15 +176,13 @@ public operator fun DoubleExpression.invoke(): Double = this(EMPTY_DOUBLE_ARRAY)
@UnstableKMathAPI @UnstableKMathAPI
public operator fun DoubleExpression.invoke(vararg arguments: Double): Double = this(arguments) public operator fun DoubleExpression.invoke(vararg arguments: Double): Double = this(arguments)
private val EMPTY_INT_ARRAY = IntArray(0)
/** /**
* Calls this expression without providing any arguments. * Calls this expression without providing any arguments.
* *
* @return a value. * @return a value.
*/ */
@UnstableKMathAPI @UnstableKMathAPI
public operator fun IntExpression.invoke(): Int = this(EMPTY_INT_ARRAY) public operator fun IntExpression.invoke(): Int = this(IntExpression.EMPTY_INT_ARRAY)
/** /**
* Calls this expression from arguments. * Calls this expression from arguments.
@ -183,15 +193,13 @@ public operator fun IntExpression.invoke(): Int = this(EMPTY_INT_ARRAY)
@UnstableKMathAPI @UnstableKMathAPI
public operator fun IntExpression.invoke(vararg arguments: Int): Int = this(arguments) public operator fun IntExpression.invoke(vararg arguments: Int): Int = this(arguments)
private val EMPTY_LONG_ARRAY = LongArray(0)
/** /**
* Calls this expression without providing any arguments. * Calls this expression without providing any arguments.
* *
* @return a value. * @return a value.
*/ */
@UnstableKMathAPI @UnstableKMathAPI
public operator fun LongExpression.invoke(): Long = this(EMPTY_LONG_ARRAY) public operator fun LongExpression.invoke(): Long = this(LongExpression.EMPTY_LONG_ARRAY)
/** /**
* Calls this expression from arguments. * Calls this expression from arguments.

View File

@ -0,0 +1,31 @@
/*
* Copyright 2018-2023 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.expressions
public class ExpressionWithDefault<T>(
private val origin: Expression<T>,
private val defaultArgs: Map<Symbol, T>,
) : Expression<T> {
override fun invoke(arguments: Map<Symbol, T>): T = origin.invoke(defaultArgs + arguments)
}
public fun <T> Expression<T>.withDefaultArgs(defaultArgs: Map<Symbol, T>): ExpressionWithDefault<T> =
ExpressionWithDefault(this, defaultArgs)
public class DiffExpressionWithDefault<T>(
private val origin: DifferentiableExpression<T>,
private val defaultArgs: Map<Symbol, T>,
) : DifferentiableExpression<T> {
override fun invoke(arguments: Map<Symbol, T>): T = origin.invoke(defaultArgs + arguments)
override fun derivativeOrNull(symbols: List<Symbol>): Expression<T>? =
origin.derivativeOrNull(symbols)?.withDefaultArgs(defaultArgs)
}
public fun <T> DifferentiableExpression<T>.withDefaultArgs(defaultArgs: Map<Symbol, T>): DiffExpressionWithDefault<T> =
DiffExpressionWithDefault(this, defaultArgs)

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.expressions package space.kscience.kmath.expressions
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
/** /**

View File

@ -0,0 +1,39 @@
/*
* Copyright 2018-2023 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.
*/
@file:OptIn(UnstableKMathAPI::class)
package space.kscience.kmath.expressions
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Matrix
import space.kscience.kmath.structures.getOrNull
public class NamedMatrix<T>(public val values: Matrix<T>, public val indexer: SymbolIndexer) : Matrix<T> by values {
public operator fun get(i: Symbol, j: Symbol): T = get(indexer.indexOf(i), indexer.indexOf(j))
public companion object {
@OptIn(PerformancePitfall::class)
public fun toStringWithSymbols(values: Matrix<*>, indexer: SymbolIndexer): String = buildString {
appendLine(indexer.symbols.joinToString(separator = "\t", prefix = "\t\t"))
indexer.symbols.forEach { i ->
append(i.identity + "\t")
values.rows.getOrNull(indexer.indexOf(i))?.let { row ->
indexer.symbols.forEach { j ->
append(row.getOrNull(indexer.indexOf(j)).toString())
append("\t")
}
appendLine()
}
}
}
}
}
public fun <T> Matrix<T>.named(indexer: SymbolIndexer): NamedMatrix<T> = NamedMatrix(this, indexer)
public fun <T> Matrix<T>.named(symbols: List<Symbol>): NamedMatrix<T> = named(SimpleSymbolIndexer(symbols))

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.expressions package space.kscience.kmath.expressions
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.asBuffer import space.kscience.kmath.structures.asBuffer
import kotlin.contracts.InvocationKind import kotlin.contracts.InvocationKind

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.expressions package space.kscience.kmath.expressions
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point import space.kscience.kmath.linear.Point
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.structures.BufferFactory import space.kscience.kmath.structures.BufferFactory
import space.kscience.kmath.structures.DoubleBuffer import space.kscience.kmath.structures.DoubleBuffer

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.nd.* import space.kscience.kmath.nd.*
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.nd.* import space.kscience.kmath.nd.*
import space.kscience.kmath.operations.DoubleBufferOps import space.kscience.kmath.operations.DoubleBufferOps
import space.kscience.kmath.operations.DoubleField import space.kscience.kmath.operations.DoubleField

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.nd.MutableStructure2D import space.kscience.kmath.nd.MutableStructure2D
import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.nd.StructureFeature import space.kscience.kmath.nd.StructureFeature

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.BufferAccessor2D import space.kscience.kmath.structures.BufferAccessor2D
import space.kscience.kmath.structures.DoubleBuffer import space.kscience.kmath.structures.DoubleBuffer

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.Ring import space.kscience.kmath.operations.Ring
import space.kscience.kmath.structures.BufferAccessor2D import space.kscience.kmath.structures.BufferAccessor2D
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.linear package space.kscience.kmath.linear
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.misc.FeatureSet import space.kscience.kmath.misc.FeatureSet
import space.kscience.kmath.misc.UnstableKMathAPI
import space.kscience.kmath.nd.StructureFeature import space.kscience.kmath.nd.StructureFeature
import space.kscience.kmath.operations.Ring import space.kscience.kmath.operations.Ring
import kotlin.reflect.KClass import kotlin.reflect.KClass

View File

@ -9,7 +9,7 @@ import kotlin.jvm.JvmInline
import kotlin.reflect.KClass import kotlin.reflect.KClass
/** /**
* A entity that contains a set of features defined by their types * An entity that contains a set of features defined by their types
*/ */
public interface Featured<F : Any> { public interface Featured<F : Any> {
public fun <T : F> getFeature(type: FeatureKey<T>): T? public fun <T : F> getFeature(type: FeatureKey<T>): T?

View File

@ -0,0 +1,22 @@
/*
* Copyright 2018-2023 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.misc
/**
* The same as [zipWithNext], but includes link between last and first element
*/
public inline fun <T, R> List<T>.zipWithNextCircular(transform: (a: T, b: T) -> R): List<R> {
if (isEmpty()) return emptyList()
return indices.map { i ->
if (i == size - 1) {
transform(last(), first())
} else {
transform(get(i), get(i + 1))
}
}
}
public fun <T> List<T>.zipWithNextCircular(): List<Pair<T,T>> = zipWithNextCircular { l, r -> l to r }

View File

@ -6,6 +6,7 @@
package space.kscience.kmath.misc package space.kscience.kmath.misc
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.VirtualBuffer import space.kscience.kmath.structures.VirtualBuffer

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import kotlin.reflect.KClass import kotlin.reflect.KClass

View File

@ -7,8 +7,8 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
public interface BufferAlgebraND<T, out A : Algebra<T>> : AlgebraND<T, A> { public interface BufferAlgebraND<T, out A : Algebra<T>> : AlgebraND<T, A> {

View File

@ -5,9 +5,11 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.BufferFactory
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableBufferFactory
/** /**
* Represents [StructureND] over [Buffer]. * Represents [StructureND] over [Buffer].
@ -29,6 +31,18 @@ public open class BufferND<out T>(
override fun toString(): String = StructureND.toString(this) override fun toString(): String = StructureND.toString(this)
} }
/**
* Create a generic [BufferND] using provided [initializer]
*/
public fun <T> BufferND(
shape: ShapeND,
bufferFactory: BufferFactory<T> = BufferFactory.boxing(),
initializer: (IntArray) -> T,
): BufferND<T> {
val strides = Strides(shape)
return BufferND(strides, bufferFactory(strides.linearSize) { initializer(strides.index(it)) })
}
///** ///**
// * Transform structure to a new structure using provided [BufferFactory] and optimizing if argument is [BufferND] // * Transform structure to a new structure using provided [BufferFactory] and optimizing if argument is [BufferND]
// */ // */
@ -67,6 +81,18 @@ public open class MutableBufferND<T>(
} }
} }
/**
* Create a generic [BufferND] using provided [initializer]
*/
public fun <T> MutableBufferND(
shape: ShapeND,
bufferFactory: MutableBufferFactory<T> = MutableBufferFactory.boxing(),
initializer: (IntArray) -> T,
): MutableBufferND<T> {
val strides = Strides(shape)
return MutableBufferND(strides, bufferFactory(strides.linearSize) { initializer(strides.index(it)) })
}
///** ///**
// * Transform structure to a new structure using provided [MutableBufferFactory] and optimizing if argument is [MutableBufferND] // * Transform structure to a new structure using provided [MutableBufferFactory] and optimizing if argument is [MutableBufferND]
// */ // */

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.* import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.DoubleBuffer import space.kscience.kmath.structures.DoubleBuffer
import kotlin.contracts.InvocationKind import kotlin.contracts.InvocationKind

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.IntRing import space.kscience.kmath.operations.IntRing
import space.kscience.kmath.operations.NumbersAddOps import space.kscience.kmath.operations.NumbersAddOps
import space.kscience.kmath.operations.bufferAlgebra import space.kscience.kmath.operations.bufferAlgebra

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
public class PermutedStructureND<T>( public class PermutedStructureND<T>(

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.UnsafeKMathAPI import space.kscience.kmath.UnsafeKMathAPI
import kotlin.jvm.JvmInline import kotlin.jvm.JvmInline
/** /**

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.operations.NumbersAddOps import space.kscience.kmath.operations.NumbersAddOps
import space.kscience.kmath.operations.ShortRing import space.kscience.kmath.operations.ShortRing
import space.kscience.kmath.operations.bufferAlgebra import space.kscience.kmath.operations.bufferAlgebra

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.operations.asSequence import space.kscience.kmath.operations.asSequence
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableListBuffer import space.kscience.kmath.structures.MutableListBuffer

View File

@ -5,10 +5,10 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.linear.LinearSpace import space.kscience.kmath.linear.LinearSpace
import space.kscience.kmath.misc.Feature import space.kscience.kmath.misc.Feature
import space.kscience.kmath.misc.Featured import space.kscience.kmath.misc.Featured
import space.kscience.kmath.misc.PerformancePitfall
import space.kscience.kmath.operations.Ring import space.kscience.kmath.operations.Ring
import space.kscience.kmath.operations.invoke import space.kscience.kmath.operations.invoke
import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.Buffer

View File

@ -5,8 +5,8 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.misc.UnstableKMathAPI import space.kscience.kmath.UnstableKMathAPI
public open class VirtualStructureND<T>( public open class VirtualStructureND<T>(
override val shape: ShapeND, override val shape: ShapeND,

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
@OptIn(PerformancePitfall::class) @OptIn(PerformancePitfall::class)
public fun <T> StructureND<T>.roll(axis: Int, step: Int = 1): StructureND<T> { public fun <T> StructureND<T>.roll(axis: Int, step: Int = 1): StructureND<T> {

View File

@ -5,7 +5,7 @@
package space.kscience.kmath.nd package space.kscience.kmath.nd
import space.kscience.kmath.misc.PerformancePitfall import space.kscience.kmath.PerformancePitfall
public interface StructureNDOfDouble : StructureND<Double> { public interface StructureNDOfDouble : StructureND<Double> {
/** /**

Some files were not shown because too many files have changed in this diff Show More