Compare commits

...

88 Commits
dev ... dev

Author SHA1 Message Date
0cd9a329ce fix geometric mean test 2025-05-26 15:41:41 +03:00
d2a3fd4fa2 Merge pull request 'STUD-13 add Quantile' () from qwazer/kmath:STUD-13-quantile into dev
Reviewed-on: 
Reviewed-by: Alexander Nozik <altavir@gmail.com>
2025-05-26 12:19:24 +03:00
4afd350a4e STUD-13 polish docs 2025-05-26 10:40:08 +03:00
202585d956 STUD-13 add Quantile
adapted from Julia implementation
2025-05-22 18:03:31 +03:00
f6f9984c8e Merge pull request 'fix geometric mean ComposableStatistic' () from qwazer/kmath:STUD-13-fix-composite-means into dev
Reviewed-on: 
Reviewed-by: Alexander Nozik <altavir@gmail.com>
2025-05-12 17:32:09 +03:00
3649d013cd fix geometric mean ComposableStatistic 2025-05-12 17:23:49 +03:00
b10caebe2a fix mean statistics composition 2025-05-11 19:36:02 +03:00
752a849cd3 Merge pull request 'STUD-13 add Variance and StandardDeviation statistics' () from qwazer/kmath:STUD-13 into dev
Reviewed-on: 
Reviewed-by: Alexander Nozik <altavir@gmail.com>
2025-05-10 20:40:41 +03:00
2535d4536e STUD-13 add Variance and StandardDeviation statistics 2025-05-09 16:07:41 +03:00
4464b72e45 STUD-13. Improve numerical stability of mean statistic algorithm in method computeIntermediate 2025-05-06 16:11:19 +03:00
ce453129f0 Merge pull request 'STUD-13. Improve numerical stability of mean statistic algorithm' () from qwazer/kmath:STUD-13 into dev
Reviewed-on: 
Reviewed-by: Alexander Nozik <altavir@gmail.com>
2025-05-05 15:57:20 +03:00
d43ce15b99 STUD-13. Improve numerical stability of mean statistic algorithm
Replace naive summation that prone to floating-point errors (loss of precision) by Welford’s Online Algorithm which updates mean incrementally and more numerically stable.
 The cons is slightly higher computational overhead.
2025-05-05 15:34:49 +03:00
288ec467e6 Merge pull request 'add Geometric Mean statistic' () from qwazer/kmath:STUD-13 into dev
Reviewed-on: 
2025-04-28 10:38:08 +03:00
59fbe5165f add Geometric Mean statistic 2025-04-23 16:26:48 +03:00
2d37a5255f Merge remote-tracking branch 'github/dev' into dev 2025-04-23 09:13:46 +03:00
SPC-code
5bbff7e8ad
Merge pull request from qwazer/STUD-13
Add "min" and "max" statistics implemented as ExtremeValueStatistic
2025-04-23 09:11:20 +03:00
7ac9794c0c Add Min/Max statistics
- Remove ExtremeValueStatistic
- Add benchmark
2025-04-17 16:26:21 +03:00
e41bbe711c fix global scope pollution 2025-04-16 15:52:16 +03:00
57e4819430 Add "min" and "max" statistics implemented as ExtremeValueStatistic
- Add ExtremeValueStatistic
- Add statistics docs
2025-04-15 19:53:40 +03:00
e213db67da Add Float64Vector3D factory function 2025-04-07 12:27:23 +03:00
f2fef6cb5d Add benchmarks to Readme 2025-03-26 11:07:07 +03:00
ef31e35603 Add attribute builder accessors for fits 2025-03-16 15:54:41 +03:00
a756490d20 Fix package for context line extensions 2025-03-10 10:13:04 +03:00
9d3d08e66b Update dokka configuration 2025-03-10 09:26:13 +03:00
SPC-code
8deaf1470a
Update pages.yml 2025-03-10 07:46:52 +03:00
e11968f8d2 Remove ND4j 2025-03-07 21:03:57 +03:00
656d874a65 fix dokka 2025-03-07 21:03:44 +03:00
4277f480d8 Remove nd4j dependency from benchmarks 2025-01-27 14:46:27 +03:00
2a3cf190b1 Upgrade tensorflow version 2025-01-27 13:13:47 +03:00
06271fb889 0.4.2 release 2025-01-27 09:28:57 +03:00
bdc9d35512 Add sparse matrix builder 2025-01-27 09:26:48 +03:00
b230abefc8 Merge remote-tracking branch 'refs/remotes/github/dev' into dev 2025-01-27 09:26:04 +03:00
c47fa7bdba Merge remote-tracking branch 'github/master' into dev 2025-01-27 09:23:37 +03:00
c70a7c5128 Add sparse matrix builder 2025-01-26 22:17:36 +03:00
SPC-code
720378f7fc
Merge pull request from SciProgCentre/commandertvis/423-fix
Move ND4J dependencies to libs.versions.toml, API dump in kmath-nd4j
2025-01-22 09:51:48 +03:00
Iaroslav Postovalov
f9f6b51772
Move ND4J dependencies to libs.versions.toml, API dump in kmath-nd4j 2025-01-22 01:14:05 +01:00
676cf5ff3b Ojalgo conversion bug 2025-01-17 14:54:09 +03:00
5538102ad9 Ojalgo conversion bug 2025-01-17 14:52:47 +03:00
SPC-code
345f4f2acf
Update pages.yml 2025-01-12 15:12:02 +03:00
SPC-code
8a73406d2c
Update pages.yml 2025-01-12 14:20:22 +03:00
ead9b95ae8 Merge remote-tracking branch 'github/master' 2025-01-12 14:09:55 +03:00
c9d1de41b1 Update changelog and Readme for 0.4.1 2025-01-12 13:40:41 +03:00
b2b64f35d0 Change EJML implementation to match CM and Ojalgo 2025-01-12 13:04:46 +03:00
1ec3d1adb9 add ojalgo_license 2025-01-12 11:45:49 +03:00
d8af4e36ed Add ojalgo module 2025-01-12 11:40:51 +03:00
da9608128b Move attributes to separate project 2025-01-12 11:40:07 +03:00
5c8e50c3df Move attributes to separate project 2025-01-07 22:30:25 +03:00
117b253d4d Merge remote-tracking branch 'github/dev' into dev 2024-12-24 13:57:12 +03:00
6170f0376e Fix EJML to properly treat vectors as columns 2024-12-24 13:44:29 +03:00
cd46773f43 Fix EJML to properly treat vectors as columns 2024-12-24 13:43:41 +03:00
SPC-code
b518969f02
Update build.yml 2024-12-24 13:02:47 +03:00
3aa387c544 Fix EJML to properly treat vectors as columns 2024-12-24 12:58:00 +03:00
19139c0d4e Fix EJML to properly treat vectors as columns 2024-12-24 12:57:08 +03:00
b4b8f30b2a Remove hardcoded reference to SymbolIndexer in asm 2024-12-24 12:51:15 +03:00
b9f413b5ce Revert SymbolIndexer package to make ASM builders work. 2024-12-24 12:26:01 +03:00
43e407e11a Merge changes for Kotlin 2.1.0 2024-12-24 10:51:55 +03:00
a6fcfdebd1 Merge remote-tracking branch 'spc/dev' into dev 2024-12-24 10:44:42 +03:00
8f55d89daf EAP 2.1.20 2024-12-21 14:02:54 +03:00
c475c43744 Named buffers and named module 2024-12-14 11:50:46 +03:00
7064546f83 add dokka multimodule 2024-10-04 14:55:15 +03:00
8a453bf0b9 Merge branch 'dev' into beta/kotlin-2.0.20
# Conflicts:
#	benchmarks/build.gradle.kts
#	gradle.properties
#	kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/base64/base64.kt
2024-09-22 16:46:45 +03:00
ab16bd16ac Fix benchmark results script 2024-08-26 13:37:49 +03:00
222cdc2c14 Add unstable marker to eigenvalue decomposition 2024-08-21 12:06:00 +03:00
6c1a5e62bf Remove buildSrc 2024-08-21 11:56:05 +03:00
1619a49017 Add proper test for symmetric matrices eigenValueDecomposition 2024-08-18 22:45:33 +03:00
b818a8981f Eigenvalue decomposition API
Cosmetic change Double -> Float64
2024-08-17 21:11:13 +03:00
91513a1629 Reimplement random-forking chain 2024-08-14 19:20:05 +03:00
2becee7f59 Reimplement random-forking chain 2024-08-09 22:14:24 +03:00
6619db3f45 Reimplement random-forging chain 2024-08-09 10:22:37 +03:00
48d0ee8126 Add Metropolis-Hastings sampler.
Minor fixes.
2024-08-04 21:26:51 +03:00
57d1cd8c87 Add Metropolis-Hastings sampler.
Minor fixes.
2024-08-04 15:01:47 +03:00
SPC-code
e0997ccf9c
Merge pull request from Vasilev-Ilya/STUD-7_metropolis_hastings_sampler
Draft: STUD-7: Metropolis-Hastings sampler implementation
2024-08-03 21:35:29 +03:00
0a90d2e8c9 Kotlin 2.0.20-Beta2 2024-07-25 10:09:26 +03:00
3e8f44166c add Attributes minus 2024-07-07 11:14:11 +03:00
6e24b563b2 optimize attributes plus 2024-07-07 11:06:20 +03:00
2d309e050b Merge branch 'refs/heads/beta/kotlin2.0.0' into dev 2024-07-07 11:03:48 +03:00
07aeec6dfb beta-2.0.20 2024-07-07 11:02:49 +03:00
c585c59552 2.0.0 2024-06-04 10:31:42 +03:00
vasilev.ilya
3417d8cdc1 Minor edits. Tests added. | STUD-7 2024-05-20 01:12:27 +03:00
c418607bf6 2.0.0-RC2 2024-04-30 19:41:34 +03:00
dbc5488eb2 Minor edits. Tests added. | STUD-7 2024-04-24 23:29:14 +03:00
d0d250c67f MHS first implementation | STUD-7 2024-04-22 22:01:15 +03:00
9518f16348 Merge branch 'refs/heads/dev' into beta/kotlin2.0.0
# Conflicts:
#	gradle.properties
2024-04-20 09:22:19 +03:00
SPC-code
d1d1476cae
Merge pull request from SciProgCentre/dev
0.4.0
2024-04-15 20:20:54 +03:00
0af8147be6 Remove unnecessary internal dependencies 2024-03-26 09:58:50 +03:00
bd9430bab4 Merge branch 'dev' into beta/kotlin2.0.0
# Conflicts:
#	gradle.properties
#	kmath-histograms/build.gradle.kts
#	kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Histogram.kt
2024-03-19 09:15:55 +03:00
9f9c4a347b Fix all issues for 2.0.0 2024-01-28 18:35:47 +03:00
9e88bff668 Kotlin 2.0.0-Beta1 2023-11-22 09:22:28 +03:00
301 changed files with 5079 additions and 3174 deletions
.github/workflows
.space.kts
.space
CHANGELOG.mdREADME.md
attributes-kt
benchmarks
build.gradle.kts
buildSrc
docs
examples
gradle.properties
gradle
kmath-ast
README.mdbuild.gradle.kts
src
commonTest/kotlin/space/kscience/kmath/ast
jsMain/kotlin/space/kscience/kmath
jsTest/kotlin/space/kscience/kmath/ast
jvmMain/kotlin/space/kscience/kmath/asm/internal
jvmTest/kotlin/space/kscience/kmath/ast
kmath-commons
README.mdbuild.gradle.kts
src
jvmMain/kotlin/space/kscience/kmath/commons
jvmTest/kotlin/space/kscience/kmath/commons/optimization
kmath-complex
README.md
src/commonMain/kotlin/space/kscience/kmath/complex
kmath-core

@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3.5.1
with:
java-version: '11'
java-version: '17'
distribution: 'liberica'
cache: 'gradle'
- name: Gradle Wrapper Validation

@ -7,25 +7,25 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
- uses: actions/checkout@v3.0.0
- uses: actions/setup-java@v3.0.0
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: 11
java-version: 17
distribution: liberica
- name: Cache konan
uses: actions/cache@v3.0.1
uses: actions/cache@v3
with:
path: ~/.konan
key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle.kts') }}
restore-keys: |
${{ runner.os }}-gradle-
- uses: gradle/gradle-build-action@v2.4.2
- uses: gradle/gradle-build-action@v3
with:
arguments: dokkaHtmlMultiModule --no-parallel
- uses: JamesIves/github-pages-deploy-action@v4.3.0
arguments: dokkaGenerate --no-parallel
- uses: JamesIves/github-pages-deploy-action@v4
with:
branch: gh-pages
folder: build/dokka/htmlMultiModule
folder: build/dokka/html

@ -1,50 +0,0 @@
name: Gradle publish
on:
workflow_dispatch:
release:
types: [ created ]
jobs:
publish:
environment:
name: publish
strategy:
matrix:
os: [ macOS-latest, windows-latest ]
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v3.0.0
- uses: actions/setup-java@v3.10.0
with:
java-version: 11
distribution: liberica
- name: Cache konan
uses: actions/cache@v3.0.1
with:
path: ~/.konan
key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle.kts') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Publish Windows Artifacts
if: matrix.os == 'windows-latest'
uses: gradle/gradle-build-action@v2.4.2
with:
arguments: |
publishAllPublicationsToSpaceRepository
-Ppublishing.targets=all
-Ppublishing.space.user=${{ secrets.SPACE_APP_ID }}
-Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }}
- name: Publish Mac Artifacts
if: matrix.os == 'macOS-latest'
uses: gradle/gradle-build-action@v2.4.2
with:
arguments: |
publishMacosX64PublicationToSpaceRepository
publishMacosArm64PublicationToSpaceRepository
publishIosX64PublicationToSpaceRepository
publishIosArm64PublicationToSpaceRepository
publishIosSimulatorArm64PublicationToSpaceRepository
-Ppublishing.targets=all
-Ppublishing.space.user=${{ secrets.SPACE_APP_ID }}
-Ppublishing.space.token=${{ secrets.SPACE_APP_SECRET }}

@ -1,48 +0,0 @@
import kotlin.io.path.readText
val projectName = "kmath"
job("Build") {
//Perform only jvm tests
gradlew("spc.registry.jetbrains.space/p/sci/containers/kotlin-ci:1.0.3", "test", "jvmTest")
}
job("Publish") {
startOn {
gitPush { enabled = false }
}
container("spc.registry.jetbrains.space/p/sci/containers/kotlin-ci:1.0.3") {
env["SPACE_USER"] = "{{ project:space_user }}"
env["SPACE_TOKEN"] = "{{ project:space_token }}"
kotlinScript { api ->
val spaceUser = System.getenv("SPACE_USER")
val spaceToken = System.getenv("SPACE_TOKEN")
// write the version to the build directory
api.gradlew("version")
//read the version from build file
val version = java.nio.file.Path.of("build/project-version.txt").readText()
val revisionSuffix = if (version.endsWith("SNAPSHOT")) {
"-" + api.gitRevision().take(7)
} else {
""
}
api.space().projects.automation.deployments.start(
project = api.projectIdentifier(),
targetIdentifier = TargetIdentifier.Key(projectName),
version = version + revisionSuffix,
// automatically update deployment status based on the status of a job
syncWithAutomationJob = true
)
api.gradlew(
"publishAllPublicationsToSpaceRepository",
"-Ppublishing.space.user=\"$spaceUser\"",
"-Ppublishing.space.token=\"$spaceToken\"",
)
}
}
}

@ -3,8 +3,10 @@
## Unreleased
### Added
- Fit accessors with Attribute
### Changed
- Upgrade tensorflow version to 1.0.0
### Deprecated
@ -14,7 +16,36 @@
### Security
## 0.4.0-dev-3 - 2024-02-18
## 0.4.2 - 2025-01-27
### Added
- Convenient matrix builders for rows, columns, vstacks and hstacks
- Sparse matrix builder
### Fixed
- Ojalgo conversion bug which made all converted matrices be zero.
## 0.4.1 - 2025-01-12
### Added
- Metropolis-Hastings sampler
- Ojalgo `LinearSpace` implementation.
### Changed
- attributes-kt moved to a separate project, and the version used is 0.3.0
- Kotlin 2.1. Now use cross-compilation to deploy macOS targets.
- Changed `origin` to `cmMatrix` in kmath-commons to avoid property name clash. Expose bidirectional conversion in `CMLinearSpace`
- (BREAKING CHANGE) Changed implementations in `kmath-ejml` to match CM and ojalgo style. Specifically, provide bidirectional conversion for library types.
### Fixed
- (BREAKING CHANGE) Fix EJML to properly treat vectors as columns
## 0.4.0 - 2024-02-18
### Added
@ -200,7 +231,7 @@
- Full autodiff refactoring based on `Symbol`
- `kmath-prob` renamed to `kmath-stat`
- Grid generators moved to `kmath-for-real`
- Use `Point<Double>` instead of specialized type in `kmath-for-real`
- Use `Point<Float64>` instead of specialized type in `kmath-for-real`
- Optimized dot product for buffer matrices moved to `kmath-for-real`
- EjmlMatrix context is an object
- Matrix LUP `inverse` renamed to `inverseWithLup`

@ -2,7 +2,6 @@
[![DOI](https://zenodo.org/badge/129486382.svg)](https://zenodo.org/badge/latestdoi/129486382)
![Gradle build](https://github.com/SciProgCentre/kmath/workflows/Gradle%20build/badge.svg)
[![Maven Central](https://img.shields.io/maven-central/v/space.kscience/kmath-core.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22space.kscience%22)
[![Space](https://img.shields.io/badge/dynamic/xml?color=orange&label=Space&query=//metadata/versioning/latest&url=https%3A%2F%2Fmaven.pkg.jetbrains.space%2Fmipt-npm%2Fp%2Fsci%2Fmaven%2Fspace%2Fkscience%2Fkmath-core%2Fmaven-metadata.xml)](https://maven.pkg.jetbrains.space/mipt-npm/p/sci/maven/space/kscience/)
# KMath
@ -57,11 +56,6 @@ module definitions below. The module stability could have the following levels:
## Modules
### [attributes-kt](attributes-kt)
> An API and basic implementation for arranging objects in a continuous memory block.
>
> **Maturity**: DEVELOPMENT
### [benchmarks](benchmarks)
>
> **Maturity**: EXPERIMENTAL
@ -107,8 +101,6 @@ module definitions below. The module stability could have the following levels:
> - [linear](kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Basic linear algebra operations (sums, products, etc.), backed by the `Space` API. Advanced linear algebra operations like matrix inversion and LU decomposition.
> - [buffers](kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/Buffers.kt) : One-dimensional structure
> - [expressions](kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions) : By writing a single mathematical expression once, users will be able to apply different types of
objects to the expression by providing a context. Expressions can be used for a wide variety of purposes from high
performance calculations to code generation.
> - [domains](kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
> - [autodiff](kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic differentiation
> - [Parallel linear algebra](kmath-core/#) : Parallel implementation for `LinearAlgebra`
@ -167,15 +159,6 @@ One can still use generic algebras though.
>
> **Maturity**: PROTOTYPE
### [kmath-jafama](kmath-jafama)
> Jafama integration module
>
> **Maturity**: DEPRECATED
>
> **Features:**
> - [jafama-double](kmath-jafama/src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations based on Jafama
### [kmath-jupyter](kmath-jupyter)
>
> **Maturity**: PROTOTYPE
@ -211,6 +194,11 @@ One can still use generic algebras though.
> - [nd4jarrayfields](kmath-nd4j/#) : Fields over Nd4jArrayStructure of Float and Double
### [kmath-ojalgo](kmath-ojalgo)
> Ojalgo bindings for kmath
>
> **Maturity**: PROTOTYPE
### [kmath-optimization](kmath-optimization)
>
> **Maturity**: EXPERIMENTAL

@ -1,21 +0,0 @@
# Module attributes-kt
## Usage
## Artifact:
The Maven coordinates of this project are `space.kscience:attributes-kt:0.1.0`.
**Gradle Kotlin DSL:**
```kotlin
repositories {
maven("https://repo.kotlin.link")
mavenCentral()
}
dependencies {
implementation("space.kscience:attributes-kt:0.1.0")
}
```

@ -1,104 +0,0 @@
public abstract interface class space/kscience/attributes/Attribute {
}
public abstract interface class space/kscience/attributes/AttributeContainer {
public abstract fun getAttributes ()Lspace/kscience/attributes/Attributes;
}
public abstract interface class space/kscience/attributes/AttributeScope {
}
public abstract interface class space/kscience/attributes/AttributeWithDefault : space/kscience/attributes/Attribute {
public abstract fun getDefault ()Ljava/lang/Object;
}
public abstract interface class space/kscience/attributes/Attributes {
public static final field Companion Lspace/kscience/attributes/Attributes$Companion;
public abstract fun equals (Ljava/lang/Object;)Z
public fun get (Lspace/kscience/attributes/Attribute;)Ljava/lang/Object;
public abstract fun getContent ()Ljava/util/Map;
public fun getKeys ()Ljava/util/Set;
public abstract fun hashCode ()I
public abstract fun toString ()Ljava/lang/String;
}
public final class space/kscience/attributes/Attributes$Companion {
public final fun equals (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/Attributes;)Z
public final fun getEMPTY ()Lspace/kscience/attributes/Attributes;
}
public final class space/kscience/attributes/AttributesBuilder : space/kscience/attributes/Attributes {
public final fun add (Lspace/kscience/attributes/SetAttribute;Ljava/lang/Object;)V
public final fun build ()Lspace/kscience/attributes/Attributes;
public fun equals (Ljava/lang/Object;)Z
public fun getContent ()Ljava/util/Map;
public fun hashCode ()I
public final fun invoke (Lspace/kscience/attributes/Attribute;Ljava/lang/Object;)V
public final fun put (Lspace/kscience/attributes/Attribute;Ljava/lang/Object;)V
public final fun putAll (Lspace/kscience/attributes/Attributes;)V
public final fun remove (Lspace/kscience/attributes/SetAttribute;Ljava/lang/Object;)V
public final fun set (Lspace/kscience/attributes/Attribute;Ljava/lang/Object;)V
public fun toString ()Ljava/lang/String;
}
public final class space/kscience/attributes/AttributesBuilderKt {
public static final fun Attributes (Lkotlin/jvm/functions/Function1;)Lspace/kscience/attributes/Attributes;
}
public final class space/kscience/attributes/AttributesKt {
public static final fun Attributes (Lspace/kscience/attributes/Attribute;)Lspace/kscience/attributes/Attributes;
public static final fun Attributes (Lspace/kscience/attributes/Attribute;Ljava/lang/Object;)Lspace/kscience/attributes/Attributes;
public static final fun getOrDefault (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/AttributeWithDefault;)Ljava/lang/Object;
public static final fun isEmpty (Lspace/kscience/attributes/Attributes;)Z
public static final fun modified (Lspace/kscience/attributes/Attributes;Lkotlin/jvm/functions/Function1;)Lspace/kscience/attributes/Attributes;
public static final fun plus (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/Attributes;)Lspace/kscience/attributes/Attributes;
public static final fun withAttribute (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/Attribute;)Lspace/kscience/attributes/Attributes;
public static final fun withAttribute (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/Attribute;Ljava/lang/Object;)Lspace/kscience/attributes/Attributes;
public static final fun withAttributeElement (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/SetAttribute;Ljava/lang/Object;)Lspace/kscience/attributes/Attributes;
public static final fun withoutAttribute (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/Attribute;)Lspace/kscience/attributes/Attributes;
public static final fun withoutAttributeElement (Lspace/kscience/attributes/Attributes;Lspace/kscience/attributes/SetAttribute;Ljava/lang/Object;)Lspace/kscience/attributes/Attributes;
}
public abstract interface class space/kscience/attributes/FlagAttribute : space/kscience/attributes/Attribute {
}
public abstract class space/kscience/attributes/PolymorphicAttribute : space/kscience/attributes/Attribute {
public synthetic fun <init> (Lkotlin/reflect/KType;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun equals (Ljava/lang/Object;)Z
public final fun getType-V0oMfBY ()Lkotlin/reflect/KType;
public fun hashCode ()I
}
public final class space/kscience/attributes/PolymorphicAttributeKt {
public static final fun get (Lspace/kscience/attributes/Attributes;Lkotlin/jvm/functions/Function0;)Ljava/lang/Object;
public static final fun set (Lspace/kscience/attributes/AttributesBuilder;Lkotlin/jvm/functions/Function0;Ljava/lang/Object;)V
}
public final class space/kscience/attributes/SafeType {
public static final synthetic fun box-impl (Lkotlin/reflect/KType;)Lspace/kscience/attributes/SafeType;
public static fun constructor-impl (Lkotlin/reflect/KType;)Lkotlin/reflect/KType;
public fun equals (Ljava/lang/Object;)Z
public static fun equals-impl (Lkotlin/reflect/KType;Ljava/lang/Object;)Z
public static final fun equals-impl0 (Lkotlin/reflect/KType;Lkotlin/reflect/KType;)Z
public final fun getKType ()Lkotlin/reflect/KType;
public fun hashCode ()I
public static fun hashCode-impl (Lkotlin/reflect/KType;)I
public fun toString ()Ljava/lang/String;
public static fun toString-impl (Lkotlin/reflect/KType;)Ljava/lang/String;
public final synthetic fun unbox-impl ()Lkotlin/reflect/KType;
}
public final class space/kscience/attributes/SafeTypeKt {
public static final fun getKClass-X0YbwmU (Lkotlin/reflect/KType;)Lkotlin/reflect/KClass;
}
public abstract interface class space/kscience/attributes/SetAttribute : space/kscience/attributes/Attribute {
}
public abstract interface annotation class space/kscience/attributes/UnstableAttributesAPI : java/lang/annotation/Annotation {
}
public abstract interface class space/kscience/attributes/WithType {
public abstract fun getType-V0oMfBY ()Lkotlin/reflect/KType;
}

@ -1,20 +0,0 @@
plugins {
id("space.kscience.gradle.mpp")
`maven-publish`
}
version = rootProject.extra.get("attributesVersion").toString()
kscience {
jvm()
js()
native()
wasm()
}
readme {
maturity = space.kscience.gradle.Maturity.DEVELOPMENT
description = """
An API and basic implementation for arranging objects in a continuous memory block.
""".trimIndent()
}

@ -1,29 +0,0 @@
/*
* 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.attributes
/**
* A marker interface for an attribute. Attributes are used as keys to access contents of type [T] in the container.
*/
public interface Attribute<T>
/**
* An attribute that could be either present or absent
*/
public interface FlagAttribute : Attribute<Unit>
/**
* An attribute with a default value
*/
public interface AttributeWithDefault<T> : Attribute<T> {
public val default: T
}
/**
* Attribute containing a set of values
*/
public interface SetAttribute<V> : Attribute<Set<V>>

@ -1,20 +0,0 @@
/*
* 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.attributes
/**
* A container for [Attributes]
*/
public interface AttributeContainer {
public val attributes: Attributes
}
/**
* A scope, where attribute keys could be resolved.
* [O] is used only to resolve types in compile-time.
*/
public interface AttributeScope<O>

@ -1,143 +0,0 @@
/*
* 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.attributes
/**
* A set of attributes. The implementation must guarantee that [content] keys correspond to their value types.
*/
public interface Attributes {
/**
* Raw content for this [Attributes]
*/
public val content: Map<out Attribute<*>, Any?>
/**
* Attribute keys contained in this [Attributes]
*/
public val keys: Set<Attribute<*>> get() = content.keys
/**
* Provide an attribute value. Return null if attribute is not present or if its value is null.
*/
@Suppress("UNCHECKED_CAST")
public operator fun <T> get(attribute: Attribute<T>): T? = content[attribute] as? T
override fun toString(): String
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
public companion object {
public val EMPTY: Attributes = object : Attributes {
override val content: Map<out Attribute<*>, Any?> get() = emptyMap()
override fun toString(): String = "Attributes.EMPTY"
override fun equals(other: Any?): Boolean = (other as? Attributes)?.isEmpty() ?: false
override fun hashCode(): Int = Unit.hashCode()
}
public fun equals(a1: Attributes, a2: Attributes): Boolean =
a1.keys == a2.keys && a1.keys.all { a1[it] == a2[it] }
}
}
internal class MapAttributes(override val content: Map<out Attribute<*>, Any?>) : Attributes {
override fun toString(): String = "Attributes(value=${content.entries})"
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
override fun hashCode(): Int = content.hashCode()
}
public fun Attributes.isEmpty(): Boolean = keys.isEmpty()
/**
* Get attribute value or default
*/
public fun <T> Attributes.getOrDefault(attribute: AttributeWithDefault<T>): T = get(attribute) ?: attribute.default
/**
* Check if there is an attribute that matches given key by type and adheres to [predicate].
*/
@Suppress("UNCHECKED_CAST")
public inline fun <T, reified A : Attribute<T>> Attributes.hasAny(predicate: (value: T) -> Boolean): Boolean =
content.any { (mapKey, mapValue) -> mapKey is A && predicate(mapValue as T) }
/**
* Check if there is an attribute of given type (subtypes included)
*/
public inline fun <reified A : Attribute<*>> Attributes.hasAny(): Boolean =
content.any { (mapKey, _) -> mapKey is A }
/**
* Check if [Attributes] contains a flag. Multiple keys that are instances of a flag could be present
*/
public inline fun <reified A : FlagAttribute> Attributes.hasFlag(): Boolean =
content.keys.any { it is A }
/**
* Create [Attributes] with an added or replaced attribute key.
*/
public fun <T, A : Attribute<T>> Attributes.withAttribute(
attribute: A,
attrValue: T,
): Attributes = MapAttributes(content + (attribute to attrValue))
public fun <A : Attribute<Unit>> Attributes.withAttribute(attribute: A): Attributes =
withAttribute(attribute, Unit)
/**
* Create a new [Attributes] by modifying the current one
*/
public fun <O> Attributes.modified(block: AttributesBuilder<O>.() -> Unit): Attributes = Attributes<O> {
putAll(this@modified)
block()
}
/**
* Create new [Attributes] by removing [attribute] key
*/
public fun Attributes.withoutAttribute(attribute: Attribute<*>): Attributes = MapAttributes(content.minus(attribute))
/**
* Add an element to a [SetAttribute]
*/
public fun <T, A : SetAttribute<T>> Attributes.withAttributeElement(
attribute: A,
attrValue: T,
): Attributes {
val currentSet: Set<T> = get(attribute) ?: emptySet()
return MapAttributes(
content + (attribute to (currentSet + attrValue))
)
}
/**
* Remove an element from [SetAttribute]
*/
public fun <T, A : SetAttribute<T>> Attributes.withoutAttributeElement(
attribute: A,
attrValue: T,
): Attributes {
val currentSet: Set<T> = get(attribute) ?: emptySet()
return MapAttributes(content + (attribute to (currentSet - attrValue)))
}
/**
* Create [Attributes] with a single key
*/
public fun <T, A : Attribute<T>> Attributes(
attribute: A,
attrValue: T,
): Attributes = MapAttributes(mapOf(attribute to attrValue))
/**
* Create Attributes with a single [Unit] valued attribute
*/
public fun <A : Attribute<Unit>> Attributes(
attribute: A,
): Attributes = MapAttributes(mapOf(attribute to Unit))
public operator fun Attributes.plus(other: Attributes): Attributes = MapAttributes(content + other.content)

@ -1,68 +0,0 @@
/*
* 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.attributes
/**
* A builder for [Attributes].
* The builder is not thread safe
*
* @param O type marker of an owner object, for which these attributes are made
*/
public class AttributesBuilder<out O> internal constructor() : Attributes {
private val map = mutableMapOf<Attribute<*>, Any?>()
override fun toString(): String = "Attributes(value=${map.entries})"
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
override fun hashCode(): Int = map.hashCode()
override val content: Map<out Attribute<*>, Any?> get() = map
public operator fun <T> set(attribute: Attribute<T>, value: T?) {
if (value == null) {
map.remove(attribute)
} else {
map[attribute] = value
}
}
public operator fun <V> Attribute<V>.invoke(value: V?) {
set(this, value)
}
public infix fun <V> Attribute<V>.put(value: V?) {
set(this, value)
}
/**
* Put all attributes for given [attributes]
*/
public fun putAll(attributes: Attributes) {
map.putAll(attributes.content)
}
public infix fun <V> SetAttribute<V>.add(attrValue: V) {
val currentSet: Set<V> = get(this) ?: emptySet()
map[this] = currentSet + attrValue
}
/**
* Remove an element from [SetAttribute]
*/
public infix fun <V> SetAttribute<V>.remove(attrValue: V) {
val currentSet: Set<V> = get(this) ?: emptySet()
map[this] = currentSet - attrValue
}
public fun build(): Attributes = MapAttributes(map)
}
/**
* Create [Attributes] with a given [builder]
* @param O the type for which attributes are built. The type is used only during compilation phase for static extension dispatch
*/
public fun <O> Attributes(builder: AttributesBuilder<O>.() -> Unit): Attributes =
AttributesBuilder<O>().apply(builder).build()

@ -1,34 +0,0 @@
/*
* 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.attributes
/**
* An attribute that has a type parameter for value
* @param type parameter-type
*/
public abstract class PolymorphicAttribute<T>(public val type: SafeType<T>) : Attribute<T> {
override fun equals(other: Any?): Boolean = other != null &&
(this::class == other::class) &&
(other as? PolymorphicAttribute<*>)?.type == this.type
override fun hashCode(): Int = this::class.hashCode() + type.hashCode()
}
/**
* Get a polymorphic attribute using attribute factory
*/
@UnstableAttributesAPI
public operator fun <T> Attributes.get(attributeKeyBuilder: () -> PolymorphicAttribute<T>): T? =
get(attributeKeyBuilder())
/**
* Set a polymorphic attribute using its factory
*/
@UnstableAttributesAPI
public operator fun <O, T> AttributesBuilder<O>.set(attributeKeyBuilder: () -> PolymorphicAttribute<T>, value: T) {
set(attributeKeyBuilder(), value)
}

@ -1,35 +0,0 @@
/*
* 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.attributes
import kotlin.jvm.JvmInline
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.typeOf
/**
* Safe variant ok Kotlin [KType] that ensures that the type parameter is of the same type as [kType]
*
* @param kType raw [KType]
*/
@JvmInline
public value class SafeType<out T> @PublishedApi internal constructor(public val kType: KType)
public inline fun <reified T> safeTypeOf(): SafeType<T> = SafeType(typeOf<T>())
/**
* Derive Kotlin [KClass] from this type and fail if the type is not a class (should not happen)
*/
@Suppress("UNCHECKED_CAST")
@UnstableAttributesAPI
public val <T> SafeType<T>.kClass: KClass<T & Any> get() = kType.classifier as KClass<T & Any>
/**
* An interface containing [type] for dynamic type checking.
*/
public interface WithType<out T> {
public val type: SafeType<T>
}

@ -1,17 +0,0 @@
/*
* 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.attributes
/**
* Marks declarations that are still experimental in the Attributes-kt APIs, which means that the design of the corresponding
* declarations has open issues that may (or may not) lead to their changes in the future. Roughly speaking, there is
* a chance of those declarations will be deprecated in the future or the semantics of their behavior may change
* in some way that may break some code.
*/
@MustBeDocumented
@Retention(value = AnnotationRetention.BINARY)
@RequiresOptIn("This API is unstable and could change in future", RequiresOptIn.Level.WARNING)
public annotation class UnstableAttributesAPI

@ -1,4 +1,121 @@
# Module benchmarks
# BenchmarksResult
## Report for benchmark configuration <code>main</code>
* Run on OpenJDK 64-Bit Server VM (build 17.0.11+9) with Java process:
```
C:\Users\altavir\scoop\apps\gradle\current\.gradle\jdks\eclipse_adoptium-17-amd64-windows.2\bin\java.exe -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant
```
* JMH 1.21 was used in `thrpt` mode with 5 warmup iterations by 10 s and 5 measurement iterations by 10 s.
### [ArrayBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/ArrayBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`benchmarkArrayRead`|3.9E+06 &plusmn; 3.4E+05 ops/s|
|`benchmarkBufferRead`|4.0E+06 &plusmn; 3.2E+05 ops/s|
|`nativeBufferRead`|3.9E+06 &plusmn; 2.0E+05 ops/s|
### [BigIntBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BigIntBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`jvmAdd`|3.1E+07 &plusmn; 1.8E+07 ops/s|
|`jvmAddLarge`|4.5E+04 &plusmn; 5.5E+03 ops/s|
|`jvmMultiply`|3.6E+07 &plusmn; 1.7E+07 ops/s|
|`jvmMultiplyLarge`|1.9E+02 &plusmn; 95 ops/s|
|`jvmParsing10`|4.0E+06 &plusmn; 8.8E+05 ops/s|
|`jvmParsing16`|3.6E+06 &plusmn; 6.5E+05 ops/s|
|`jvmPower`|25 &plusmn; 1.4 ops/s|
|`jvmSmallAdd`|5.7E+07 &plusmn; 9.7E+05 ops/s|
|`kmAdd`|2.6E+07 &plusmn; 8.8E+05 ops/s|
|`kmAddLarge`|2.3E+04 &plusmn; 1.2E+03 ops/s|
|`kmMultiply`|3.8E+07 &plusmn; 5.5E+06 ops/s|
|`kmMultiplyLarge`|36 &plusmn; 3.8 ops/s|
|`kmParsing10`|2.5E+06 &plusmn; 1.4E+05 ops/s|
|`kmParsing16`|3.7E+06 &plusmn; 4.7E+05 ops/s|
|`kmPower`|6.6 &plusmn; 1.0 ops/s|
|`kmSmallAdd`|2.0E+07 &plusmn; 1.7E+06 ops/s|
### [BufferBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BufferBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`bufferViewReadWrite`|6.0E+06 &plusmn; 7.4E+05 ops/s|
|`bufferViewReadWriteSpecialized`|7.6E+05 &plusmn; 1.1E+04 ops/s|
|`complexBufferReadWrite`|2.4E+06 &plusmn; 2.7E+05 ops/s|
|`doubleArrayReadWrite`|7.3E+06 &plusmn; 4.3E+05 ops/s|
|`doubleBufferReadWrite`|7.3E+06 &plusmn; 3.4E+05 ops/s|
### [DotBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/DotBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`bufferedDot`|1.3 &plusmn; 0.032 ops/s|
|`cmDot`|0.42 &plusmn; 0.20 ops/s|
|`cmDotWithConversion`|0.83 &plusmn; 0.12 ops/s|
|`ejmlDot`|2.6 &plusmn; 0.049 ops/s|
|`ejmlDotWithConversion`|2.5 &plusmn; 0.075 ops/s|
|`multikDot`|25 &plusmn; 0.52 ops/s|
|`ojalgoDot`|11 &plusmn; 1.3 ops/s|
|`parallelDot`|11 &plusmn; 0.17 ops/s|
|`tensorDot`|1.1 &plusmn; 0.028 ops/s|
|`tfDot`|4.7 &plusmn; 0.14 ops/s|
### [ExpressionsInterpretersBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/ExpressionsInterpretersBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`asmGenericExpression`|12 &plusmn; 0.099 ops/s|
|`asmPrimitiveExpression`|26 &plusmn; 0.57 ops/s|
|`asmPrimitiveExpressionArray`|74 &plusmn; 1.7 ops/s|
|`functionalExpression`|5.3 &plusmn; 0.015 ops/s|
|`justCalculate`|74 &plusmn; 0.85 ops/s|
|`mstExpression`|4.2 &plusmn; 0.10 ops/s|
|`rawExpression`|25 &plusmn; 0.74 ops/s|
### [IntegrationBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/IntegrationBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`complexIntegration`|2.6E+03 &plusmn; 46 ops/s|
|`doubleIntegration`|2.8E+03 &plusmn; 1.1E+02 ops/s|
### [MatrixInverseBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MatrixInverseBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`cmLUPInversion`|2.1E+03 &plusmn; 35 ops/s|
|`ejmlInverse`|1.2E+03 &plusmn; 27 ops/s|
|`kmathLupInversion`|4.0E+02 &plusmn; 52 ops/s|
|`kmathParallelLupInversion`|4.0E+02 &plusmn; 9.6 ops/s|
|`ojalgoInverse`|2.1E+03 &plusmn; 3.3E+02 ops/s|
### [MinStatisticBenchmark.kt](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/MinStatisticBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`kotlinArrayMin`| 1875.7 &plusmn; 401.5 ops/s |
|`minBlocking`| 1357.9 &plusmn; 72.0 ops/s |
### [NDFieldBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/NDFieldBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`boxingFieldAdd`|1.7 &plusmn; 0.11 ops/s|
|`multikAdd`|7.0 &plusmn; 0.41 ops/s|
|`multikInPlaceAdd`|34 &plusmn; 1.7 ops/s|
|`specializedFieldAdd`|7.2 &plusmn; 1.2 ops/s|
|`tensorAdd`|7.2 &plusmn; 1.6 ops/s|
|`tensorInPlaceAdd`|7.4 &plusmn; 4.9 ops/s|
|`viktorAdd`|5.8 &plusmn; 0.65 ops/s|
### [ViktorBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/ViktorBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`doubleFieldAddition`|7.1 &plusmn; 2.0 ops/s|
|`rawViktor`|6.2 &plusmn; 1.0 ops/s|
|`viktorFieldAddition`|6.4 &plusmn; 0.29 ops/s|
### [ViktorLogBenchmark](src/jvmMain/kotlin/space/kscience/kmath/benchmarks/ViktorLogBenchmark.kt)
| Benchmark | Score |
|:---------:|:-----:|
|`rawViktorLog`|1.3 &plusmn; 0.016 ops/s|
|`realFieldLog`|1.3 &plusmn; 0.019 ops/s|
|`viktorFieldLog`|1.3 &plusmn; 0.020 ops/s|

@ -1,24 +1,30 @@
@file:Suppress("UNUSED_VARIABLE")
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
import space.kscience.kmath.benchmarks.addBenchmarkProperties
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.benchmark.gradle.BenchmarksExtension
import java.util.*
plugins {
kotlin("multiplatform")
alias(spclibs.plugins.kotlin.plugin.allopen)
id("org.jetbrains.kotlinx.benchmark")
alias(spclibs.plugins.kotlinx.benchmark)
}
allOpen.annotation("org.openjdk.jmh.annotations.State")
sourceSets.register("benchmarks")
//sourceSets.register("benchmarks")
repositories {
mavenCentral()
}
val multikVersion: String by rootProject.extra
kotlin {
jvmToolchain(17)
compilerOptions {
optIn.addAll(
"space.kscience.kmath.UnstableKMathAPI"
)
}
jvm()
js(IR) {
@ -45,23 +51,24 @@ kotlin {
implementation(project(":kmath-dimensions"))
implementation(project(":kmath-for-real"))
implementation(project(":kmath-tensors"))
implementation(project(":kmath-multik"))
implementation("org.jetbrains.kotlinx:multik-default:$multikVersion")
implementation(libs.multik.default)
implementation(spclibs.kotlinx.benchmark.runtime)
}
}
val jvmMain by getting {
dependencies {
implementation(project(":kmath-commons"))
implementation(project(":kmath-ejml"))
implementation(project(":kmath-nd4j"))
implementation(project(":kmath-kotlingrad"))
implementation(project(":kmath-viktor"))
implementation(project(":kmath-jafama"))
implementation(projects.kmathCommons)
implementation(projects.kmathEjml)
implementation(projects.kmathKotlingrad)
implementation(projects.kmathViktor)
implementation(projects.kmathOjalgo)
implementation(projects.kmath.kmathTensorflow)
implementation("org.tensorflow:tensorflow-core-platform:0.4.0")
implementation("org.nd4j:nd4j-native:1.0.0-M1")
implementation(projects.kmathMultik)
implementation(libs.tensorflow.core.platform)
// implementation(projects.kmathNd4j)
// implementation(libs.nd4j.native.platform)
// uncomment if your system supports AVX2
// val os = System.getProperty("os.name")
//
@ -96,6 +103,11 @@ benchmark {
include("BufferBenchmark")
}
configurations.register("minStatistic") {
commonConfiguration()
include("MinStatisticBenchmark")
}
configurations.register("nd") {
commonConfiguration()
include("NDFieldBenchmark")
@ -152,23 +164,121 @@ benchmark {
}
}
kotlin.sourceSets.all {
with(languageSettings) {
optIn("kotlin.contracts.ExperimentalContracts")
optIn("kotlin.ExperimentalUnsignedTypes")
optIn("space.kscience.kmath.UnstableKMathAPI")
}
}
tasks.withType<KotlinJvmCompile> {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = freeCompilerArgs + "-Xjvm-default=all" + "-Xlambdas=indy"
private data class JmhReport(
val jmhVersion: String,
val benchmark: String,
val mode: String,
val threads: Int,
val forks: Int,
val jvm: String,
val jvmArgs: List<String>,
val jdkVersion: String,
val vmName: String,
val vmVersion: String,
val warmupIterations: Int,
val warmupTime: String,
val warmupBatchSize: Int,
val measurementIterations: Int,
val measurementTime: String,
val measurementBatchSize: Int,
val params: Map<String, String> = emptyMap(),
val primaryMetric: PrimaryMetric,
val secondaryMetrics: Map<String, SecondaryMetric>,
) {
interface Metric {
val score: Double
val scoreError: Double
val scoreConfidence: List<Double>
val scorePercentiles: Map<Double, Double>
val scoreUnit: String
}
data class PrimaryMetric(
override val score: Double,
override val scoreError: Double,
override val scoreConfidence: List<Double>,
override val scorePercentiles: Map<Double, Double>,
override val scoreUnit: String,
val rawDataHistogram: List<List<List<List<Double>>>>? = null,
val rawData: List<List<Double>>? = null,
) : Metric
data class SecondaryMetric(
override val score: Double,
override val scoreError: Double,
override val scoreConfidence: List<Double>,
override val scorePercentiles: Map<Double, Double>,
override val scoreUnit: String,
val rawData: List<List<Double>>,
) : Metric
}
readme {
maturity = space.kscience.gradle.Maturity.EXPERIMENTAL
}
addBenchmarkProperties()
val jsonMapper = jacksonObjectMapper()
fun noun(number: Number, singular: String, plural: String) = if (number.toLong() == 1L) singular else plural
extensions.findByType(BenchmarksExtension::class.java)?.configurations?.forEach { cfg ->
val propertyName =
"benchmark${cfg.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }}"
logger.info("Processing benchmark data from benchmark ${cfg.name} into readme property $propertyName")
val launches = layout.buildDirectory.dir("reports/benchmarks/${cfg.name}").get().asFile
if (!launches.exists()) return@forEach
property(propertyName) {
val resDirectory = launches.listFiles()?.maxByOrNull {
it.nameWithoutExtension
}
if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) {
"> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**."
} else {
val reports: List<JmhReport> =
jsonMapper.readValue<List<JmhReport>>(resDirectory.resolve("jvm.json"))
buildString {
appendLine("## Report for benchmark configuration <code>${cfg.name}</code>")
appendLine()
val first = reports.first()
appendLine("* Run on ${first.vmName} (build ${first.vmVersion}) with Java process:")
appendLine()
appendLine("```")
appendLine(
"${first.jvm} ${
first.jvmArgs.joinToString(" ")
}"
)
appendLine("```")
appendLine(
"* JMH ${first.jmhVersion} was used in `${first.mode}` mode with ${first.warmupIterations} warmup ${
noun(first.warmupIterations, "iteration", "iterations")
} by ${first.warmupTime} and ${first.measurementIterations} measurement ${
noun(first.measurementIterations, "iteration", "iterations")
} by ${first.measurementTime}."
)
reports.groupBy { it.benchmark.substringBeforeLast(".") }.forEach { (cl, compare) ->
appendLine("### [${cl.substringAfterLast(".")}](src/jvmMain/kotlin/${cl.replace(".","/")}.kt)")
appendLine()
appendLine("| Benchmark | Score |")
appendLine("|:---------:|:-----:|")
compare.forEach { report ->
val benchmarkName = report.benchmark.substringAfterLast(".")
val score = String.format("%.2G", report.primaryMetric.score)
val error = String.format("%.2G", report.primaryMetric.scoreError)
appendLine("|`$benchmarkName`|$score &plusmn; $error ${report.primaryMetric.scoreUnit}|")
}
}
}
}
}
}
}

@ -0,0 +1,5 @@
# BenchmarksResult
${benchmarkMain}

@ -14,6 +14,7 @@ import space.kscience.kmath.expressions.*
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.bindSymbol
import space.kscience.kmath.operations.invoke
import space.kscience.kmath.structures.Float64
import kotlin.math.sin
import kotlin.random.Random
import space.kscience.kmath.estree.compileToExpression as estreeCompileToExpression
@ -67,7 +68,7 @@ class ExpressionsInterpretersBenchmark {
blackhole.consume(sum)
}
private fun invokeAndSum(expr: Expression<Double>, blackhole: Blackhole) {
private fun invokeAndSum(expr: Expression<Float64>, blackhole: Blackhole) {
val random = Random(0)
var sum = 0.0
val m = HashMap<Symbol, Double>()
@ -99,7 +100,7 @@ class ExpressionsInterpretersBenchmark {
private val wasm = node.wasmCompileToExpression(Float64Field)
private val estree = node.estreeCompileToExpression(Float64Field)
private val raw = Expression<Double> { args ->
private val raw = Expression<Float64> { args ->
val x = args.getValue(x)
x * 2.0 + 2.0 / x - 16.0 / sin(x)
}

@ -14,6 +14,8 @@ import space.kscience.kmath.ejml.EjmlLinearSpaceDDRM
import space.kscience.kmath.linear.Float64ParallelLinearSpace
import space.kscience.kmath.linear.invoke
import space.kscience.kmath.linear.linearSpace
import space.kscience.kmath.ojalgo.Ojalgo
import space.kscience.kmath.ojalgo.linearSpace
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.tensorflow.produceWithTF
import space.kscience.kmath.tensors.core.tensorAlgebra
@ -56,13 +58,13 @@ internal class DotBenchmark {
}
@Benchmark
fun cmDot(blackhole: Blackhole) = CMLinearSpace {
blackhole.consume(cmMatrix1 dot cmMatrix2)
fun cmDot(blackhole: Blackhole): Unit = CMLinearSpace {
blackhole.consume(cmMatrix1.asMatrix() dot cmMatrix2.asMatrix())
}
@Benchmark
fun ejmlDot(blackhole: Blackhole) = EjmlLinearSpaceDDRM {
blackhole.consume(ejmlMatrix1 dot ejmlMatrix2)
fun ejmlDot(blackhole: Blackhole): Unit = EjmlLinearSpaceDDRM {
blackhole.consume(ejmlMatrix1.asMatrix() dot ejmlMatrix2.asMatrix())
}
@Benchmark
@ -70,6 +72,11 @@ internal class DotBenchmark {
blackhole.consume(matrix1 dot matrix2)
}
@Benchmark
fun ojalgoDot(blackhole: Blackhole) = Ojalgo.R064.linearSpace {
blackhole.consume(matrix1 dot matrix2)
}
@Benchmark
fun multikDot(blackhole: Blackhole) = with(multikAlgebra) {
blackhole.consume(matrix1 dot matrix2)

@ -15,6 +15,7 @@ import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.bindSymbol
import space.kscience.kmath.operations.invoke
import space.kscience.kmath.structures.Float64
import kotlin.math.sin
import kotlin.random.Random
@ -83,7 +84,7 @@ internal class ExpressionsInterpretersBenchmark {
blackhole.consume(sum)
}
private fun invokeAndSum(expr: Expression<Double>, blackhole: Blackhole) {
private fun invokeAndSum(expr: Expression<Float64>, blackhole: Blackhole) {
val random = Random(0)
var sum = 0.0
val m = HashMap<Symbol, Double>()
@ -114,9 +115,9 @@ internal class ExpressionsInterpretersBenchmark {
private val asmPrimitive = node.compileToExpression(Float64Field)
private val xIdx = asmPrimitive.indexer.indexOf(x)
private val asmGeneric = node.compileToExpression(Float64Field as Algebra<Double>)
private val asmGeneric = node.compileToExpression(Float64Field as Algebra<Float64>)
private val raw = Expression<Double> { args ->
private val raw = Expression<Float64> { args ->
val x = args[x]!!
x * 2.0 + 2.0 / x - 16.0 / sin(x)
}

@ -1,39 +0,0 @@
/*
* Copyright 2018-2024 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 kotlinx.benchmark.Blackhole
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.State
import space.kscience.kmath.jafama.JafamaDoubleField
import space.kscience.kmath.jafama.StrictJafamaDoubleField
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.invoke
import kotlin.random.Random
@State(Scope.Benchmark)
internal class JafamaBenchmark {
@Benchmark
fun jafama(blackhole: Blackhole) = invokeBenchmarks(blackhole) { x ->
JafamaDoubleField { x * power(x, 4) * exp(x) / cos(x) + sin(x) }
}
@Benchmark
fun core(blackhole: Blackhole) = invokeBenchmarks(blackhole) { x ->
Float64Field { x * power(x, 4) * exp(x) / cos(x) + sin(x) }
}
@Benchmark
fun strictJafama(blackhole: Blackhole) = invokeBenchmarks(blackhole) { x ->
StrictJafamaDoubleField { x * power(x, 4) * exp(x) / cos(x) + sin(x) }
}
}
private inline fun invokeBenchmarks(blackhole: Blackhole, expr: (Double) -> Double) {
val rng = Random(0)
repeat(1000000) { blackhole.consume(expr(rng.nextDouble())) }
}

@ -12,10 +12,9 @@ import kotlinx.benchmark.State
import space.kscience.kmath.commons.linear.CMLinearSpace
import space.kscience.kmath.commons.linear.lupSolver
import space.kscience.kmath.ejml.EjmlLinearSpaceDDRM
import space.kscience.kmath.linear.invoke
import space.kscience.kmath.linear.linearSpace
import space.kscience.kmath.linear.lupSolver
import space.kscience.kmath.linear.parallel
import space.kscience.kmath.linear.*
import space.kscience.kmath.ojalgo.Ojalgo
import space.kscience.kmath.ojalgo.linearSpace
import space.kscience.kmath.operations.algebra
import kotlin.random.Random
@ -48,10 +47,14 @@ internal class MatrixInverseBenchmark {
blackhole.consume(lupSolver().inverse(matrix))
}
@Benchmark
fun ejmlInverse(blackhole: Blackhole) = EjmlLinearSpaceDDRM {
blackhole.consume(matrix.toEjml().inverted())
blackhole.consume(matrix.inverted())
}
@Benchmark
fun ojalgoInverse(blackhole: Blackhole) = Ojalgo.R064.linearSpace {
blackhole.consume(matrix.getOrComputeAttribute(Inverted))
}
}

@ -0,0 +1,44 @@
/*
* Copyright 2018-2025 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 kotlinx.benchmark.Benchmark
import kotlinx.benchmark.Blackhole
import kotlinx.benchmark.Scope
import kotlinx.benchmark.State
import kotlinx.coroutines.runBlocking
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.stat.min
import space.kscience.kmath.structures.*
@State(Scope.Benchmark)
internal class MinStatisticBenchmark {
@Benchmark
fun kotlinArrayMin(blackhole: Blackhole) {
val array = DoubleArray(size) { it.toDouble() }
var res = 0.0
(0 until size).forEach {
res += array.min()
}
blackhole.consume(res)
}
@Benchmark
fun minBlocking(blackhole: Blackhole) {
val buffer = Float64Buffer(size) { it.toDouble() }
var res = 0.0
(0 until size).forEach {
res += Float64Field.min.evaluateBlocking(buffer)
}
blackhole.consume(res)
}
private companion object {
private const val size = 1000
}
}

@ -15,8 +15,8 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DN
import org.jetbrains.kotlinx.multik.ndarray.data.DataType
import space.kscience.kmath.UnsafeKMathAPI
import space.kscience.kmath.nd.*
import space.kscience.kmath.nd4j.nd4j
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.tensors.core.DoubleTensor
import space.kscience.kmath.tensors.core.one
import space.kscience.kmath.tensors.core.tensorAlgebra
@ -31,34 +31,33 @@ internal class NDFieldBenchmark {
private val shape = ShapeND(dim, dim)
private val specializedField = Float64Field.ndAlgebra
private val genericField = BufferedFieldOpsND(Float64Field)
private val nd4jField = Float64Field.nd4j
private val viktorField = Float64Field.viktorAlgebra
}
@Benchmark
fun specializedFieldAdd(blackhole: Blackhole) = with(specializedField) {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
blackhole.consume(res)
}
@Benchmark
fun boxingFieldAdd(blackhole: Blackhole) = with(genericField) {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
blackhole.consume(res)
}
@Benchmark
fun multikAdd(blackhole: Blackhole) = with(multikAlgebra) {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
blackhole.consume(res)
}
@Benchmark
fun viktorAdd(blackhole: Blackhole) = with(viktorField) {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
blackhole.consume(res)
}
@ -87,7 +86,7 @@ internal class NDFieldBenchmark {
// @Benchmark
// fun nd4jAdd(blackhole: Blackhole) = with(nd4jField) {
// var res: StructureND<Double> = one(dim, dim)
// var res: StructureND<Float64> = one(dim, dim)
// repeat(n) { res += 1.0 }
// blackhole.consume(res)
// }

@ -9,8 +9,8 @@ import kotlinx.benchmark.Benchmark
import kotlinx.benchmark.Blackhole
import kotlinx.benchmark.Scope
import kotlinx.benchmark.State
import space.kscience.kmath.linear.MatrixBuilder
import space.kscience.kmath.linear.linearSpace
import space.kscience.kmath.linear.matrix
import space.kscience.kmath.linear.symmetric
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.tensors.core.symEigJacobi
@ -24,7 +24,7 @@ internal class TensorAlgebraBenchmark {
private val random = Random(12224)
private const val dim = 30
private val matrix = Float64Field.linearSpace.matrix(dim, dim).symmetric { _, _ -> random.nextDouble() }
private val matrix = Float64Field.linearSpace.MatrixBuilder(dim, dim).symmetric { _, _ -> random.nextDouble() }
}
@Benchmark

@ -15,6 +15,7 @@ import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.nd.ndAlgebra
import space.kscience.kmath.nd.one
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.viktor.ViktorFieldND
@State(Scope.Benchmark)
@ -23,7 +24,7 @@ internal class ViktorBenchmark {
@Benchmark
fun doubleFieldAddition(blackhole: Blackhole) {
with(doubleField) {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
blackhole.consume(res)
}

@ -2,12 +2,10 @@ import space.kscience.gradle.useApache2Licence
import space.kscience.gradle.useSPCTeam
plugins {
id("space.kscience.gradle.project")
id("org.jetbrains.kotlinx.kover") version "0.7.6"
alias(spclibs.plugins.kscience.project)
alias(spclibs.plugins.kotlinx.kover)
}
val attributesVersion by extra("0.2.0")
allprojects {
repositories {
maven("https://repo.kotlin.link")
@ -16,30 +14,49 @@ allprojects {
}
group = "space.kscience"
version = "0.4.0"
version = "0.4.3-dev-1"
}
dependencies {
subprojects.forEach {
dokka(it)
}
}
dokka{
dokkaSourceSets.configureEach {
val readmeFile = projectDir.resolve("README.md")
if (readmeFile.exists()) includes.from(readmeFile)
}
}
subprojects {
if (name.startsWith("kmath")) apply<MavenPublishPlugin>()
plugins.withId("org.jetbrains.dokka") {
tasks.withType<org.jetbrains.dokka.gradle.DokkaTaskPartial> {
dependsOn(tasks["assemble"])
dokkaSourceSets.all {
val readmeFile = this@subprojects.projectDir.resolve("README.md")
dokka {
dokkaSourceSets.configureEach {
val readmeFile = projectDir.resolve("README.md")
if (readmeFile.exists()) includes.from(readmeFile)
val kotlinDirPath = "src/$name/kotlin"
val kotlinDir = file(kotlinDirPath)
if (kotlinDir.exists()) sourceLink {
localDirectory.set(kotlinDir)
remoteUrl.set(
uri("https://github.com/SciProgCentre/kmath/tree/master/${this@subprojects.name}/$kotlinDirPath").toURL()
remoteUrl(
"https://github.com/SciProgCentre/kmath/tree/master/${name}/$kotlinDirPath"
)
}
fun externalDocumentationLink(url: String, packageListUrl: String? = null){
externalDocumentationLinks.register(url) {
url(url)
packageListUrl?.let {
packageListUrl(it)
}
}
}
externalDocumentationLink("https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/")
externalDocumentationLink("https://deeplearning4j.org/api/latest/")
externalDocumentationLink("https://axelclk.bitbucket.io/symja/javadoc/")
@ -50,11 +67,12 @@ subprojects {
)
externalDocumentationLink(
"https://breandan.net/kotlingrad/kotlingrad/",
"https://breandan.net/kotlingrad/kotlingrad/kotlingrad/package-list",
"https://breandan.net/kotlingrad/kotlingrad",
"https://breandan.net/kotlingrad/package-list",
)
}
}
}
}
@ -66,9 +84,7 @@ ksciencePublish {
useSPCTeam()
}
repository("spc", "https://maven.sciprog.center/kscience")
sonatype("https://oss.sonatype.org")
central()
}
apiValidation.nonPublicMarkers.add("space.kscience.kmath.UnstableKMathAPI")
val multikVersion by extra("0.2.3")

@ -1,34 +0,0 @@
plugins {
`kotlin-dsl`
`version-catalog`
}
repositories {
mavenLocal()
maven("https://repo.kotlin.link")
mavenCentral()
gradlePluginPortal()
}
val toolsVersion = spclibs.versions.tools.get()
val kotlinVersion = spclibs.versions.kotlin.asProvider().get()
val benchmarksVersion = spclibs.versions.kotlinx.benchmark.get()
dependencies {
api("space.kscience:gradle-tools:$toolsVersion")
//plugins form benchmarks
api("org.jetbrains.kotlinx:kotlinx-benchmark-plugin:$benchmarksVersion")
//api("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
//to be used inside build-script only
//implementation(spclibs.kotlinx.serialization.json)
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.+")
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
sourceSets.all {
languageSettings.optIn("kotlin.OptIn")
}
}

@ -1,38 +0,0 @@
/*
* Copyright 2018-2021 KMath contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
dependencyResolutionManagement {
val projectProperties = java.util.Properties()
file("../gradle.properties").inputStream().use {
projectProperties.load(it)
}
projectProperties.forEach { key, value ->
extra.set(key.toString(), value)
}
val toolsVersion: String = projectProperties["toolsVersion"].toString()
@Suppress("UnstableApiUsage")
repositories {
mavenLocal()
maven("https://repo.kotlin.link")
mavenCentral()
gradlePluginPortal()
}
versionCatalogs {
create("spclibs") {
from("space.kscience:version-catalog:$toolsVersion")
}
}
}

@ -1,55 +0,0 @@
/*
* Copyright 2018-2024 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
data class JmhReport(
val jmhVersion: String,
val benchmark: String,
val mode: String,
val threads: Int,
val forks: Int,
val jvm: String,
val jvmArgs: List<String>,
val jdkVersion: String,
val vmName: String,
val vmVersion: String,
val warmupIterations: Int,
val warmupTime: String,
val warmupBatchSize: Int,
val measurementIterations: Int,
val measurementTime: String,
val measurementBatchSize: Int,
val params: Map<String, String> = emptyMap(),
val primaryMetric: PrimaryMetric,
val secondaryMetrics: Map<String, SecondaryMetric>,
) {
interface Metric {
val score: Double
val scoreError: Double
val scoreConfidence: List<Double>
val scorePercentiles: Map<Double, Double>
val scoreUnit: String
}
data class PrimaryMetric(
override val score: Double,
override val scoreError: Double,
override val scoreConfidence: List<Double>,
override val scorePercentiles: Map<Double, Double>,
override val scoreUnit: String,
val rawDataHistogram: List<List<List<List<Double>>>>? = null,
val rawData: List<List<Double>>? = null,
) : Metric
data class SecondaryMetric(
override val score: Double,
override val scoreError: Double,
override val scoreConfidence: List<Double>,
override val scorePercentiles: Map<Double, Double>,
override val scoreUnit: String,
val rawData: List<List<Double>>,
) : Metric
}

@ -1,110 +0,0 @@
/*
* Copyright 2018-2024 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 com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.benchmark.gradle.BenchmarksExtension
import org.gradle.api.Project
import space.kscience.gradle.KScienceReadmeExtension
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.format.SignStyle
import java.time.temporal.ChronoField.*
import java.util.*
private val ISO_DATE_TIME: DateTimeFormatter = DateTimeFormatterBuilder().run {
parseCaseInsensitive()
appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
appendLiteral('-')
appendValue(MONTH_OF_YEAR, 2)
appendLiteral('-')
appendValue(DAY_OF_MONTH, 2)
appendLiteral('T')
appendValue(HOUR_OF_DAY, 2)
appendLiteral('.')
appendValue(MINUTE_OF_HOUR, 2)
optionalStart()
appendLiteral('.')
appendValue(SECOND_OF_MINUTE, 2)
optionalStart()
appendFraction(NANO_OF_SECOND, 0, 9, true)
optionalStart()
appendOffsetId()
optionalStart()
appendLiteral('[')
parseCaseSensitive()
appendZoneRegionId()
appendLiteral(']')
toFormatter()
}
private fun noun(number: Number, singular: String, plural: String) = if (number.toLong() == 1L) singular else plural
private val jsonMapper = jacksonObjectMapper()
fun Project.addBenchmarkProperties() {
val benchmarksProject = this
rootProject.subprojects.forEach { p ->
p.extensions.findByType(KScienceReadmeExtension::class.java)?.run {
benchmarksProject.extensions.findByType(BenchmarksExtension::class.java)?.configurations?.forEach { cfg ->
property("benchmark${cfg.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }}") {
val launches = benchmarksProject.layout.buildDirectory.dir("reports/benchmarks/${cfg.name}").get()
val resDirectory = launches.files().maxByOrNull {
LocalDateTime.parse(it.name, ISO_DATE_TIME).atZone(ZoneId.systemDefault()).toInstant()
}
if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) {
"> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**."
} else {
val reports: List<JmhReport> =
jsonMapper.readValue<List<JmhReport>>(resDirectory.resolve("jvm.json"))
buildString {
appendLine("<details>")
appendLine("<summary>")
appendLine("Report for benchmark configuration <code>${cfg.name}</code>")
appendLine("</summary>")
appendLine()
val first = reports.first()
appendLine("* Run on ${first.vmName} (build ${first.vmVersion}) with Java process:")
appendLine()
appendLine("```")
appendLine(
"${first.jvm} ${
first.jvmArgs.joinToString(" ")
}"
)
appendLine("```")
appendLine(
"* JMH ${first.jmhVersion} was used in `${first.mode}` mode with ${first.warmupIterations} warmup ${
noun(first.warmupIterations, "iteration", "iterations")
} by ${first.warmupTime} and ${first.measurementIterations} measurement ${
noun(first.measurementIterations, "iteration", "iterations")
} by ${first.measurementTime}."
)
appendLine()
appendLine("| Benchmark | Score |")
appendLine("|:---------:|:-----:|")
reports.forEach { report ->
appendLine("|`${report.benchmark}`|${report.primaryMetric.score} &plusmn; ${report.primaryMetric.scoreError} ${report.primaryMetric.scoreUnit}|")
}
appendLine("</details>")
}
}
}
}
}
}
}

@ -31,7 +31,7 @@ The code to run this looks like:
```kotlin
specializedField.run {
var res: NDBuffer<Double> = one
var res: NDBuffer<Float64> = one
repeat(n) {
res += 1.0
}
@ -103,7 +103,7 @@ The boxing field produced by
```kotlin
genericField.run {
var res: NDBuffer<Double> = one
var res: NDBuffer<Float64> = one
repeat(n) {
res += 1.0
}

@ -11,4 +11,6 @@
* [Expressions](expressions.md)
* [Statistics](statistics.md): statistical functions on data [Buffers](buffers.md)
* Commons math integration

34
docs/statistics.md Normal file

@ -0,0 +1,34 @@
# Statistics
Mathematically speaking, a statistic is a measurable numerical function of sample data.
In KMath, a statistic is a function that operates on a [Buffer](buffers.md) and is implemented as the `evaluate` method
of the `Statistic` interface.
There are two subinterfaces of the `Statistic` interface:
* `BlockingStatistic` A statistic that is computed in a synchronous blocking mode
* `ComposableStatistic` A statistic tha could be computed separately on different blocks of data and then composed
## Common statistics and Implementation Status
| Category | Statistic | Description | Implementation Status |
|------------------|-------------------|------------------------------------|--------------------------------|
| **Basic** | Min | Minimum value | ✅ `ComposableStatistic` |
| | Max | Maximum value | ✅ `ComposableStatistic` |
| | Mean | Arithmetic mean | ✅ `ComposableStatistic` |
| | Sum | Sum of all values | 🚧 Not yet implemented |
| | Product | Product of all values | 🚧 Not yet implemented |
| **Distribution** | Median | Median (50th percentile) | ✅ `BlockingStatistic` |
| | Quantile | Quantile and percentile | ✅ `BlockingStatistic` |
| | Variance | Unbiased sample variance | ✅ `BlockingStatistic` |
| | StandardDeviation | Population standard deviation (σ) | ✅ `BlockingStatistic` |
| | Skewness | Measure of distribution asymmetry | 🚧 *(Requires `ThirdMoment`)* |
| | Kurtosis | Measure of distribution tailedness | 🚧 *(Requires `FourthMoment`)* |
| **Advanced** | GeometricMean | Nth root of product of values | ✅ `ComposableStatistic` |
| | SumOfLogs | Sum of natural logarithms | Does not planned |
| | SumOfSquares | Sum of squared values | 🚧 *(Blocks `Variance`)* |
| **Moments** | FirstMoment | Mean (same as `Mean`) | ✅ *(Alias for `Mean`)* |
| | SecondMoment | Variance (same as `Variance`) | ✅ *(Alias for `Variance`)* |
| | ThirdMoment | Used in skewness calculation | 🚧 Not yet implemented |
| | FourthMoment | Used in kurtosis calculation | 🚧 Not yet implemented |
| **Risk Metrics** | SemiVariance | Downside variance | 🚧 *(Depends on `Variance`)* |

@ -10,8 +10,6 @@ repositories {
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers")
}
val multikVersion: String by rootProject.extra
dependencies {
implementation(project(":kmath-ast"))
implementation(project(":kmath-kotlingrad"))
@ -25,20 +23,18 @@ dependencies {
implementation(project(":kmath-viktor"))
implementation(project(":kmath-dimensions"))
implementation(project(":kmath-ejml"))
implementation(project(":kmath-nd4j"))
implementation(project(":kmath-tensors"))
implementation(project(":kmath-symja"))
implementation(project(":kmath-for-real"))
//jafama
implementation(project(":kmath-jafama"))
//multik
implementation(project(":kmath-multik"))
implementation("org.jetbrains.kotlinx:multik-default:$multikVersion")
implementation(libs.multik.default)
//datetime
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
implementation(spclibs.kotlinx.datetime)
implementation("org.nd4j:nd4j-native:1.0.0-beta7")
// implementation(project(":kmath-nd4j"))
// implementation("org.nd4j:nd4j-native:1.0.0-beta7")
// uncomment if your system supports AVX2
// val os = System.getProperty("os.name")
@ -48,7 +44,7 @@ dependencies {
// os == "Linux" -> implementation("org.nd4j:nd4j-native:1.0.0-beta7:linux-x86_64-avx2")
// os == "Mac OS X" -> implementation("org.nd4j:nd4j-native:1.0.0-beta7:macosx-x86_64-avx2")
// } else
implementation("org.nd4j:nd4j-native-platform:1.0.0-beta7")
// implementation("org.nd4j:nd4j-native-platform:1.0.0-beta7")
implementation("org.slf4j:slf4j-simple:1.7.32")
// plotting
@ -56,7 +52,7 @@ dependencies {
}
kotlin {
jvmToolchain(11)
jvmToolchain(17)
sourceSets.all {
languageSettings {
optIn("kotlin.contracts.ExperimentalContracts")

@ -9,16 +9,21 @@ import kotlinx.html.br
import kotlinx.html.h3
import space.kscience.kmath.commons.optimization.CMOptimizer
import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.expressions.DifferentiableExpression
import space.kscience.kmath.expressions.autodiff
import space.kscience.kmath.expressions.symbol
import space.kscience.kmath.operations.asIterable
import space.kscience.kmath.operations.toList
import space.kscience.kmath.optimization.*
import space.kscience.kmath.optimization.minimize
import space.kscience.kmath.optimization.optimizeWith
import space.kscience.kmath.optimization.result
import space.kscience.kmath.optimization.resultValue
import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.real.DoubleVector
import space.kscience.kmath.real.map
import space.kscience.kmath.real.step
import space.kscience.kmath.stat.chiSquaredExpression
import space.kscience.kmath.structures.Float64
import space.kscience.plotly.*
import space.kscience.plotly.models.ScatterMode
import space.kscience.plotly.models.TraceValues
@ -64,7 +69,7 @@ suspend fun main() {
val yErr = y.map { sqrt(it) }//RealVector.same(x.size, sigma)
// compute differentiable chi^2 sum for given model ax^2 + bx + c
val chi2 = Double.autodiff.chiSquaredExpression(x, y, yErr) { arg ->
val chi2: DifferentiableExpression<Float64> = Double.autodiff.chiSquaredExpression(x, y, yErr) { arg ->
//bind variables to autodiff context
val a = bindSymbol(a)
val b = bindSymbol(b)
@ -77,9 +82,10 @@ suspend fun main() {
val result = chi2.optimizeWith(
CMOptimizer,
mapOf(a to 1.5, b to 0.9, c to 1.0),
) {
FunctionOptimizationTarget(OptimizationDirection.MINIMIZE)
}
attributesBuilder = {
minimize()
}
)
//display a page with plot and numerical results
val page = Plotly.page {

@ -7,7 +7,6 @@ package space.kscience.kmath.fit
import kotlinx.html.br
import kotlinx.html.h3
import space.kscience.attributes.Attributes
import space.kscience.kmath.data.XYErrorColumnarData
import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.expressions.Symbol
@ -65,7 +64,9 @@ suspend fun main() {
QowOptimizer,
Double.autodiff,
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),
attributes = Attributes(OptimizationParameters, listOf(a, b, c, d))
attributesBuilder = {
freeParameters(a, b, c, d)
},
) { arg ->
//bind variables to autodiff context
val a by binding

@ -14,11 +14,12 @@ import space.kscience.kmath.integration.gaussIntegrator
import space.kscience.kmath.integration.integrate
import space.kscience.kmath.integration.value
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Float64
import kotlin.math.pow
fun main() {
//Define a function
val function: Function1D<Double> = { x -> 3 * x.pow(2) + 2 * x + 1 }
val function: Function1D<Float64> = { x -> 3 * x.pow(2) + 2 * x + 1 }
//get the result of the integration
val result = Float64Field.gaussIntegrator.integrate(0.0..10.0, function = function)

@ -8,6 +8,7 @@ package space.kscience.kmath.functions
import space.kscience.kmath.interpolation.SplineInterpolator
import space.kscience.kmath.interpolation.interpolatePolynomials
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Float64
import space.kscience.plotly.Plotly
import space.kscience.plotly.UnstablePlotlyAPI
import space.kscience.plotly.makeFile
@ -23,7 +24,7 @@ fun main() {
x to sin(x)
}
val polynomial: PiecewisePolynomial<Double> = SplineInterpolator(Float64Field).interpolatePolynomials(data)
val polynomial: PiecewisePolynomial<Float64> = SplineInterpolator(Float64Field).interpolatePolynomials(data)
val function = polynomial.asFunction(Float64Field, 0.0)

@ -10,6 +10,7 @@ import space.kscience.kmath.interpolation.splineInterpolator
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.real.map
import space.kscience.kmath.real.step
import space.kscience.kmath.structures.Float64
import space.kscience.plotly.Plotly
import space.kscience.plotly.UnstablePlotlyAPI
import space.kscience.plotly.makeFile
@ -18,7 +19,7 @@ import space.kscience.plotly.scatter
@OptIn(UnstablePlotlyAPI::class)
fun main() {
val function: Function1D<Double> = { x ->
val function: Function1D<Float64> = { x ->
if (x in 30.0..50.0) {
1.0
} else {
@ -28,7 +29,7 @@ fun main() {
val xs = 0.0..100.0 step 0.5
val ys = xs.map(function)
val polynomial: PiecewisePolynomial<Double> = Float64Field.splineInterpolator.interpolatePolynomials(xs, ys)
val polynomial: PiecewisePolynomial<Float64> = Float64Field.splineInterpolator.interpolatePolynomials(xs, ys)
val polyFunction = polynomial.asFunction(Float64Field, 0.0)

@ -12,6 +12,7 @@ import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.nd.structureND
import space.kscience.kmath.nd.withNdAlgebra
import space.kscience.kmath.operations.algebra
import space.kscience.kmath.structures.Float64
import kotlin.math.pow
fun main(): Unit = Double.algebra.withNdAlgebra(2, 2) {
@ -22,7 +23,7 @@ fun main(): Unit = Double.algebra.withNdAlgebra(2, 2) {
}
//Define a function in a nd space
val function: (Double) -> StructureND<Double> = { x: Double -> 3 * x.pow(2) + 2 * diagonal(x) + 1 }
val function: (Double) -> StructureND<Float64> = { 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)

@ -1,15 +0,0 @@
/*
* Copyright 2018-2024 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.jafama
import space.kscience.kmath.operations.invoke
fun main() {
val a = 2.0
val b = StrictJafamaDoubleField { exp(a) }
println(JafamaDoubleField { b + a })
println(StrictJafamaDoubleField { ln(b) })
}

@ -0,0 +1,42 @@
/*
* Copyright 2018-2024 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.linear
import space.kscience.kmath.PerformancePitfall
import space.kscience.kmath.commons.linear.CMLinearSpace
import space.kscience.kmath.ejml.EjmlLinearSpaceDDRM
import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.operations.algebra
import space.kscience.kmath.structures.Float64
import kotlin.random.Random
@OptIn(PerformancePitfall::class)
fun main() {
val dim = 46
val random = Random(123)
val u = Float64.algebra.linearSpace.buildMatrix(dim, dim) { i, j -> if (i <= j) random.nextDouble() else 0.0 }
listOf(CMLinearSpace, EjmlLinearSpaceDDRM).forEach { algebra ->
with(algebra) {
//create a symmetric matrix
val matrix = buildMatrix(dim, dim) { row, col ->
if (row >= col) u[row, col] else u[col, row]
}
val eigen = matrix.getOrComputeAttribute(EIG) ?: error("Failed to compute eigenvalue decomposition")
check(
StructureND.contentEquals(
matrix,
eigen.v dot eigen.d dot eigen.v.transposed(),
1e-4
)
) { "$algebra decomposition failed" }
println("$algebra eigenvalue decomposition complete and checked" )
}
}
}

@ -6,18 +6,19 @@
package space.kscience.kmath.linear
import space.kscience.kmath.real.*
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.Float64Buffer
fun main() {
val x0 = DoubleVector(0.0, 0.0, 0.0)
val sigma = DoubleVector(1.0, 1.0, 1.0)
val gaussian: (Point<Double>) -> Double = { x ->
val gaussian: (Point<Float64>) -> Double = { x ->
require(x.size == x0.size)
kotlin.math.exp(-((x - x0) / sigma).square().sum())
}
fun ((Point<Double>) -> Double).grad(x: Point<Double>): Point<Double> {
fun ((Point<Float64>) -> Double).grad(x: Point<Float64>): Point<Float64> {
require(x.size == x0.size)
return Float64Buffer(x.size) { i ->
val h = sigma[i] / 5

@ -6,21 +6,21 @@
package space.kscience.kmath.operations
import space.kscience.kmath.commons.linear.CMLinearSpace
import space.kscience.kmath.linear.matrix
import space.kscience.kmath.linear.MatrixBuilder
import space.kscience.kmath.linear.fill
import space.kscience.kmath.nd.Float64BufferND
import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.nd.mutableStructureND
import space.kscience.kmath.nd.ndAlgebra
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.viktor.viktorAlgebra
import kotlin.collections.component1
import kotlin.collections.component2
fun main() {
val viktorStructure = Float64Field.viktorAlgebra.mutableStructureND(2, 2) { (i, j) ->
if (i == j) 2.0 else 0.0
}
val cmMatrix: Structure2D<Double> = CMLinearSpace.matrix(2, 2)(0.0, 1.0, 0.0, 3.0)
val cmMatrix: Structure2D<Float64> = CMLinearSpace.MatrixBuilder(2, 2).fill(0.0, 1.0, 0.0, 3.0)
val res: Float64BufferND = Float64Field.ndAlgebra {
exp(viktorStructure) + 2.0 * cmMatrix

@ -14,6 +14,7 @@ import space.kscience.kmath.operations.toList
import space.kscience.kmath.stat.KMComparisonResult
import space.kscience.kmath.stat.ksComparisonStatistic
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.slice
import space.kscience.plotly.*
import kotlin.math.PI
@ -24,7 +25,7 @@ fun Double.Companion.seriesAlgebra() = Double.algebra.bufferAlgebra.seriesAlgebr
fun main() = with(Double.seriesAlgebra()) {
fun Plot.plotSeries(name: String, buffer: Buffer<Double>) {
fun Plot.plotSeries(name: String, buffer: Buffer<Float64>) {
scatter {
this.name = name
x.numbers = buffer.labels
@ -37,10 +38,10 @@ fun main() = with(Double.seriesAlgebra()) {
val s2 = s1.slice(20..50).moveTo(40)
val s3: Buffer<Double> = s1.zip(s2) { l, r -> l + r } //s1 + s2
val s3: Buffer<Float64> = s1.zip(s2) { l, r -> l + r } //s1 + s2
val s4 = s3.map { ln(it) }
val kmTest: KMComparisonResult<Double> = ksComparisonStatistic(s1, s2)
val kmTest: KMComparisonResult<Float64> = ksComparisonStatistic(s1, s2)
Plotly.page {
h1 { +"This is my plot" }

@ -6,10 +6,7 @@
package space.kscience.kmath.series
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64Buffer
import space.kscience.kmath.structures.asBuffer
import space.kscience.kmath.structures.toDoubleArray
import space.kscience.kmath.structures.*
import space.kscience.plotly.*
import space.kscience.plotly.models.Scatter
import space.kscience.plotly.models.ScatterMode
@ -22,7 +19,7 @@ fun main(): Unit = with(Double.seriesAlgebra()) {
val arrayOfRandoms = DoubleArray(20) { random.nextDouble() }
val series1: Float64Buffer = arrayOfRandoms.asBuffer()
val series2: Series<Double> = series1.moveBy(3)
val series2: Series<Float64> = series1.moveBy(3)
val res = series2 - series1
@ -30,7 +27,7 @@ fun main(): Unit = with(Double.seriesAlgebra()) {
println(res)
fun Plot.series(name: String, buffer: Buffer<Double>, block: Scatter.() -> Unit = {}) {
fun Plot.series(name: String, buffer: Buffer<Float64>, block: Scatter.() -> Unit = {}) {
scatter {
this.name = name
x.numbers = buffer.offsetIndices

@ -36,8 +36,28 @@ private suspend fun runKMathChained(): Duration {
return Duration.between(startTime, Instant.now())
}
private fun runKMathBlocking(): Duration {
val generator = RandomGenerator.fromSource(RandomSource.MT, 123L)
val normal = GaussianSampler(7.0, 2.0)
val chain = normal.sample(generator)
val startTime = Instant.now()
var sum = 0.0
repeat(10000001) { counter ->
sum += chain.nextBlocking()
if (counter % 100000 == 0) {
val duration = Duration.between(startTime, Instant.now())
val meanValue = sum / counter
println("Chain sampler completed $counter elements in $duration: $meanValue")
}
}
return Duration.between(startTime, Instant.now())
}
private fun runCMDirect(): Duration {
val rng = RandomSource.create(RandomSource.MT, 123L)
val rng = RandomSource.MT.create(123L)
val sampler = CMGaussianSampler.of(
BoxMullerNormalizedGaussianSampler.of(rng),
@ -67,6 +87,8 @@ private fun runCMDirect(): Duration {
fun main(): Unit = runBlocking(Dispatchers.Default) {
val directJob = async { runCMDirect() }
val chainJob = async { runKMathChained() }
val blockingJob = async { runKMathBlocking() }
println("KMath Chained: ${chainJob.await()}")
println("KMath Blocking: ${blockingJob.await()}")
println("Apache Direct: ${directJob.await()}")
}

@ -10,13 +10,14 @@ import space.kscience.kmath.chains.Chain
import space.kscience.kmath.chains.combineWithState
import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.structures.Float64
private data class AveragingChainState(var num: Int = 0, var value: Double = 0.0)
/**
* Averaging.
*/
private fun Chain<Double>.mean(): Chain<Double> = combineWithState(AveragingChainState(), { it.copy() }) { chain ->
private fun Chain<Float64>.mean(): Chain<Float64> = combineWithState(AveragingChainState(), { it.copy() }) { chain ->
val next = chain.next()
num++
value += next

@ -26,7 +26,7 @@ fun main() {
val realTime = measureTimeMillis {
realField {
var res: StructureND<Double> = one
var res: StructureND<Float64> = one
repeat(n) {
res += 1.0
}

@ -7,9 +7,7 @@ package space.kscience.kmath.structures
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import org.nd4j.linalg.factory.Nd4j
import space.kscience.kmath.nd.*
import space.kscience.kmath.nd4j.nd4j
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.invoke
import space.kscience.kmath.viktor.ViktorFieldND
@ -26,7 +24,6 @@ internal inline fun measureAndPrint(title: String, block: () -> Unit) {
@OptIn(DelicateCoroutinesApi::class)
fun main() {
// initializing Nd4j
Nd4j.zeros(0)
val dim = 1000
val n = 1000
val shape = ShapeND(dim, dim)
@ -36,8 +33,6 @@ fun main() {
val doubleField = Float64Field.ndAlgebra
//A generic field. It should be used for objects, not primitives.
val genericField = BufferedFieldOpsND(Float64Field)
// Nd4j specialized field.
val nd4jField = Float64Field.nd4j
//viktor field
val viktorField = ViktorFieldND(dim, dim)
//parallel processing based on Java Streams
@ -45,35 +40,28 @@ fun main() {
measureAndPrint("Boxing addition") {
genericField {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
}
}
measureAndPrint("Specialized addition") {
doubleField {
var res: StructureND<Double> = one(shape)
repeat(n) { res += 1.0 }
}
}
measureAndPrint("Nd4j specialized addition") {
nd4jField {
var res: StructureND<Double> = one(shape)
var res: StructureND<Float64> = one(shape)
repeat(n) { res += 1.0 }
}
}
measureAndPrint("Viktor addition") {
viktorField {
var res: StructureND<Double> = one
var res: StructureND<Float64> = one
repeat(n) { res += 1.0 }
}
}
measureAndPrint("Parallel stream addition") {
parallelField {
var res: StructureND<Double> = one
var res: StructureND<Float64> = one
repeat(n) { res += 1.0 }
}
}

@ -19,21 +19,21 @@ import java.util.stream.IntStream
* execution.
*/
class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64Field>,
NumbersAddOps<StructureND<Double>>,
ExtendedField<StructureND<Double>> {
NumbersAddOps<StructureND<Float64>>,
ExtendedField<StructureND<Float64>> {
private val strides = ColumnStrides(shape)
override val elementAlgebra: Float64Field get() = Float64Field
override val zero: BufferND<Double> by lazy { structureND(shape) { zero } }
override val one: BufferND<Double> by lazy { structureND(shape) { one } }
override val zero: BufferND<Float64> by lazy { structureND(shape) { zero } }
override val one: BufferND<Float64> by lazy { structureND(shape) { one } }
override fun number(value: Number): BufferND<Double> {
override fun number(value: Number): BufferND<Float64> {
val d = value.toDouble() // minimize conversions
return structureND(shape) { d }
}
@OptIn(PerformancePitfall::class)
private val StructureND<Double>.buffer: Float64Buffer
private val StructureND<Float64>.buffer: Float64Buffer
get() = when {
shape != this@StreamDoubleFieldND.shape -> throw ShapeMismatchException(
this@StreamDoubleFieldND.shape,
@ -44,7 +44,7 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64
else -> Float64Buffer(strides.linearSize) { offset -> get(strides.index(offset)) }
}
override fun structureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): BufferND<Double> {
override fun structureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): BufferND<Float64> {
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
val index = strides.index(offset)
Float64Field.initializer(index)
@ -56,7 +56,7 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64
override fun mutableStructureND(
shape: ShapeND,
initializer: DoubleField.(IntArray) -> Double,
): MutableBufferND<Double> {
): MutableBufferND<Float64> {
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
val index = strides.index(offset)
DoubleField.initializer(index)
@ -66,17 +66,17 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64
}
@OptIn(PerformancePitfall::class)
override fun StructureND<Double>.map(
override fun StructureND<Float64>.map(
transform: Float64Field.(Double) -> Double,
): BufferND<Double> {
): BufferND<Float64> {
val array = Arrays.stream(buffer.array).parallel().map { Float64Field.transform(it) }.toArray()
return BufferND(strides, array.asBuffer())
}
@OptIn(PerformancePitfall::class)
override fun StructureND<Double>.mapIndexed(
override fun StructureND<Float64>.mapIndexed(
transform: Float64Field.(index: IntArray, Double) -> Double,
): BufferND<Double> {
): BufferND<Float64> {
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
Float64Field.transform(
strides.index(offset),
@ -89,39 +89,39 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64
@OptIn(PerformancePitfall::class)
override fun zip(
left: StructureND<Double>,
right: StructureND<Double>,
left: StructureND<Float64>,
right: StructureND<Float64>,
transform: Float64Field.(Double, Double) -> Double,
): BufferND<Double> {
): BufferND<Float64> {
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
Float64Field.transform(left.buffer.array[offset], right.buffer.array[offset])
}.toArray()
return BufferND(strides, array.asBuffer())
}
override fun StructureND<Double>.unaryMinus(): StructureND<Double> = map { -it }
override fun StructureND<Float64>.unaryMinus(): StructureND<Float64> = map { -it }
override fun scale(a: StructureND<Double>, value: Double): StructureND<Double> = a.map { it * value }
override fun scale(a: StructureND<Float64>, value: Double): StructureND<Float64> = a.map { it * value }
override fun power(arg: StructureND<Double>, pow: Number): BufferND<Double> = arg.map { power(it, pow) }
override fun power(arg: StructureND<Float64>, pow: Number): BufferND<Float64> = arg.map { power(it, pow) }
override fun exp(arg: StructureND<Double>): BufferND<Double> = arg.map { exp(it) }
override fun exp(arg: StructureND<Float64>): BufferND<Float64> = arg.map { exp(it) }
override fun ln(arg: StructureND<Double>): BufferND<Double> = arg.map { ln(it) }
override fun ln(arg: StructureND<Float64>): BufferND<Float64> = arg.map { ln(it) }
override fun sin(arg: StructureND<Double>): BufferND<Double> = arg.map { sin(it) }
override fun cos(arg: StructureND<Double>): BufferND<Double> = arg.map { cos(it) }
override fun tan(arg: StructureND<Double>): BufferND<Double> = arg.map { tan(it) }
override fun asin(arg: StructureND<Double>): BufferND<Double> = arg.map { asin(it) }
override fun acos(arg: StructureND<Double>): BufferND<Double> = arg.map { acos(it) }
override fun atan(arg: StructureND<Double>): BufferND<Double> = arg.map { atan(it) }
override fun sin(arg: StructureND<Float64>): BufferND<Float64> = arg.map { sin(it) }
override fun cos(arg: StructureND<Float64>): BufferND<Float64> = arg.map { cos(it) }
override fun tan(arg: StructureND<Float64>): BufferND<Float64> = arg.map { tan(it) }
override fun asin(arg: StructureND<Float64>): BufferND<Float64> = arg.map { asin(it) }
override fun acos(arg: StructureND<Float64>): BufferND<Float64> = arg.map { acos(it) }
override fun atan(arg: StructureND<Float64>): BufferND<Float64> = arg.map { atan(it) }
override fun sinh(arg: StructureND<Double>): BufferND<Double> = arg.map { sinh(it) }
override fun cosh(arg: StructureND<Double>): BufferND<Double> = arg.map { cosh(it) }
override fun tanh(arg: StructureND<Double>): BufferND<Double> = arg.map { tanh(it) }
override fun asinh(arg: StructureND<Double>): BufferND<Double> = arg.map { asinh(it) }
override fun acosh(arg: StructureND<Double>): BufferND<Double> = arg.map { acosh(it) }
override fun atanh(arg: StructureND<Double>): BufferND<Double> = arg.map { atanh(it) }
override fun sinh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { sinh(it) }
override fun cosh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { cosh(it) }
override fun tanh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { tanh(it) }
override fun asinh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { asinh(it) }
override fun acosh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { acosh(it) }
override fun atanh(arg: StructureND<Float64>): BufferND<Float64> = arg.map { atanh(it) }
}
fun Float64Field.ndStreaming(vararg shape: Int): StreamDoubleFieldND = StreamDoubleFieldND(ShapeND(shape))

@ -11,7 +11,7 @@ import space.kscience.kmath.operations.algebra
@OptIn(PerformancePitfall::class)
fun main(): Unit = with(Double.algebra.ndAlgebra) {
val structure: MutableStructure2D<Double> = mutableStructureND(ShapeND(2, 2)) { (i, j) ->
val structure: MutableStructure2D<Float64> = mutableStructureND(ShapeND(2, 2)) { (i, j) ->
i.toDouble() + j.toDouble()
}.as2D()

@ -12,6 +12,7 @@ import space.kscience.kmath.nd.MutableStructure2D
import space.kscience.kmath.nd.ShapeND
import space.kscience.kmath.nd.as2D
import space.kscience.kmath.nd.component1
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.tensors.LevenbergMarquardt.StartDataLm
import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra.zeros
import space.kscience.kmath.tensors.core.DoubleTensorAlgebra
@ -20,9 +21,9 @@ import space.kscience.kmath.tensors.core.levenbergMarquardt
import kotlin.random.Random
fun streamLm(
lm_func: (MutableStructure2D<Double>, MutableStructure2D<Double>, Int) -> (MutableStructure2D<Double>),
lm_func: (MutableStructure2D<Float64>, MutableStructure2D<Float64>, Int) -> (MutableStructure2D<Float64>),
startData: StartDataLm, launchFrequencyInMs: Long, numberOfLaunches: Int,
): Flow<MutableStructure2D<Double>> = flow {
): Flow<MutableStructure2D<Float64>> = flow {
var example_number = startData.example_number
var p_init = startData.p_init
@ -64,7 +65,7 @@ fun streamLm(
}
}
fun generateNewYDat(y_dat: MutableStructure2D<Double>, delta: Double): MutableStructure2D<Double> {
fun generateNewYDat(y_dat: MutableStructure2D<Float64>, delta: Double): MutableStructure2D<Float64> {
val n = y_dat.shape.component1()
val y_dat_new = zeros(ShapeND(intArrayOf(n, 1))).as2D()
for (i in 0 until n) {

@ -9,6 +9,7 @@ import space.kscience.kmath.nd.MutableStructure2D
import space.kscience.kmath.nd.ShapeND
import space.kscience.kmath.nd.as2D
import space.kscience.kmath.nd.component1
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra
import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra.div
import space.kscience.kmath.tensors.core.DoubleTensorAlgebra
@ -19,24 +20,24 @@ import space.kscience.kmath.tensors.core.DoubleTensorAlgebra.Companion.times
import space.kscience.kmath.tensors.core.asDoubleTensor
public data class StartDataLm(
var lm_matx_y_dat: MutableStructure2D<Double>,
var lm_matx_y_dat: MutableStructure2D<Float64>,
var example_number: Int,
var p_init: MutableStructure2D<Double>,
var t: MutableStructure2D<Double>,
var y_dat: MutableStructure2D<Double>,
var p_init: MutableStructure2D<Float64>,
var t: MutableStructure2D<Float64>,
var y_dat: MutableStructure2D<Float64>,
var weight: Double,
var dp: MutableStructure2D<Double>,
var p_min: MutableStructure2D<Double>,
var p_max: MutableStructure2D<Double>,
var consts: MutableStructure2D<Double>,
var dp: MutableStructure2D<Float64>,
var p_min: MutableStructure2D<Float64>,
var p_max: MutableStructure2D<Float64>,
var consts: MutableStructure2D<Float64>,
var opts: DoubleArray,
)
fun funcEasyForLm(
t: MutableStructure2D<Double>,
p: MutableStructure2D<Double>,
t: MutableStructure2D<Float64>,
p: MutableStructure2D<Float64>,
exampleNumber: Int,
): MutableStructure2D<Double> {
): MutableStructure2D<Float64> {
val m = t.shape.component1()
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1)))
@ -59,10 +60,10 @@ fun funcEasyForLm(
}
fun funcMiddleForLm(
t: MutableStructure2D<Double>,
p: MutableStructure2D<Double>,
t: MutableStructure2D<Float64>,
p: MutableStructure2D<Float64>,
exampleNumber: Int,
): MutableStructure2D<Double> {
): MutableStructure2D<Float64> {
val m = t.shape.component1()
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1)))
@ -79,10 +80,10 @@ fun funcMiddleForLm(
}
fun funcDifficultForLm(
t: MutableStructure2D<Double>,
p: MutableStructure2D<Double>,
t: MutableStructure2D<Float64>,
p: MutableStructure2D<Float64>,
exampleNumber: Int,
): MutableStructure2D<Double> {
): MutableStructure2D<Float64> {
val m = t.shape.component1()
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1)))

@ -10,12 +10,13 @@ import org.jetbrains.kotlinx.multik.api.ndarray
import org.jetbrains.kotlinx.multik.default.DefaultEngine
import space.kscience.kmath.multik.MultikDoubleAlgebra
import space.kscience.kmath.nd.one
import space.kscience.kmath.structures.Float64
val multikAlgebra = MultikDoubleAlgebra(DefaultEngine())
fun main(): Unit = with(multikAlgebra) {
val a = Multik.ndarray(intArrayOf(1, 2, 3)).asType<Double>().wrap()
val a = Multik.ndarray(intArrayOf(1, 2, 3)).asType<Float64>().wrap()
val b = Multik.ndarray(doubleArrayOf(1.0, 2.0, 3.0)).wrap()
one(a.shape) - a + b * 3.0
}

@ -2,13 +2,15 @@
# Copyright 2018-2021 KMath contributors.
# Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
#
kotlin.code.style=official
kotlin.mpp.stability.nowarn=true
kotlin.native.ignoreDisabledTargets=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx4096m
org.gradle.parallel=true
org.gradle.workers.max=4
toolsVersion=0.15.2-kotlin-1.9.22
#kotlin.experimental.tryK2=true
#kscience.wasm.disabled=true
kotlin.code.style=official
kotlin.mpp.stability.nowarn=true
kotlin.native.ignoreDisabledTargets=true
org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled
kotlin.native.enableKlibsCrossCompilation=true
toolsVersion=0.16.1-kotlin-2.1.0

28
gradle/libs.versions.toml Normal file

@ -0,0 +1,28 @@
[versions]
commons-rng = "1.6"
multik = "0.2.3"
nd4j = "1.0.0-M2.1"
tensorflow = "1.0.0"
[libraries]
attributes = "space.kscience:attributes-kt:0.3.0"
commons-math = "org.apache.commons:commons-math3:3.6.1"
commons-rng-simple = { module = "org.apache.commons:commons-rng-simple", version.ref = "commons-rng" }
commons-rng-sampling = { module = "org.apache.commons:commons-rng-sampling", version.ref = "commons-rng" }
multik-core = { module = "org.jetbrains.kotlinx:multik-core", version.ref = "multik" }
multik-default = { module = "org.jetbrains.kotlinx:multik-default", version.ref = "multik" }
nd4j-api = { module = "org.nd4j:nd4j-api", version.ref = "nd4j" }
nd4j-native-platform = { module = "org.nd4j:nd4j-native-platform", version.ref = "nd4j" }
ojalgo = "org.ojalgo:ojalgo:55.1.0"
tensorflow-core-api = {module = "org.tensorflow:tensorflow-core-api", version.ref="tensorflow"}
tensorflow-core-platform = {module = "org.tensorflow:tensorflow-core-platform", version.ref="tensorflow"}
[plugins]

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

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

@ -4,7 +4,24 @@ plugins {
kscience {
jvm()
js()
js{
nodejs {
testTask {
useMocha {
timeout = "0"
}
}
}
browser {
useCommonJs()
testTask {
useMocha {
timeout = "0"
}
}
}
}
native()
dependencies {
@ -18,30 +35,17 @@ kscience {
dependencies(jsMain) {
implementation(npm("astring", "1.7.5"))
implementation(npm("binaryen", "101.0.0"))
implementation(npm("binaryen", "117.0.0"))
implementation(npm("js-base64", "3.6.1"))
}
dependencies(jvmMain) {
implementation("org.ow2.asm:asm-commons:9.2")
implementation("org.ow2.asm:asm-commons:9.7.1")
}
}
kotlin {
js {
nodejs {
testTask {
useMocha().timeout = "0"
}
}
browser {
testTask {
useMocha().timeout = "0"
}
}
}
sourceSets {
filter { it.name.contains("test", true) }
@ -50,7 +54,7 @@ kotlin {
}
}
if (System.getProperty("space.kscience.kmath.ast.dump.generated.classes") == "1") {
if (project.properties["space.kscience.kmath.ast.dump.generated.classes"] == "1") {
tasks.withType<org.jetbrains.kotlin.gradle.targets.jvm.tasks.KotlinJvmTest> {
jvmArgs("-Dspace.kscience.kmath.ast.dump.generated.classes=1")
}

@ -9,6 +9,7 @@ import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.Int32Ring
import space.kscience.kmath.operations.Int8Ring
import space.kscience.kmath.operations.pi
import space.kscience.kmath.structures.Float64
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.fail
@ -41,7 +42,7 @@ internal class TestFolding {
@Test
fun foldSymbol() = assertEquals(
Float64Field.pi,
("pi".parseMath().evaluateConstants(Float64Field) as? TypedMst.Constant<Double> ?: fail()).value,
("pi".parseMath().evaluateConstants(Float64Field) as? TypedMst.Constant<Float64> ?: fail()).value,
)
@Test

@ -10,12 +10,13 @@ import space.kscience.kmath.expressions.MST
import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.Int32Ring
import space.kscience.kmath.structures.Float64
internal interface CompilerTestContext {
fun MST.compileToExpression(algebra: Int32Ring): Expression<Int>
fun MST.compile(algebra: Int32Ring, arguments: Map<Symbol, Int>): Int
fun MST.compile(algebra: Int32Ring, vararg arguments: Pair<Symbol, Int>): Int = compile(algebra, mapOf(*arguments))
fun MST.compileToExpression(algebra: Float64Field): Expression<Double>
fun MST.compileToExpression(algebra: Float64Field): Expression<Float64>
fun MST.compile(algebra: Float64Field, arguments: Map<Symbol, Double>): Double
fun MST.compile(algebra: Float64Field, vararg arguments: Pair<Symbol, Double>): Double =

@ -4,11 +4,6 @@
*/
@file:Suppress(
"INTERFACE_WITH_SUPERCLASS",
"OVERRIDING_FINAL_MEMBER",
"RETURN_TYPE_MISMATCH_ON_OVERRIDE",
"CONFLICTING_OVERLOADS",
"NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING",
"ObjectPropertyName",
"ClassName",
)

@ -4,10 +4,6 @@
*/
@file:Suppress(
"INTERFACE_WITH_SUPERCLASS",
"OVERRIDING_FINAL_MEMBER",
"RETURN_TYPE_MISMATCH_ON_OVERRIDE",
"CONFLICTING_OVERLOADS",
"PropertyName",
"ClassName", "ENUM_CLASS_IN_EXTERNAL_DECLARATION_WARNING",
)

@ -6,10 +6,6 @@
@file:JsQualifier("WebAssembly")
@file:Suppress(
"INTERFACE_WITH_SUPERCLASS",
"OVERRIDING_FINAL_MEMBER",
"RETURN_TYPE_MISMATCH_ON_OVERRIDE",
"NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING",
"ClassName",
)
@ -22,78 +18,34 @@ import org.w3c.fetch.Response
import space.kscience.kmath.internal.tsstdlib.PromiseLike
import kotlin.js.Promise
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface CompileError {
companion object {
var prototype: CompileError
}
}
internal external interface CompileError
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface Global {
var value: Any
fun valueOf(): Any
companion object {
var prototype: Global
}
}
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
@JsName("Instance")
internal external interface Instance1 {
var exports: Exports
companion object {
var prototype: Instance
}
}
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface LinkError {
companion object {
var prototype: LinkError
}
}
internal external interface LinkError
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface Memory {
var buffer: ArrayBuffer
fun grow(delta: Number): Number
companion object {
var prototype: Memory
}
}
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
@JsName("Module")
internal external interface Module1 {
companion object {
var prototype: Module
fun customSections(moduleObject: Module, sectionName: String): Array<ArrayBuffer>
fun exports(moduleObject: Module): Array<ModuleExportDescriptor>
fun imports(moduleObject: Module): Array<ModuleImportDescriptor>
}
}
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface RuntimeError {
companion object {
var prototype: RuntimeError
}
}
internal external interface RuntimeError
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
internal external interface Table {
var length: Number
fun get(index: Number): Function<*>?
fun grow(delta: Number): Number
fun set(index: Number, value: Function<*>?)
companion object {
var prototype: Table
}
}
internal external interface GlobalDescriptor {

@ -3,13 +3,6 @@
* 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(
"INTERFACE_WITH_SUPERCLASS",
"OVERRIDING_FINAL_MEMBER",
"RETURN_TYPE_MISMATCH_ON_OVERRIDE",
"CONFLICTING_OVERLOADS",
"NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING",
)
package space.kscience.kmath.internal.webassembly

@ -11,6 +11,7 @@ import space.kscience.kmath.expressions.*
import space.kscience.kmath.internal.binaryen.*
import space.kscience.kmath.internal.webassembly.Instance
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.internal.binaryen.Module as BinaryenModule
import space.kscience.kmath.internal.webassembly.Module as WasmModule
@ -85,13 +86,13 @@ internal sealed class WasmBuilder<T : Number, out E : Expression<T>>(
}
@UnstableKMathAPI
internal class DoubleWasmBuilder(target: TypedMst<Double>) :
internal class DoubleWasmBuilder(target: TypedMst<Float64>) :
WasmBuilder<Double, DoubleExpression>(f64, Float64Field, target) {
override val instance by lazy {
object : DoubleExpression {
override val indexer = SimpleSymbolIndexer(keys)
override fun invoke(arguments: DoubleArray) = spreader(executable, arguments).unsafeCast<Double>()
override fun invoke(arguments: DoubleArray) = spreader(executable, arguments).unsafeCast<Float64>()
}
}
@ -99,7 +100,7 @@ internal class DoubleWasmBuilder(target: TypedMst<Double>) :
override fun visitNumber(number: Number) = ctx.f64.const(number.toDouble())
override fun visitUnary(node: TypedMst.Unary<Double>): ExpressionRef = when (node.operation) {
override fun visitUnary(node: TypedMst.Unary<Float64>): ExpressionRef = when (node.operation) {
GroupOps.MINUS_OPERATION -> ctx.f64.neg(visit(node.value))
GroupOps.PLUS_OPERATION -> visit(node.value)
PowerOperations.SQRT_OPERATION -> ctx.f64.sqrt(visit(node.value))
@ -120,7 +121,7 @@ internal class DoubleWasmBuilder(target: TypedMst<Double>) :
else -> super.visitUnary(node)
}
override fun visitBinary(mst: TypedMst.Binary<Double>): ExpressionRef = when (mst.operation) {
override fun visitBinary(mst: TypedMst.Binary<Float64>): ExpressionRef = when (mst.operation) {
GroupOps.PLUS_OPERATION -> ctx.f64.add(visit(mst.left), visit(mst.right))
GroupOps.MINUS_OPERATION -> ctx.f64.sub(visit(mst.left), visit(mst.right))
RingOps.TIMES_OPERATION -> ctx.f64.mul(visit(mst.left), visit(mst.right))

@ -13,6 +13,7 @@ import space.kscience.kmath.ast.evaluateConstants
import space.kscience.kmath.expressions.*
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.Int32Ring
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.wasm.internal.DoubleWasmBuilder
import space.kscience.kmath.wasm.internal.IntWasmBuilder
@ -58,7 +59,7 @@ public fun MST.compile(algebra: Int32Ring, vararg arguments: Pair<Symbol, Int>):
* @author Iaroslav Postovalov
*/
@UnstableKMathAPI
public fun MST.compileToExpression(algebra: Float64Field): Expression<Double> {
public fun MST.compileToExpression(algebra: Float64Field): Expression<Float64> {
val typed = evaluateConstants(algebra)
return if (typed is TypedMst.Constant) object : DoubleExpression {

@ -13,6 +13,7 @@ import space.kscience.kmath.expressions.MST
import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.Int32Ring
import space.kscience.kmath.structures.Float64
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import space.kscience.kmath.estree.compile as estreeCompile
@ -21,19 +22,19 @@ import space.kscience.kmath.wasm.compile as wasmCompile
import space.kscience.kmath.wasm.compileToExpression as wasmCompileToExpression
@OptIn(UnstableKMathAPI::class)
private object WasmCompilerTestContext : CompilerTestContext {
internal object WasmCompilerTestContext : CompilerTestContext {
override fun MST.compileToExpression(algebra: Int32Ring): Expression<Int> = wasmCompileToExpression(algebra)
override fun MST.compile(algebra: Int32Ring, arguments: Map<Symbol, Int>): Int = wasmCompile(algebra, arguments)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Double> = wasmCompileToExpression(algebra)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Float64> = wasmCompileToExpression(algebra)
override fun MST.compile(algebra: Float64Field, arguments: Map<Symbol, Double>): Double =
wasmCompile(algebra, arguments)
}
private object ESTreeCompilerTestContext : CompilerTestContext {
internal object ESTreeCompilerTestContext : CompilerTestContext {
override fun MST.compileToExpression(algebra: Int32Ring): Expression<Int> = estreeCompileToExpression(algebra)
override fun MST.compile(algebra: Int32Ring, arguments: Map<Symbol, Int>): Int = estreeCompile(algebra, arguments)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Double> = estreeCompileToExpression(algebra)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Float64> = estreeCompileToExpression(algebra)
override fun MST.compile(algebra: Float64Field, arguments: Map<Symbol, Double>): Double =
estreeCompile(algebra, arguments)

@ -15,6 +15,7 @@ import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.ast.TypedMst
import space.kscience.kmath.expressions.*
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Float64
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.nio.file.Paths
@ -74,7 +75,7 @@ internal sealed class PrimitiveAsmBuilder<T : Number, out E : Expression<T>>(
val instance: E by lazy {
val classWriter = ClassWriter(ClassWriter.COMPUTE_FRAMES) {
visit(
V1_8,
V11,
ACC_PUBLIC or ACC_FINAL or ACC_SUPER,
classType.internalName,
"${OBJECT_TYPE.descriptor}${expressionParentType.descriptor}",
@ -371,17 +372,17 @@ internal sealed class PrimitiveAsmBuilder<T : Number, out E : Expression<T>>(
/**
* ASM type for [java.lang.Number].
*/
val NUMBER_TYPE: Type = getObjectType("java/lang/Number")
val NUMBER_TYPE: Type = getType(Number::class.java)
/**
* ASM type for [SymbolIndexer].
*/
val SYMBOL_INDEXER_TYPE: Type = getObjectType("space/kscience/kmath/expressions/SymbolIndexer")
val SYMBOL_INDEXER_TYPE: Type = getType(SymbolIndexer::class.java)
}
}
@UnstableKMathAPI
internal class DoubleAsmBuilder(target: TypedMst<Double>) : PrimitiveAsmBuilder<Double, DoubleExpression>(
internal class DoubleAsmBuilder(target: TypedMst<Float64>) : PrimitiveAsmBuilder<Double, DoubleExpression>(
Float64Field,
java.lang.Double::class.java,
java.lang.Double.TYPE,
@ -410,7 +411,7 @@ internal class DoubleAsmBuilder(target: TypedMst<Double>) : PrimitiveAsmBuilder<
false,
)
override fun visitUnary(node: TypedMst.Unary<Double>) {
override fun visitUnary(node: TypedMst.Unary<Float64>) {
super.visitUnary(node)
when (node.operation) {
@ -435,7 +436,7 @@ internal class DoubleAsmBuilder(target: TypedMst<Double>) : PrimitiveAsmBuilder<
}
}
override fun visitBinary(node: TypedMst.Binary<Double>) {
override fun visitBinary(node: TypedMst.Binary<Float64>) {
super.visitBinary(node)
when (node.operation) {

@ -73,7 +73,6 @@ internal tailrec fun buildName(marker: String, collision: Int = 0): String {
return buildName(marker, collision + 1)
}
@Suppress("FunctionName")
internal inline fun ClassWriter(flags: Int, block: ClassWriter.() -> Unit): ClassWriter {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return ClassWriter(flags).apply(block)

@ -12,8 +12,7 @@ import space.kscience.kmath.expressions.Symbol
import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.Int32Ring
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.asm.compile as asmCompile
import space.kscience.kmath.asm.compileToExpression as asmCompileToExpression
@ -24,18 +23,18 @@ private object GenericAsmCompilerTestContext : CompilerTestContext {
override fun MST.compile(algebra: Int32Ring, arguments: Map<Symbol, Int>): Int =
asmCompile(algebra as Algebra<Int>, arguments)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Double> =
asmCompileToExpression(algebra as Algebra<Double>)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Float64> =
asmCompileToExpression(algebra as Algebra<Float64>)
override fun MST.compile(algebra: Float64Field, arguments: Map<Symbol, Double>): Double =
asmCompile(algebra as Algebra<Double>, arguments)
asmCompile(algebra as Algebra<Float64>, arguments)
}
@OptIn(UnstableKMathAPI::class)
private object PrimitiveAsmCompilerTestContext : CompilerTestContext {
override fun MST.compileToExpression(algebra: Int32Ring): Expression<Int> = asmCompileToExpression(algebra)
override fun MST.compile(algebra: Int32Ring, arguments: Map<Symbol, Int>): Int = asmCompile(algebra, arguments)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Double> = asmCompileToExpression(algebra)
override fun MST.compileToExpression(algebra: Float64Field): Expression<Float64> = asmCompileToExpression(algebra)
override fun MST.compile(algebra: Float64Field, arguments: Map<Symbol, Double>): Double =
asmCompile(algebra, arguments)
@ -43,7 +42,6 @@ private object PrimitiveAsmCompilerTestContext : CompilerTestContext {
internal actual inline fun runCompilerTest(action: CompilerTestContext.() -> Unit) {
contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
action(GenericAsmCompilerTestContext)
action(PrimitiveAsmCompilerTestContext)
}

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

@ -13,7 +13,7 @@ kscience {
api(projects.kmathOptimization)
api(projects.kmathStat)
api(projects.kmathFunctions)
api("org.apache.commons:commons-math3:3.6.1")
api(libs.commons.math)
}
}

@ -14,6 +14,7 @@ import space.kscience.kmath.expressions.*
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.ExtendedField
import space.kscience.kmath.operations.NumbersAddOps
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.MutableBufferFactory
/**
@ -132,9 +133,9 @@ public object CmDsProcessor : AutoDiffProcessor<Double, DerivativeStructure, CmD
@Deprecated("Use generic DSAlgebra from the core")
public class CmDsExpression(
public val function: CmDsField.() -> DerivativeStructure,
) : DifferentiableExpression<Double> {
) : DifferentiableExpression<Float64> {
override val type: SafeType<Double> get() = DoubleField.type
override val type: SafeType<Float64> get() = DoubleField.type
override operator fun invoke(arguments: Map<Symbol, Double>): Double =
CmDsField(0, arguments).function().value
@ -142,7 +143,7 @@ public class CmDsExpression(
/**
* Get the derivative expression with given orders
*/
override fun derivativeOrNull(symbols: List<Symbol>): Expression<Double> = Expression(type) { arguments ->
override fun derivativeOrNull(symbols: List<Symbol>): Expression<Float64> = Expression(type) { arguments ->
with(CmDsField(symbols.size, arguments)) { function().derivative(symbols) }
}
}

@ -7,6 +7,7 @@ package space.kscience.kmath.commons.integration
import org.apache.commons.math3.analysis.integration.gauss.GaussIntegrator
import org.apache.commons.math3.analysis.integration.gauss.GaussIntegratorFactory
import space.kscience.kmath.integration.*
import space.kscience.kmath.structures.Float64
/**
* A simple one-pass integrator based on Gauss rule
@ -14,9 +15,9 @@ import space.kscience.kmath.integration.*
public class CMGaussRuleIntegrator(
private val numpoints: Int,
private var type: GaussRule = GaussRule.LEGENDRE,
) : UnivariateIntegrator<Double> {
) : UnivariateIntegrator<Float64> {
override fun integrate(integrand: UnivariateIntegrand<Double>): UnivariateIntegrand<Double> {
override fun integrate(integrand: UnivariateIntegrand<Float64>): UnivariateIntegrand<Float64> {
val range = integrand[IntegrationRange]
?: error("Integration range is not provided")
val integrator: GaussIntegrator = getIntegrator(range)
@ -28,7 +29,7 @@ public class CMGaussRuleIntegrator(
}
}
private fun getIntegrator(range: ClosedRange<Double>): GaussIntegrator {
private fun getIntegrator(range: ClosedRange<Float64>): GaussIntegrator {
return when (type) {
GaussRule.LEGENDRE -> factory.legendre(
numpoints,
@ -77,7 +78,7 @@ public class CMGaussRuleIntegrator(
private val factory: GaussIntegratorFactory = GaussIntegratorFactory()
public fun integrate(
range: ClosedRange<Double>,
range: ClosedRange<Float64>,
numPoints: Int = 100,
type: GaussRule = GaussRule.LEGENDRE,
function: (Double) -> Double,

@ -10,6 +10,7 @@ import org.apache.commons.math3.analysis.integration.SimpsonIntegrator
import space.kscience.attributes.Attributes
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.integration.*
import space.kscience.kmath.structures.Float64
import org.apache.commons.math3.analysis.integration.UnivariateIntegrator as CMUnivariateIntegrator
/**
@ -17,10 +18,10 @@ import org.apache.commons.math3.analysis.integration.UnivariateIntegrator as CMU
*/
public class CMIntegrator(
private val defaultMaxCalls: Int = 200,
public val integratorBuilder: (Integrand<Double>) -> CMUnivariateIntegrator,
) : UnivariateIntegrator<Double> {
public val integratorBuilder: (Integrand<Float64>) -> CMUnivariateIntegrator,
) : UnivariateIntegrator<Float64> {
override fun integrate(integrand: UnivariateIntegrand<Double>): UnivariateIntegrand<Double> {
override fun integrate(integrand: UnivariateIntegrand<Float64>): UnivariateIntegrand<Float64> {
val integrator = integratorBuilder(integrand)
val maxCalls = integrand[IntegrandMaxCalls] ?: defaultMaxCalls
val remainingCalls = maxCalls - integrand.calls

@ -0,0 +1,167 @@
/*
* Copyright 2018-2024 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.commons.linear
import org.apache.commons.math3.linear.*
import space.kscience.attributes.SafeType
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.*
import space.kscience.kmath.linear.CholeskyDecomposition
import space.kscience.kmath.linear.EigenDecomposition
import space.kscience.kmath.linear.QRDecomposition
import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.nd.StructureAttribute
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.IntBuffer
import space.kscience.kmath.structures.asBuffer
@JvmInline
public value class CMMatrix(public val cmMatrix: RealMatrix) : Matrix<Float64> {
override val rowNum: Int get() = cmMatrix.rowDimension
override val colNum: Int get() = cmMatrix.columnDimension
override operator fun get(i: Int, j: Int): Double = cmMatrix.getEntry(i, j)
}
@JvmInline
public value class CMVector(public val cmVector: RealVector) : Point<Float64> {
override val size: Int get() = cmVector.dimension
override operator fun get(index: Int): Double = cmVector.getEntry(index)
override operator fun iterator(): Iterator<Float64> = cmVector.toArray().iterator()
override fun toString(): String = Buffer.toString(this)
}
public object CMLinearSpace : LinearSpace<Double, Float64Field> {
override val elementAlgebra: Float64Field get() = Float64Field
override val type: SafeType<Float64> get() = DoubleField.type
override fun buildMatrix(
rows: Int,
columns: Int,
initializer: Float64Field.(i: Int, j: Int) -> Double,
): CMMatrix {
val array = Array(rows) { i -> DoubleArray(columns) { j -> Float64Field.initializer(i, j) } }
return CMMatrix(Array2DRowRealMatrix(array))
}
@OptIn(UnstableKMathAPI::class)
public fun Matrix<Float64>.toCM(): RealMatrix = when (val matrix = origin) {
is CMMatrix -> matrix.cmMatrix
else -> {
//TODO add feature analysis
val array = Array(rowNum) { i -> DoubleArray(colNum) { j -> get(i, j) } }
Array2DRowRealMatrix(array)
}
}
public fun Point<Float64>.toCM(): RealVector = if (this is CMVector) cmVector else {
val array = DoubleArray(size) { get(it) }
ArrayRealVector(array)
}
public fun RealMatrix.asMatrix(): CMMatrix = CMMatrix(this)
public fun RealVector.asVector(): CMVector = CMVector(this)
override fun buildVector(size: Int, initializer: Float64Field.(Int) -> Double): Point<Float64> =
ArrayRealVector(DoubleArray(size) { Float64Field.initializer(it) }).asVector()
override fun Matrix<Float64>.plus(other: Matrix<Float64>): CMMatrix =
toCM().add(other.toCM()).asMatrix()
override fun Point<Float64>.plus(other: Point<Float64>): CMVector =
toCM().add(other.toCM()).asVector()
override fun Point<Float64>.minus(other: Point<Float64>): CMVector =
toCM().subtract(other.toCM()).asVector()
override fun Matrix<Float64>.dot(other: Matrix<Float64>): CMMatrix =
toCM().multiply(other.toCM()).asMatrix()
override fun Matrix<Float64>.dot(vector: Point<Float64>): CMVector =
toCM().preMultiply(vector.toCM()).asVector()
override operator fun Matrix<Float64>.minus(other: Matrix<Float64>): CMMatrix =
toCM().subtract(other.toCM()).asMatrix()
override operator fun Matrix<Float64>.times(value: Double): CMMatrix =
toCM().scalarMultiply(value).asMatrix()
override fun Double.times(m: Matrix<Float64>): CMMatrix =
m * this
override fun Point<Float64>.times(value: Double): CMVector =
toCM().mapMultiply(value).asVector()
override fun Double.times(v: Point<Float64>): CMVector =
v * this
@OptIn(UnstableKMathAPI::class)
override fun <V, A : StructureAttribute<V>> computeAttribute(structure: Structure2D<Float64>, attribute: A): V? {
val origin = structure.toCM()
val raw: Any? = when (attribute) {
IsDiagonal -> if (origin is DiagonalMatrix) Unit else null
Determinant -> org.apache.commons.math3.linear.LUDecomposition(origin).determinant
Inverted -> org.apache.commons.math3.linear.LUDecomposition(origin).solver.inverse.asMatrix()
LUP -> object : LupDecomposition<Float64> {
val lup by lazy { org.apache.commons.math3.linear.LUDecomposition(origin) }
override val pivot: IntBuffer get() = lup.pivot.asBuffer()
override val l: Matrix<Float64> get() = lup.l.asMatrix().withAttribute(LowerTriangular)
override val u: Matrix<Float64> get() = lup.u.asMatrix().withAttribute(UpperTriangular)
}
Cholesky -> object : CholeskyDecomposition<Float64> {
val cmCholesky by lazy { org.apache.commons.math3.linear.CholeskyDecomposition(origin) }
override val l: Matrix<Float64> get() = cmCholesky.l.asMatrix()
}
QR -> object : QRDecomposition<Float64> {
val cmQr by lazy { org.apache.commons.math3.linear.QRDecomposition(origin) }
override val q: Matrix<Float64> get() = cmQr.q.asMatrix().withAttribute(OrthogonalAttribute)
override val r: Matrix<Float64> get() = cmQr.r.asMatrix().withAttribute(UpperTriangular)
}
SVD -> object : space.kscience.kmath.linear.SingularValueDecomposition<Float64> {
val cmSvd by lazy { org.apache.commons.math3.linear.SingularValueDecomposition(origin) }
override val u: Matrix<Float64> get() = cmSvd.u.asMatrix()
override val s: Matrix<Float64> get() = cmSvd.s.asMatrix()
override val v: Matrix<Float64> get() = cmSvd.v.asMatrix()
override val singularValues: Point<Float64> get() = cmSvd.singularValues.asBuffer()
}
EIG -> object : EigenDecomposition<Float64> {
val cmEigen by lazy { org.apache.commons.math3.linear.EigenDecomposition(origin) }
override val v: Matrix<Float64> get() = cmEigen.v.asMatrix()
override val d: Matrix<Float64> get() = cmEigen.d.asMatrix()
}
else -> null
}
@Suppress("UNCHECKED_CAST")
return raw as V?
}
}
public operator fun CMMatrix.plus(other: CMMatrix): CMMatrix = CMMatrix(cmMatrix.add(other.cmMatrix))
public operator fun CMMatrix.minus(other: CMMatrix): CMMatrix = CMMatrix(cmMatrix.subtract(other.cmMatrix))
public infix fun CMMatrix.dot(other: CMMatrix): CMMatrix = CMMatrix(cmMatrix.multiply(other.cmMatrix))

@ -1,159 +0,0 @@
/*
* Copyright 2018-2024 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.commons.linear
import org.apache.commons.math3.linear.*
import org.apache.commons.math3.linear.LUDecomposition
import org.apache.commons.math3.linear.SingularValueDecomposition
import space.kscience.attributes.SafeType
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.*
import space.kscience.kmath.linear.CholeskyDecomposition
import space.kscience.kmath.linear.QRDecomposition
import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.nd.StructureAttribute
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.IntBuffer
import space.kscience.kmath.structures.asBuffer
public class CMMatrix(public val origin: RealMatrix) : Matrix<Double> {
override val rowNum: Int get() = origin.rowDimension
override val colNum: Int get() = origin.columnDimension
override operator fun get(i: Int, j: Int): Double = origin.getEntry(i, j)
}
@JvmInline
public value class CMVector(public val origin: RealVector) : Point<Double> {
override val size: Int get() = origin.dimension
override operator fun get(index: Int): Double = origin.getEntry(index)
override operator fun iterator(): Iterator<Double> = origin.toArray().iterator()
override fun toString(): String = Buffer.toString(this)
}
public fun RealVector.toPoint(): CMVector = CMVector(this)
public object CMLinearSpace : LinearSpace<Double, Float64Field> {
override val elementAlgebra: Float64Field get() = Float64Field
override val type: SafeType<Double> get() = DoubleField.type
override fun buildMatrix(
rows: Int,
columns: Int,
initializer: Float64Field.(i: Int, j: Int) -> Double,
): CMMatrix {
val array = Array(rows) { i -> DoubleArray(columns) { j -> Float64Field.initializer(i, j) } }
return CMMatrix(Array2DRowRealMatrix(array))
}
@OptIn(UnstableKMathAPI::class)
public fun Matrix<Double>.toCM(): CMMatrix = when (val matrix = origin) {
is CMMatrix -> matrix
else -> {
//TODO add feature analysis
val array = Array(rowNum) { i -> DoubleArray(colNum) { j -> get(i, j) } }
Array2DRowRealMatrix(array).wrap()
}
}
public fun Point<Double>.toCM(): CMVector = if (this is CMVector) this else {
val array = DoubleArray(size) { this[it] }
ArrayRealVector(array).wrap()
}
internal fun RealMatrix.wrap(): CMMatrix = CMMatrix(this)
internal fun RealVector.wrap(): CMVector = CMVector(this)
override fun buildVector(size: Int, initializer: Float64Field.(Int) -> Double): Point<Double> =
ArrayRealVector(DoubleArray(size) { Float64Field.initializer(it) }).wrap()
override fun Matrix<Double>.plus(other: Matrix<Double>): CMMatrix =
toCM().origin.add(other.toCM().origin).wrap()
override fun Point<Double>.plus(other: Point<Double>): CMVector =
toCM().origin.add(other.toCM().origin).wrap()
override fun Point<Double>.minus(other: Point<Double>): CMVector =
toCM().origin.subtract(other.toCM().origin).wrap()
override fun Matrix<Double>.dot(other: Matrix<Double>): CMMatrix =
toCM().origin.multiply(other.toCM().origin).wrap()
override fun Matrix<Double>.dot(vector: Point<Double>): CMVector =
toCM().origin.preMultiply(vector.toCM().origin).wrap()
override operator fun Matrix<Double>.minus(other: Matrix<Double>): CMMatrix =
toCM().origin.subtract(other.toCM().origin).wrap()
override operator fun Matrix<Double>.times(value: Double): CMMatrix =
toCM().origin.scalarMultiply(value).wrap()
override fun Double.times(m: Matrix<Double>): CMMatrix =
m * this
override fun Point<Double>.times(value: Double): CMVector =
toCM().origin.mapMultiply(value).wrap()
override fun Double.times(v: Point<Double>): CMVector =
v * this
override fun <V, A : StructureAttribute<V>> computeAttribute(structure: Structure2D<Double>, attribute: A): V? {
val origin = structure.toCM().origin
val raw: Any? = when (attribute) {
IsDiagonal -> if (origin is DiagonalMatrix) Unit else null
Determinant -> LUDecomposition(origin).determinant
LUP -> object : LupDecomposition<Float64> {
val lup by lazy { LUDecomposition(origin) }
override val pivot: IntBuffer get() = lup.pivot.asBuffer()
override val l: Matrix<Float64> get() = lup.l.wrap()
override val u: Matrix<Float64> get() = lup.u.wrap()
}
Cholesky -> object : CholeskyDecomposition<Float64> {
val cmCholesky by lazy { org.apache.commons.math3.linear.CholeskyDecomposition(origin) }
override val l: Matrix<Double> get() = cmCholesky.l.wrap()
}
QR -> object : QRDecomposition<Float64> {
val cmQr by lazy { org.apache.commons.math3.linear.QRDecomposition(origin) }
override val q: Matrix<Float64> get() = cmQr.q.wrap().withAttribute(OrthogonalAttribute)
override val r: Matrix<Float64> get() = cmQr.r.wrap().withAttribute(UpperTriangular)
}
SVD -> object : space.kscience.kmath.linear.SingularValueDecomposition<Float64> {
val cmSvd by lazy { SingularValueDecomposition(origin) }
override val u: Matrix<Float64> get() = cmSvd.u.wrap()
override val s: Matrix<Float64> get() = cmSvd.s.wrap()
override val v: Matrix<Float64> get() = cmSvd.v.wrap()
override val singularValues: Point<Float64> get() = cmSvd.singularValues.asBuffer()
}
else -> null
}
@Suppress("UNCHECKED_CAST")
return raw as V?
}
}
public operator fun CMMatrix.plus(other: CMMatrix): CMMatrix = CMMatrix(origin.add(other.origin))
public operator fun CMMatrix.minus(other: CMMatrix): CMMatrix = CMMatrix(origin.subtract(other.origin))
public infix fun CMMatrix.dot(other: CMMatrix): CMMatrix = CMMatrix(origin.multiply(other.origin))

@ -9,6 +9,7 @@ import org.apache.commons.math3.linear.*
import space.kscience.kmath.linear.LinearSolver
import space.kscience.kmath.linear.Matrix
import space.kscience.kmath.linear.Point
import space.kscience.kmath.structures.Float64
public enum class CMDecomposition {
LUP,
@ -18,43 +19,44 @@ public enum class CMDecomposition {
CHOLESKY
}
private fun CMLinearSpace.solver(
a: Matrix<Double>,
private fun CMLinearSpace.cmSolver(
a: Matrix<Float64>,
decomposition: CMDecomposition = CMDecomposition.LUP,
): DecompositionSolver = when (decomposition) {
CMDecomposition.LUP -> LUDecomposition(a.toCM().origin).solver
CMDecomposition.RRQR -> RRQRDecomposition(a.toCM().origin).solver
CMDecomposition.QR -> QRDecomposition(a.toCM().origin).solver
CMDecomposition.EIGEN -> EigenDecomposition(a.toCM().origin).solver
CMDecomposition.CHOLESKY -> CholeskyDecomposition(a.toCM().origin).solver
CMDecomposition.LUP -> LUDecomposition(a.toCM()).solver
CMDecomposition.RRQR -> RRQRDecomposition(a.toCM()).solver
CMDecomposition.QR -> QRDecomposition(a.toCM()).solver
CMDecomposition.EIGEN -> EigenDecomposition(a.toCM()).solver
CMDecomposition.CHOLESKY -> CholeskyDecomposition(a.toCM()).solver
}
public fun CMLinearSpace.solve(
a: Matrix<Double>,
b: Matrix<Double>,
a: Matrix<Float64>,
b: Matrix<Float64>,
decomposition: CMDecomposition = CMDecomposition.LUP,
): CMMatrix = solver(a, decomposition).solve(b.toCM().origin).wrap()
): CMMatrix = cmSolver(a, decomposition).solve(b.toCM()).asMatrix()
public fun CMLinearSpace.solve(
a: Matrix<Double>,
b: Point<Double>,
a: Matrix<Float64>,
b: Point<Float64>,
decomposition: CMDecomposition = CMDecomposition.LUP,
): CMVector = solver(a, decomposition).solve(b.toCM().origin).toPoint()
): CMVector = cmSolver(a, decomposition).solve(b.toCM()).asVector()
public fun CMLinearSpace.inverse(
a: Matrix<Double>,
a: Matrix<Float64>,
decomposition: CMDecomposition = CMDecomposition.LUP,
): CMMatrix = solver(a, decomposition).inverse.wrap()
): CMMatrix = cmSolver(a, decomposition).inverse.asMatrix()
public fun CMLinearSpace.solver(decomposition: CMDecomposition): LinearSolver<Double> = object : LinearSolver<Double> {
override fun solve(a: Matrix<Double>, b: Matrix<Double>): Matrix<Double> =
solver(a, decomposition).solve(b.toCM().origin).wrap()
public fun CMLinearSpace.solver(decomposition: CMDecomposition): LinearSolver<Float64> =
object : LinearSolver<Float64> {
override fun solve(a: Matrix<Float64>, b: Matrix<Float64>): Matrix<Float64> =
cmSolver(a, decomposition).solve(b.toCM()).asMatrix()
override fun solve(a: Matrix<Double>, b: Point<Double>): Point<Double> =
solver(a, decomposition).solve(b.toCM().origin).toPoint()
override fun solve(a: Matrix<Float64>, b: Point<Float64>): Point<Float64> =
cmSolver(a, decomposition).solve(b.toCM()).asVector()
override fun inverse(matrix: Matrix<Double>): Matrix<Double> = solver(matrix, decomposition).inverse.wrap()
}
override fun inverse(matrix: Matrix<Float64>): Matrix<Float64> = cmSolver(matrix, decomposition).inverse.asMatrix()
}
public fun CMLinearSpace.lupSolver(): LinearSolver<Double> = solver((CMDecomposition.LUP))
public fun CMLinearSpace.lupSolver(): LinearSolver<Float64> = solver((CMDecomposition.LUP))

@ -22,7 +22,7 @@ import space.kscience.kmath.expressions.SymbolIndexer
import space.kscience.kmath.expressions.derivative
import space.kscience.kmath.expressions.withSymbols
import space.kscience.kmath.optimization.*
import kotlin.collections.set
import space.kscience.kmath.structures.Float64
import kotlin.reflect.KClass
public operator fun PointValuePair.component1(): DoubleArray = point
@ -33,8 +33,8 @@ public object CMOptimizerEngine : OptimizationAttribute<() -> MultivariateOptimi
/**
* Specify a Commons-maths optimization engine
*/
public fun AttributesBuilder<FunctionOptimization<Double>>.cmEngine(optimizerBuilder: () -> MultivariateOptimizer) {
set(CMOptimizerEngine, optimizerBuilder)
public fun AttributesBuilder<FunctionOptimization<Float64>>.cmEngine(optimizerBuilder: () -> MultivariateOptimizer) {
CMOptimizerEngine(optimizerBuilder)
}
public object CMOptimizerData : SetAttribute<SymbolIndexer.() -> OptimizationData>
@ -42,18 +42,18 @@ public object CMOptimizerData : SetAttribute<SymbolIndexer.() -> OptimizationDat
/**
* Specify Commons-maths optimization data.
*/
public fun AttributesBuilder<FunctionOptimization<Double>>.cmOptimizationData(data: SymbolIndexer.() -> OptimizationData) {
public fun AttributesBuilder<FunctionOptimization<Float64>>.cmOptimizationData(data: SymbolIndexer.() -> OptimizationData) {
CMOptimizerData add data
}
public fun AttributesBuilder<FunctionOptimization<Double>>.simplexSteps(vararg steps: Pair<Symbol, Double>) {
public fun AttributesBuilder<FunctionOptimization<Float64>>.simplexSteps(vararg steps: Pair<Symbol, Double>) {
//TODO use convergence checker from features
cmEngine { SimplexOptimizer(CMOptimizer.defaultConvergenceChecker) }
cmOptimizationData { NelderMeadSimplex(mapOf(*steps).toDoubleArray()) }
}
@OptIn(UnstableKMathAPI::class)
public object CMOptimizer : Optimizer<Double, FunctionOptimization<Double>> {
public object CMOptimizer : Optimizer<Double, FunctionOptimization<Float64>> {
public const val DEFAULT_RELATIVE_TOLERANCE: Double = 1e-4
public const val DEFAULT_ABSOLUTE_TOLERANCE: Double = 1e-4
@ -67,12 +67,12 @@ public object CMOptimizer : Optimizer<Double, FunctionOptimization<Double>> {
override suspend fun optimize(
problem: FunctionOptimization<Double>,
): FunctionOptimization<Double> {
problem: FunctionOptimization<Float64>,
): FunctionOptimization<Float64> {
val startPoint = problem.startPoint
val parameters = problem.attributes[OptimizationParameters]
?: problem.attributes[OptimizationStartPoint<Double>()]?.keys
?: problem.attributes[OptimizationStartPoint<Float64>()]?.keys
?: startPoint.keys

@ -77,7 +77,7 @@ public fun Flow<Buffer<Complex>>.fft(
}
@JvmName("realFFT")
public fun Flow<Buffer<Double>>.fft(
public fun Flow<Buffer<Float64>>.fft(
normalization: DftNormalization = DftNormalization.STANDARD,
direction: TransformType = TransformType.FORWARD,
): Flow<Buffer<Complex>> {
@ -89,7 +89,7 @@ public fun Flow<Buffer<Double>>.fft(
* Process a continuous flow of real numbers in FFT splitting it in chunks of [bufferSize].
*/
@JvmName("realFFT")
public fun Flow<Double>.fft(
public fun Flow<Float64>.fft(
bufferSize: Int = Int.MAX_VALUE,
normalization: DftNormalization = DftNormalization.STANDARD,
direction: TransformType = TransformType.FORWARD,
@ -99,4 +99,4 @@ public fun Flow<Double>.fft(
* Map a complex flow into real flow by taking real part of each number
*/
@FlowPreview
public fun Flow<Complex>.real(): Flow<Double> = map { it.re }
public fun Flow<Complex>.real(): Flow<Float64> = map { it.re }

@ -18,6 +18,7 @@ import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.optimization.*
import space.kscience.kmath.random.RandomGenerator
import space.kscience.kmath.stat.chiSquaredExpression
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.Float64Buffer
import space.kscience.kmath.structures.asBuffer
import kotlin.test.Test
@ -70,7 +71,7 @@ internal class OptimizeTest {
bindSymbol(a) * arg.pow(2) + bindSymbol(b) * arg + cWithDefault
}
val result: FunctionOptimization<Double> = chi2.optimizeWith(
val result: FunctionOptimization<Float64> = chi2.optimizeWith(
CMOptimizer,
mapOf(a to 1.5, b to 0.9, c to 1.0),
) {

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

@ -11,6 +11,7 @@ import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.memory.*
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.MutableBuffer
import space.kscience.kmath.structures.MutableBufferFactory
import kotlin.math.*
@ -28,7 +29,7 @@ public class Quaternion(
public val x: Double,
public val y: Double,
public val z: Double,
) : Buffer<Double> {
) : Buffer<Float64> {
init {
require(!w.isNaN()) { "w-component of quaternion is not-a-number" }
require(!x.isNaN()) { "x-component of quaternion is not-a-number" }
@ -51,7 +52,7 @@ public class Quaternion(
else -> error("Index $index out of bounds [0,3]")
}
override fun iterator(): Iterator<Double> = listOf(w, x, y, z).iterator()
override fun iterator(): Iterator<Float64> = listOf(w, x, y, z).iterator()
override fun equals(other: Any?): Boolean {
if (this === other) return true

@ -7,8 +7,6 @@ The core interfaces of KMath.
- [linear](src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Basic linear algebra operations (sums, products, etc.), backed by the `Space` API. Advanced linear algebra operations like matrix inversion and LU decomposition.
- [buffers](src/commonMain/kotlin/space/kscience/kmath/structures/Buffers.kt) : One-dimensional structure
- [expressions](src/commonMain/kotlin/space/kscience/kmath/expressions) : By writing a single mathematical expression once, users will be able to apply different types of
objects to the expression by providing a context. Expressions can be used for a wide variety of purposes from high
performance calculations to code generation.
- [domains](src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
- [autodiff](src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic differentiation
- [Parallel linear algebra](#) : Parallel implementation for `LinearAlgebra`
@ -16,7 +14,7 @@ performance calculations to code generation.
## Artifact:
The Maven coordinates of this project are `space.kscience:kmath-core:0.4.0`.
The Maven coordinates of this project are `space.kscience:kmath-core:0.4.2`.
**Gradle Kotlin DSL:**
```kotlin
@ -26,6 +24,6 @@ repositories {
}
dependencies {
implementation("space.kscience:kmath-core:0.4.0")
implementation("space.kscience:kmath-core:0.4.2")
}
```

@ -9,15 +9,9 @@ public abstract interface annotation class space/kscience/kmath/UnsafeKMathAPI :
public abstract interface annotation class space/kscience/kmath/UnstableKMathAPI : java/lang/annotation/Annotation {
}
public final class space/kscience/kmath/data/ColumnarDataKt {
}
public final class space/kscience/kmath/data/XYColumnarData$Companion {
}
public final class space/kscience/kmath/data/XYColumnarDataKt {
}
public final class space/kscience/kmath/data/XYErrorColumnarData$Companion {
public final fun of (Lspace/kscience/kmath/structures/Buffer;Lspace/kscience/kmath/structures/Buffer;Lspace/kscience/kmath/structures/Buffer;)Lspace/kscience/kmath/data/XYErrorColumnarData;
}
@ -27,9 +21,6 @@ public abstract interface class space/kscience/kmath/domains/Domain {
public abstract fun getDimension ()I
}
public final class space/kscience/kmath/domains/Domain1DKt {
}
public abstract interface class space/kscience/kmath/expressions/AutoDiffProcessor {
public abstract fun differentiate (Lkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/expressions/DifferentiableExpression;
}
@ -39,9 +30,6 @@ public class space/kscience/kmath/expressions/AutoDiffValue {
public final fun getValue ()Ljava/lang/Object;
}
public final class space/kscience/kmath/expressions/DSAlgebraKt {
}
public final class space/kscience/kmath/expressions/DSCompiler {
public final fun getAlgebra ()Lspace/kscience/kmath/operations/Algebra;
public final fun getFreeParameters ()I
@ -412,34 +400,6 @@ public final class space/kscience/kmath/expressions/MstRing : space/kscience/kma
public fun unaryPlus (Lspace/kscience/kmath/expressions/MST;)Lspace/kscience/kmath/expressions/MST$Unary;
}
public final class space/kscience/kmath/expressions/NamedMatrix : space/kscience/kmath/nd/Structure2D {
public static final field Companion Lspace/kscience/kmath/expressions/NamedMatrix$Companion;
public fun <init> (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)V
public fun elements ()Lkotlin/sequences/Sequence;
public fun get (II)Ljava/lang/Object;
public final fun get (Lspace/kscience/kmath/expressions/Symbol;Lspace/kscience/kmath/expressions/Symbol;)Ljava/lang/Object;
public fun get ([I)Ljava/lang/Object;
public fun getAttributes ()Lspace/kscience/attributes/Attributes;
public fun getColNum ()I
public fun getColumns ()Ljava/util/List;
public fun getDimension ()I
public final fun getIndexer ()Lspace/kscience/kmath/expressions/SymbolIndexer;
public fun getIndices ()Lspace/kscience/kmath/nd/ShapeIndexer;
public fun getRowNum ()I
public fun getRows ()Ljava/util/List;
public fun getShape-IIYLAfE ()[I
public final fun getValues ()Lspace/kscience/kmath/nd/Structure2D;
}
public final class space/kscience/kmath/expressions/NamedMatrix$Companion {
public final fun toStringWithSymbols (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)Ljava/lang/String;
}
public final class space/kscience/kmath/expressions/NamedMatrixKt {
public static final fun named (Lspace/kscience/kmath/nd/Structure2D;Ljava/util/List;)Lspace/kscience/kmath/expressions/NamedMatrix;
public static final fun named (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)Lspace/kscience/kmath/expressions/NamedMatrix;
}
public final class space/kscience/kmath/expressions/SimpleAutoDiffExpression : space/kscience/kmath/expressions/FirstDerivativeExpression {
public fun <init> (Lspace/kscience/kmath/operations/Field;Lkotlin/jvm/functions/Function1;)V
public fun derivativeOrNull (Lspace/kscience/kmath/expressions/Symbol;)Lspace/kscience/kmath/expressions/Expression;
@ -565,9 +525,6 @@ public final class space/kscience/kmath/expressions/Symbol$Companion {
public final fun getZError ()Lspace/kscience/kmath/expressions/Symbol;
}
public final class space/kscience/kmath/expressions/SymbolIndexerKt {
}
public final class space/kscience/kmath/expressions/SymbolKt {
public static final fun Symbol (Ljava/lang/String;)Lspace/kscience/kmath/expressions/Symbol;
public static final fun get (Ljava/util/Map;Ljava/lang/String;)Ljava/lang/Object;
@ -679,7 +636,7 @@ public final class space/kscience/kmath/linear/Inverted : space/kscience/attribu
public fun <init> ()V
}
public abstract interface class space/kscience/kmath/linear/IsDiagonal : space/kscience/attributes/FlagAttribute, space/kscience/kmath/linear/MatrixAttribute {
public abstract interface class space/kscience/kmath/linear/IsDiagonal : space/kscience/kmath/linear/Symmetric {
public static final field Companion Lspace/kscience/kmath/linear/IsDiagonal$Companion;
}
@ -786,24 +743,15 @@ public final class space/kscience/kmath/linear/MatrixAttributesKt {
public static final fun getSVD (Lspace/kscience/kmath/linear/MatrixScope;)Lspace/kscience/kmath/linear/SVDAttribute;
}
public final class space/kscience/kmath/linear/MatrixBuilder : space/kscience/attributes/WithType {
public fun <init> (Lspace/kscience/kmath/linear/LinearSpace;II)V
public final fun getColumns ()I
public final fun getLinearSpace ()Lspace/kscience/kmath/linear/LinearSpace;
public final fun getRows ()I
public fun getType-V0oMfBY ()Lkotlin/reflect/KType;
public final fun invoke ([Ljava/lang/Object;)Lspace/kscience/kmath/nd/Structure2D;
}
public final class space/kscience/kmath/linear/MatrixBuilderKt {
public static final fun column (Lspace/kscience/kmath/linear/LinearSpace;ILkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/Structure2D;
public final class space/kscience/kmath/linear/MatrixBuildersKt {
public static final fun column (Lspace/kscience/kmath/linear/LinearSpace;ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun column (Lspace/kscience/kmath/linear/LinearSpace;[Ljava/lang/Object;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun row (Lspace/kscience/kmath/linear/LinearSpace;ILkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun row (Lspace/kscience/kmath/linear/LinearSpace;ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun row (Lspace/kscience/kmath/linear/LinearSpace;[Ljava/lang/Object;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun symmetric (Lspace/kscience/kmath/linear/MatrixBuilder;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/Structure2D;
public static final fun vector (Lspace/kscience/kmath/linear/LinearSpace;[Ljava/lang/Object;)Lspace/kscience/kmath/structures/Buffer;
}
public abstract interface class space/kscience/kmath/linear/MatrixScope : space/kscience/attributes/AttributeScope, space/kscience/attributes/WithType {
public abstract interface class space/kscience/kmath/linear/MatrixScope : space/kscience/attributes/WithType {
}
public final class space/kscience/kmath/linear/MatrixWrapper : space/kscience/kmath/nd/Structure2D {
@ -818,7 +766,7 @@ public final class space/kscience/kmath/linear/MatrixWrapper : space/kscience/km
public final fun getOrigin ()Lspace/kscience/kmath/nd/Structure2D;
public fun getRowNum ()I
public fun getRows ()Ljava/util/List;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public fun toString ()Ljava/lang/String;
}
@ -854,8 +802,11 @@ public abstract interface class space/kscience/kmath/linear/SingularValueDecompo
public abstract fun getV ()Lspace/kscience/kmath/nd/Structure2D;
}
public final class space/kscience/kmath/linear/Symmetric : space/kscience/attributes/FlagAttribute, space/kscience/kmath/linear/MatrixAttribute {
public static final field INSTANCE Lspace/kscience/kmath/linear/Symmetric;
public abstract interface class space/kscience/kmath/linear/Symmetric : space/kscience/attributes/FlagAttribute, space/kscience/kmath/linear/MatrixAttribute {
public static final field Companion Lspace/kscience/kmath/linear/Symmetric$Companion;
}
public final class space/kscience/kmath/linear/Symmetric$Companion : space/kscience/kmath/linear/Symmetric {
}
public final class space/kscience/kmath/linear/TransposedKt {
@ -883,12 +834,6 @@ public final class space/kscience/kmath/linear/VirtualMatrix : space/kscience/km
public fun getColNum ()I
public final fun getGenerator ()Lkotlin/jvm/functions/Function2;
public fun getRowNum ()I
public fun getShape-IIYLAfE ()[I
}
public final class space/kscience/kmath/linear/VirtualMatrixKt {
public static final fun virtual (Lspace/kscience/kmath/linear/MatrixBuilder;Lspace/kscience/attributes/Attributes;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/linear/VirtualMatrix;
public static synthetic fun virtual$default (Lspace/kscience/kmath/linear/MatrixBuilder;Lspace/kscience/attributes/Attributes;Lkotlin/jvm/functions/Function2;ILjava/lang/Object;)Lspace/kscience/kmath/linear/VirtualMatrix;
}
public final class space/kscience/kmath/misc/CollectionsKt {
@ -944,14 +889,66 @@ public final class space/kscience/kmath/misc/SortingKt {
public static final fun sortedWith (Lspace/kscience/kmath/structures/Buffer;Ljava/util/Comparator;)Lspace/kscience/kmath/structures/Buffer;
}
public final class space/kscience/kmath/named/NamedBuffer : space/kscience/kmath/structures/Buffer {
public fun <init> (Lspace/kscience/kmath/structures/Buffer;Lspace/kscience/kmath/expressions/SymbolIndexer;)V
public fun get (I)Ljava/lang/Object;
public final fun get (Lspace/kscience/kmath/expressions/Symbol;)Ljava/lang/Object;
public final fun getIndexer ()Lspace/kscience/kmath/expressions/SymbolIndexer;
public fun getSize ()I
public final fun getValues ()Lspace/kscience/kmath/structures/Buffer;
public fun iterator ()Ljava/util/Iterator;
public fun toString ()Ljava/lang/String;
}
public final class space/kscience/kmath/named/NamedMatrix : space/kscience/kmath/nd/Structure2D {
public static final field Companion Lspace/kscience/kmath/named/NamedMatrix$Companion;
public fun <init> (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)V
public fun elements ()Lkotlin/sequences/Sequence;
public fun get (II)Ljava/lang/Object;
public final fun get (Lspace/kscience/kmath/expressions/Symbol;Lspace/kscience/kmath/expressions/Symbol;)Ljava/lang/Object;
public fun get ([I)Ljava/lang/Object;
public fun getAttributes ()Lspace/kscience/attributes/Attributes;
public fun getColNum ()I
public fun getColumns ()Ljava/util/List;
public fun getDimension ()I
public final fun getIndexer ()Lspace/kscience/kmath/expressions/SymbolIndexer;
public fun getIndices ()Lspace/kscience/kmath/nd/ShapeIndexer;
public fun getRowNum ()I
public fun getRows ()Ljava/util/List;
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public final fun getValues ()Lspace/kscience/kmath/nd/Structure2D;
}
public final class space/kscience/kmath/named/NamedMatrix$Companion {
public final fun toStringWithSymbols (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)Ljava/lang/String;
}
public final class space/kscience/kmath/named/NamedMatrixKt {
public static final fun named (Lspace/kscience/kmath/nd/Structure2D;Ljava/util/List;)Lspace/kscience/kmath/named/NamedMatrix;
public static final fun named (Lspace/kscience/kmath/nd/Structure2D;Lspace/kscience/kmath/expressions/SymbolIndexer;)Lspace/kscience/kmath/named/NamedMatrix;
}
public final class space/kscience/kmath/named/NamedMutableBuffer : space/kscience/kmath/structures/MutableBuffer {
public fun <init> (Lspace/kscience/kmath/structures/MutableBuffer;Lspace/kscience/kmath/expressions/SymbolIndexer;)V
public fun get (I)Ljava/lang/Object;
public final fun get (Lspace/kscience/kmath/expressions/Symbol;)Ljava/lang/Object;
public final fun getIndexer ()Lspace/kscience/kmath/expressions/SymbolIndexer;
public fun getSize ()I
public final fun getValues ()Lspace/kscience/kmath/structures/MutableBuffer;
public fun iterator ()Ljava/util/Iterator;
public fun set (ILjava/lang/Object;)V
public final fun set (Lspace/kscience/kmath/expressions/Symbol;Ljava/lang/Object;)V
public fun toString ()Ljava/lang/String;
}
public abstract interface class space/kscience/kmath/nd/AlgebraND : space/kscience/kmath/operations/Algebra {
public static final field Companion Lspace/kscience/kmath/nd/AlgebraND$Companion;
public abstract fun getElementAlgebra ()Lspace/kscience/kmath/operations/Algebra;
public fun invoke (Lkotlin/jvm/functions/Function1;Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/StructureND;
public fun map (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public fun mapIndexed (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/StructureND;
public abstract fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public abstract fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public fun zip (Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/StructureND;
}
@ -960,10 +957,10 @@ public final class space/kscience/kmath/nd/AlgebraND$Companion {
public final class space/kscience/kmath/nd/AlgebraNDExtentionsKt {
public static final fun mutableStructureND (Lspace/kscience/kmath/nd/AlgebraND;I[ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public static final fun one-waz_sdI (Lspace/kscience/kmath/nd/AlgebraND;[I)Lspace/kscience/kmath/nd/StructureND;
public static final fun one (Lspace/kscience/kmath/nd/AlgebraND;Lspace/kscience/kmath/nd/ShapeND;)Lspace/kscience/kmath/nd/StructureND;
public static final fun oneVarArg (Lspace/kscience/kmath/nd/AlgebraND;I[I)Lspace/kscience/kmath/nd/StructureND;
public static final fun structureND (Lspace/kscience/kmath/nd/AlgebraND;I[ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public static final fun zero-waz_sdI (Lspace/kscience/kmath/nd/AlgebraND;[I)Lspace/kscience/kmath/nd/StructureND;
public static final fun zero (Lspace/kscience/kmath/nd/AlgebraND;Lspace/kscience/kmath/nd/ShapeND;)Lspace/kscience/kmath/nd/StructureND;
public static final fun zeroVarArg (Lspace/kscience/kmath/nd/AlgebraND;I[I)Lspace/kscience/kmath/nd/StructureND;
}
@ -976,10 +973,10 @@ public abstract interface class space/kscience/kmath/nd/BufferAlgebraND : space/
public synthetic fun map (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public fun mapIndexed (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/BufferND;
public synthetic fun mapIndexed (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/StructureND;
public fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableBufferND;
public synthetic fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/BufferND;
public synthetic fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableBufferND;
public synthetic fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/BufferND;
public synthetic fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public fun toBufferND (Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/BufferND;
public fun zip (Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/BufferND;
public synthetic fun zip (Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function3;)Lspace/kscience/kmath/nd/StructureND;
@ -1004,7 +1001,7 @@ public class space/kscience/kmath/nd/BufferND : space/kscience/kmath/nd/Structur
public fun get ([I)Ljava/lang/Object;
public fun getBuffer ()Lspace/kscience/kmath/structures/Buffer;
public fun getIndices ()Lspace/kscience/kmath/nd/ShapeIndexer;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public fun toString ()Ljava/lang/String;
}
@ -1034,10 +1031,10 @@ public class space/kscience/kmath/nd/BufferedRingOpsND : space/kscience/kmath/nd
public final class space/kscience/kmath/nd/ColumnStrides : space/kscience/kmath/nd/Strides {
public static final field Companion Lspace/kscience/kmath/nd/ColumnStrides$Companion;
public synthetic fun <init> ([ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;)V
public fun equals (Ljava/lang/Object;)Z
public fun getLinearSize ()I
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public fun hashCode ()I
public fun index (I)[I
}
@ -1107,9 +1104,9 @@ public abstract class space/kscience/kmath/nd/Floa64FieldOpsND : space/kscience/
public synthetic fun multiply (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
public fun multiply (Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun multiply (Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/StructureND;
public fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableBufferND;
public synthetic fun mutableStructureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableBufferND;
public synthetic fun mutableStructureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/MutableStructureND;
public fun plus (DLspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/StructureND;
public synthetic fun plus (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
public synthetic fun plus (Ljava/lang/Object;Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/StructureND;
@ -1159,7 +1156,7 @@ public final class space/kscience/kmath/nd/Float64BufferND : space/kscience/kmat
}
public final class space/kscience/kmath/nd/Float64FieldND : space/kscience/kmath/nd/Floa64FieldOpsND, space/kscience/kmath/nd/FieldND, space/kscience/kmath/operations/ExtendedField, space/kscience/kmath/operations/NumbersAddOps {
public synthetic fun <init> ([ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;)V
public synthetic fun acosh (Ljava/lang/Object;)Ljava/lang/Object;
public fun acosh (Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun asinh (Ljava/lang/Object;)Ljava/lang/Object;
@ -1168,7 +1165,7 @@ public final class space/kscience/kmath/nd/Float64FieldND : space/kscience/kmath
public fun atanh (Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun cosh (Ljava/lang/Object;)Ljava/lang/Object;
public fun cosh (Lspace/kscience/kmath/nd/StructureND;)Lspace/kscience/kmath/nd/Float64BufferND;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public synthetic fun number (Ljava/lang/Number;)Ljava/lang/Object;
public fun number (Ljava/lang/Number;)Lspace/kscience/kmath/nd/Float64BufferND;
public synthetic fun power (Ljava/lang/Object;I)Ljava/lang/Object;
@ -1186,8 +1183,8 @@ public final class space/kscience/kmath/nd/Float64FieldND : space/kscience/kmath
public final class space/kscience/kmath/nd/Float64FieldNDKt {
public static final fun getNdAlgebra (Lspace/kscience/kmath/operations/Float64Field;)Lspace/kscience/kmath/nd/Floa64FieldOpsND;
public static final fun ndAlgebra (Lspace/kscience/kmath/operations/Float64Field;Lspace/kscience/kmath/nd/ShapeND;)Lspace/kscience/kmath/nd/Float64FieldND;
public static final fun ndAlgebra (Lspace/kscience/kmath/operations/Float64Field;[I)Lspace/kscience/kmath/nd/Float64FieldND;
public static final fun ndAlgebra-waz_sdI (Lspace/kscience/kmath/operations/Float64Field;[I)Lspace/kscience/kmath/nd/Float64FieldND;
}
public abstract interface class space/kscience/kmath/nd/GroupND : space/kscience/kmath/nd/GroupOpsND, space/kscience/kmath/nd/WithShape, space/kscience/kmath/operations/Group {
@ -1210,14 +1207,14 @@ public final class space/kscience/kmath/nd/GroupOpsND$Companion {
}
public final class space/kscience/kmath/nd/IndexOutOfShapeException : java/lang/RuntimeException {
public synthetic fun <init> ([I[ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;[I)V
public final fun getIndex ()[I
public final fun getShape-IIYLAfE ()[I
public final fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public final class space/kscience/kmath/nd/Int16RingND : space/kscience/kmath/nd/Int16RingOpsND, space/kscience/kmath/nd/RingND, space/kscience/kmath/operations/NumbersAddOps {
public synthetic fun <init> ([ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun getShape-IIYLAfE ()[I
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;)V
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public synthetic fun number (Ljava/lang/Number;)Ljava/lang/Object;
public fun number (Ljava/lang/Number;)Lspace/kscience/kmath/nd/BufferND;
}
@ -1241,8 +1238,8 @@ public final class space/kscience/kmath/nd/IntBufferND : space/kscience/kmath/nd
}
public final class space/kscience/kmath/nd/IntRingND : space/kscience/kmath/nd/IntRingOpsND, space/kscience/kmath/nd/RingND, space/kscience/kmath/operations/NumbersAddOps {
public synthetic fun <init> ([ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun getShape-IIYLAfE ()[I
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;)V
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public synthetic fun number (Ljava/lang/Number;)Ljava/lang/Object;
public fun number (Ljava/lang/Number;)Lspace/kscience/kmath/nd/BufferND;
}
@ -1253,9 +1250,9 @@ public final class space/kscience/kmath/nd/IntRingNDKt {
public abstract class space/kscience/kmath/nd/IntRingOpsND : space/kscience/kmath/nd/BufferedRingOpsND {
public static final field Companion Lspace/kscience/kmath/nd/IntRingOpsND$Companion;
public synthetic fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/BufferND;
public fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/IntBufferND;
public synthetic fun structureND-qL90JFI ([ILkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
public synthetic fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/BufferND;
public fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/IntBufferND;
public synthetic fun structureND (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)Lspace/kscience/kmath/nd/StructureND;
}
public final class space/kscience/kmath/nd/IntRingOpsND$Companion : space/kscience/kmath/nd/IntRingOpsND {
@ -1302,12 +1299,12 @@ public final class space/kscience/kmath/nd/OperationsNDKt {
}
public final class space/kscience/kmath/nd/PermutedMutableStructureND : space/kscience/kmath/nd/MutableStructureND {
public synthetic fun <init> (Lspace/kscience/kmath/nd/MutableStructureND;[ILkotlin/jvm/functions/Function1;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public synthetic fun <init> (Lspace/kscience/kmath/nd/MutableStructureND;[ILkotlin/jvm/functions/Function1;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/MutableStructureND;Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;)V
public synthetic fun <init> (Lspace/kscience/kmath/nd/MutableStructureND;Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun get ([I)Ljava/lang/Object;
public final fun getOrigin ()Lspace/kscience/kmath/nd/MutableStructureND;
public final fun getPermutation ()Lkotlin/jvm/functions/Function1;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public fun set ([ILjava/lang/Object;)V
}
@ -1316,13 +1313,13 @@ public final class space/kscience/kmath/nd/PermutedStructureND : space/kscience/
public fun get ([I)Ljava/lang/Object;
public final fun getOrigin ()Lspace/kscience/kmath/nd/StructureND;
public final fun getPermutation ()Lkotlin/jvm/functions/Function1;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public final class space/kscience/kmath/nd/PermutedStructureNDKt {
public static final fun permute (Lspace/kscience/kmath/nd/MutableStructureND;Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/PermutedMutableStructureND;
public static final fun permute (Lspace/kscience/kmath/nd/StructureND;Lkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/PermutedStructureND;
public static final fun permute-_A0By-k (Lspace/kscience/kmath/nd/MutableStructureND;[ILkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/PermutedMutableStructureND;
public static synthetic fun permute-_A0By-k$default (Lspace/kscience/kmath/nd/MutableStructureND;[ILkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lspace/kscience/kmath/nd/PermutedMutableStructureND;
public static synthetic fun permute$default (Lspace/kscience/kmath/nd/MutableStructureND;Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lspace/kscience/kmath/nd/PermutedMutableStructureND;
}
public final class space/kscience/kmath/nd/PrimitiveStructureNDKt {
@ -1349,10 +1346,10 @@ public final class space/kscience/kmath/nd/RingOpsND$Companion {
public final class space/kscience/kmath/nd/RowStrides : space/kscience/kmath/nd/Strides {
public static final field Companion Lspace/kscience/kmath/nd/RowStrides$Companion;
public synthetic fun <init> ([ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;)V
public fun equals (Ljava/lang/Object;)Z
public fun getLinearSize ()I
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public fun hashCode ()I
public fun index (I)[I
}
@ -1364,7 +1361,7 @@ public abstract interface class space/kscience/kmath/nd/ShapeIndexer : java/lang
public abstract fun asSequence ()Lkotlin/sequences/Sequence;
public abstract fun equals (Ljava/lang/Object;)Z
public abstract fun getLinearSize ()I
public abstract fun getShape-IIYLAfE ()[I
public abstract fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
public abstract fun hashCode ()I
public abstract fun index (I)[I
public fun iterator ()Ljava/util/Iterator;
@ -1372,54 +1369,49 @@ public abstract interface class space/kscience/kmath/nd/ShapeIndexer : java/lang
}
public final class space/kscience/kmath/nd/ShapeIndicesKt {
public static final fun Strides-dNlrn20 ([I)Lspace/kscience/kmath/nd/Strides;
public static final fun Strides (Lspace/kscience/kmath/nd/ShapeND;)Lspace/kscience/kmath/nd/Strides;
}
public final class space/kscience/kmath/nd/ShapeMismatchException : java/lang/RuntimeException {
public synthetic fun <init> ([I[ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun getActual-IIYLAfE ()[I
public final fun getExpected-IIYLAfE ()[I
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;Lspace/kscience/kmath/nd/ShapeND;)V
public final fun getActual ()Lspace/kscience/kmath/nd/ShapeND;
public final fun getExpected ()Lspace/kscience/kmath/nd/ShapeND;
}
public final class space/kscience/kmath/nd/ShapeND {
public static final synthetic fun box-impl ([I)Lspace/kscience/kmath/nd/ShapeND;
public static fun constructor-impl ([I)[I
public fun <init> ([I)V
public fun equals (Ljava/lang/Object;)Z
public static fun equals-impl ([ILjava/lang/Object;)Z
public static final fun equals-impl0 ([I[I)Z
public static final fun get-impl ([II)I
public static final fun getSize-impl ([I)I
public final fun get (I)I
public final fun getArray ()[I
public final fun getSize ()I
public fun hashCode ()I
public static fun hashCode-impl ([I)I
public fun toString ()Ljava/lang/String;
public static fun toString-impl ([I)Ljava/lang/String;
public final synthetic fun unbox-impl ()[I
}
public final class space/kscience/kmath/nd/ShapeNDKt {
public static final fun ShapeND (I[I)[I
public static final fun asArray-dNlrn20 ([I)[I
public static final fun asList-dNlrn20 ([I)Ljava/util/List;
public static final fun component1-dNlrn20 ([I)I
public static final fun component2-dNlrn20 ([I)I
public static final fun component3-dNlrn20 ([I)I
public static final fun contentEquals-9Nqdy04 ([I[I)Z
public static final fun contentHashCode-dNlrn20 ([I)I
public static final fun first-dNlrn20 ([I)I
public static final fun first-qL90JFI ([II)[I
public static final fun forEach-qL90JFI ([ILkotlin/jvm/functions/Function1;)V
public static final fun forEachIndexed-qL90JFI ([ILkotlin/jvm/functions/Function2;)V
public static final fun getIndices-dNlrn20 ([I)Lkotlin/ranges/IntRange;
public static final fun getLinearSize-dNlrn20 ([I)I
public static final fun isEmpty-dNlrn20 ([I)Z
public static final fun isNotEmpty-dNlrn20 ([I)Z
public static final fun last-dNlrn20 ([I)I
public static final fun last-qL90JFI ([II)[I
public static final fun plus-9Nqdy04 ([I[I)[I
public static final fun plus-qL90JFI ([I[I)[I
public static final fun slice-qL90JFI ([ILkotlin/ranges/IntRange;)[I
public static final fun toArray-dNlrn20 ([I)[I
public static final fun transposed-bYNkpeI ([III)[I
public static final fun ShapeND (I[I)Lspace/kscience/kmath/nd/ShapeND;
public static final fun asArray (Lspace/kscience/kmath/nd/ShapeND;)[I
public static final fun asList (Lspace/kscience/kmath/nd/ShapeND;)Ljava/util/List;
public static final fun component1 (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun component2 (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun component3 (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun contentEquals (Lspace/kscience/kmath/nd/ShapeND;Lspace/kscience/kmath/nd/ShapeND;)Z
public static final fun contentHashCode (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun first (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun first (Lspace/kscience/kmath/nd/ShapeND;I)Lspace/kscience/kmath/nd/ShapeND;
public static final fun forEach (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;)V
public static final fun forEachIndexed (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function2;)V
public static final fun getIndices (Lspace/kscience/kmath/nd/ShapeND;)Lkotlin/ranges/IntRange;
public static final fun getLinearSize (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun isEmpty (Lspace/kscience/kmath/nd/ShapeND;)Z
public static final fun isNotEmpty (Lspace/kscience/kmath/nd/ShapeND;)Z
public static final fun last (Lspace/kscience/kmath/nd/ShapeND;)I
public static final fun last (Lspace/kscience/kmath/nd/ShapeND;I)Lspace/kscience/kmath/nd/ShapeND;
public static final fun plus (Lspace/kscience/kmath/nd/ShapeND;Lspace/kscience/kmath/nd/ShapeND;)Lspace/kscience/kmath/nd/ShapeND;
public static final fun plus (Lspace/kscience/kmath/nd/ShapeND;[I)Lspace/kscience/kmath/nd/ShapeND;
public static final fun slice (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/ranges/IntRange;)Lspace/kscience/kmath/nd/ShapeND;
public static final fun toArray (Lspace/kscience/kmath/nd/ShapeND;)[I
public static final fun transposed (Lspace/kscience/kmath/nd/ShapeND;II)Lspace/kscience/kmath/nd/ShapeND;
}
public abstract class space/kscience/kmath/nd/Strides : space/kscience/kmath/nd/ShapeIndexer {
@ -1453,7 +1445,7 @@ public abstract interface class space/kscience/kmath/nd/Structure2D : space/ksci
public fun getColumns ()Ljava/util/List;
public abstract fun getRowNum ()I
public fun getRows ()Ljava/util/List;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public final class space/kscience/kmath/nd/Structure2D$Companion {
@ -1473,7 +1465,7 @@ public abstract interface class space/kscience/kmath/nd/StructureND : space/ksci
public abstract fun get ([I)Ljava/lang/Object;
public fun getAttributes ()Lspace/kscience/attributes/Attributes;
public fun getDimension ()I
public abstract fun getShape-IIYLAfE ()[I
public abstract fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public final class space/kscience/kmath/nd/StructureND$Companion {
@ -1484,9 +1476,9 @@ public final class space/kscience/kmath/nd/StructureND$Companion {
}
public final class space/kscience/kmath/nd/StructureNDKt {
public static final fun BufferND--rwW0uw (Lkotlin/reflect/KType;Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/BufferND;
public static final fun BufferND--rwW0uw (Lkotlin/reflect/KType;Lspace/kscience/kmath/nd/Strides;Lkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/BufferND;
public static final fun BufferND--rwW0uw (Lkotlin/reflect/KType;[ILkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/BufferND;
public static final fun BufferND-vHyE91E (Lkotlin/reflect/KType;[ILkotlin/jvm/functions/Function1;)Lspace/kscience/kmath/nd/BufferND;
public static final fun contentEquals (Lspace/kscience/kmath/linear/LinearSpace;Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;)Z
public static final fun contentEquals (Lspace/kscience/kmath/linear/LinearSpace;Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;Ljava/lang/Comparable;)Z
public static final fun contentEquals (Lspace/kscience/kmath/nd/AlgebraND;Lspace/kscience/kmath/nd/StructureND;Lspace/kscience/kmath/nd/StructureND;)Z
@ -1506,15 +1498,15 @@ public abstract interface class space/kscience/kmath/nd/StructureNDOfInt : space
}
public class space/kscience/kmath/nd/VirtualStructureND : space/kscience/kmath/nd/StructureND {
public synthetic fun <init> ([ILkotlin/jvm/functions/Function1;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun <init> (Lspace/kscience/kmath/nd/ShapeND;Lkotlin/jvm/functions/Function1;)V
public fun get ([I)Ljava/lang/Object;
public final fun getProducer ()Lkotlin/jvm/functions/Function1;
public fun getShape-IIYLAfE ()[I
public fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public abstract interface class space/kscience/kmath/nd/WithShape {
public fun getIndices ()Lspace/kscience/kmath/nd/ShapeIndexer;
public abstract fun getShape-IIYLAfE ()[I
public abstract fun getShape ()Lspace/kscience/kmath/nd/ShapeND;
}
public abstract interface class space/kscience/kmath/operations/Algebra : space/kscience/attributes/WithType {
@ -2429,9 +2421,6 @@ public final class space/kscience/kmath/structures/BufferListKt {
public static final fun asList (Lspace/kscience/kmath/structures/Buffer;)Ljava/util/List;
}
public final class space/kscience/kmath/structures/BufferPrimitiveAccessKt {
}
public final class space/kscience/kmath/structures/BufferSlice : space/kscience/kmath/structures/BufferView {
public fun <init> (Lspace/kscience/kmath/structures/Buffer;II)V
public synthetic fun <init> (Lspace/kscience/kmath/structures/Buffer;IIILkotlin/jvm/internal/DefaultConstructorMarker;)V

@ -9,7 +9,7 @@ kscience {
wasm()
dependencies {
api(projects.attributesKt)
api(libs.attributes)
}
testDependencies {

@ -7,6 +7,7 @@ package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point
import space.kscience.kmath.structures.Float64
@UnstableKMathAPI
public abstract class Domain1D<T : Comparable<T>>(public val range: ClosedRange<T>) : Domain<T> {
@ -22,8 +23,8 @@ public abstract class Domain1D<T : Comparable<T>>(public val range: ClosedRange<
@UnstableKMathAPI
public class DoubleDomain1D(
@Suppress("CanBeParameter") public val doubleRange: ClosedFloatingPointRange<Double>,
) : Domain1D<Double>(doubleRange), Float64Domain {
public val doubleRange: ClosedFloatingPointRange<Float64>,
) : Domain1D<Float64>(doubleRange), Float64Domain {
override fun getLowerBound(num: Int): Double {
require(num == 0)
return range.start
@ -55,5 +56,5 @@ public class DoubleDomain1D(
}
@UnstableKMathAPI
public val Domain1D<Double>.center: Double
public val Domain1D<Float64>.center: Double
get() = (range.endInclusive + range.start) / 2

@ -5,6 +5,7 @@
package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.structures.Float64
/**
* n-dimensional volume
@ -12,7 +13,7 @@ import space.kscience.kmath.UnstableKMathAPI
* @author Alexander Nozik
*/
@UnstableKMathAPI
public interface Float64Domain : Domain<Double> {
public interface Float64Domain : Domain<Float64> {
/**
* Global lower edge
* @param num axis number

@ -7,6 +7,7 @@ package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point
import space.kscience.kmath.structures.Buffer
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.Float64Buffer
import space.kscience.kmath.structures.indices
@ -15,7 +16,7 @@ import space.kscience.kmath.structures.indices
* and a [Buffer] of upper boundaries. Upper should be greater or equals than lower.
*/
@UnstableKMathAPI
public class HyperSquareDomain(public val lower: Buffer<Double>, public val upper: Buffer<Double>) : Float64Domain {
public class HyperSquareDomain(public val lower: Buffer<Float64>, public val upper: Buffer<Float64>) : Float64Domain {
init {
require(lower.size == upper.size) {
"Domain borders size mismatch. Lower borders size is ${lower.size}, but upper borders size is ${upper.size}."
@ -29,7 +30,7 @@ public class HyperSquareDomain(public val lower: Buffer<Double>, public val uppe
public val center: Float64Buffer get() = Float64Buffer(dimension) { (lower[it] + upper[it]) / 2.0 }
override operator fun contains(point: Point<Double>): Boolean = point.indices.all { i ->
override operator fun contains(point: Point<Float64>): Boolean = point.indices.all { i ->
point[i] in lower[i]..upper[i]
}

@ -6,10 +6,11 @@ package space.kscience.kmath.domains
import space.kscience.kmath.UnstableKMathAPI
import space.kscience.kmath.linear.Point
import space.kscience.kmath.structures.Float64
@UnstableKMathAPI
public class UnconstrainedDomain(override val dimension: Int) : Float64Domain {
override operator fun contains(point: Point<Double>): Boolean = true
override operator fun contains(point: Point<Float64>): Boolean = true
override fun getLowerBound(num: Int): Double = Double.NEGATIVE_INFINITY

@ -126,7 +126,7 @@ public class DSCompiler<T, out A : Algebra<T>> internal constructor(
* If all orders are set to 0, then the 0<sup>th</sup> order derivative is returned, which is the value of the
* function.
*
* The indices of derivatives are between 0 and [size] &minus; 1. Their specific order is fixed for a given compiler, but
* The indices of derivatives are between 0 and [getSize] &minus; 1. Their specific order is fixed for a given compiler, but
* otherwise not publicly specified. There are however some simple cases which have guaranteed indices:
*
* * the index of 0<sup>th</sup> order derivative is always 0

@ -13,6 +13,7 @@ import space.kscience.kmath.operations.Algebra
import space.kscience.kmath.operations.DoubleField
import space.kscience.kmath.operations.IntRing
import space.kscience.kmath.operations.LongRing
import space.kscience.kmath.structures.Float64
import kotlin.jvm.JvmName
import kotlin.properties.ReadOnlyProperty
@ -47,9 +48,9 @@ public inline fun <reified T> Expression(noinline block: (Map<Symbol, T>) -> T):
* Specialization of [Expression] for [Double] allowing better performance because of using array.
*/
@UnstableKMathAPI
public interface DoubleExpression : Expression<Double> {
public interface DoubleExpression : Expression<Float64> {
override val type: SafeType<Double> get() = DoubleField.type
override val type: SafeType<Float64> get() = DoubleField.type
/**
* The indexer of this expression's arguments that should be used to build array for [invoke].

@ -6,6 +6,7 @@
package space.kscience.kmath.expressions
import space.kscience.kmath.operations.*
import space.kscience.kmath.structures.Float64
import space.kscience.kmath.structures.MutableBufferFactory
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ -197,5 +198,5 @@ public inline fun <T, A : ExtendedField<T>> A.expressionInExtendedField(
): Expression<T> = FunctionalExpressionExtendedField(this).block()
public inline fun Float64Field.expression(
block: FunctionalExpressionExtendedField<Double, Float64Field>.() -> Expression<Double>,
): Expression<Double> = FunctionalExpressionExtendedField(this).block()
block: FunctionalExpressionExtendedField<Double, Float64Field>.() -> Expression<Float64>,
): Expression<Float64> = FunctionalExpressionExtendedField(this).block()

@ -69,6 +69,9 @@ public interface SymbolIndexer {
public fun Map<Symbol, Double>.toDoubleArray(): DoubleArray = DoubleArray(symbols.size) { getValue(symbols[it]) }
}
@UnstableKMathAPI
public val SymbolIndexer.size: Int get() = symbols.size
@UnstableKMathAPI
@JvmInline
public value class SimpleSymbolIndexer(override val symbols: List<Symbol>) : SymbolIndexer

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