diff --git a/.space.kts b/.space.kts index ce52a2f5c..45c84ae3d 100644 --- a/.space.kts +++ b/.space.kts @@ -34,7 +34,7 @@ job("Publish") { api.space().projects.automation.deployments.start( project = api.projectIdentifier(), targetIdentifier = TargetIdentifier.Key(projectName), - version = version+revisionSuffix, + version = version + revisionSuffix, // automatically update deployment status based on the status of a job syncWithAutomationJob = true ) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c383fe95..6bf936c10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,7 +77,8 @@ - Major refactor of tensors (only minor API changes) - Kotlin 1.8.20 - `LazyStructure` `deffered` -> `async` to comply with coroutines code style -- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added to `DoubleTensorAlgebra`. +- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added + to `DoubleTensorAlgebra`. - Multik went MPP ### Removed @@ -236,9 +237,11 @@ - MST to JVM bytecode translator (https://github.com/mipt-npm/kmath/pull/94) - FloatBuffer (specialized MutableBuffer over FloatArray) - FlaggedBuffer to associate primitive numbers buffer with flags (to mark values infinite or missing, etc.) -- Specialized builder functions for all primitive buffers like `IntBuffer(25) { it + 1 }` (https://github.com/mipt-npm/kmath/pull/125) +- Specialized builder functions for all primitive buffers + like `IntBuffer(25) { it + 1 }` (https://github.com/mipt-npm/kmath/pull/125) - Interface `NumericAlgebra` where `number` operation is available to convert numbers to algebraic elements -- Inverse trigonometric functions support in ExtendedField (`asin`, `acos`, `atan`) (https://github.com/mipt-npm/kmath/pull/114) +- Inverse trigonometric functions support in + ExtendedField (`asin`, `acos`, `atan`) (https://github.com/mipt-npm/kmath/pull/114) - New space extensions: `average` and `averageWith` - Local coding conventions - Geometric Domains API in `kmath-core` @@ -251,7 +254,8 @@ - `readAsMemory` now has `throws IOException` in JVM signature. - Several functions taking functional types were made `inline`. - Several functions taking functional types now have `callsInPlace` contracts. -- BigInteger and BigDecimal algebra: JBigDecimalField has companion object with default math context; minor optimizations +- BigInteger and BigDecimal algebra: JBigDecimalField has companion object with default math context; minor + optimizations - `power(T, Int)` extension function has preconditions and supports `Field` - Memory objects have more preconditions (overflow checking) - `tg` function is renamed to `tan` (https://github.com/mipt-npm/kmath/pull/114) diff --git a/README.md b/README.md index 00ba00ede..cd2503a12 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,8 @@ experience could be achieved with [kmath-for-real](/kmath-for-real) extension mo # Goal -* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and Wasm). +* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and + Wasm). * Provide basic multiplatform implementations for those abstractions (without significant performance optimization). * Provide bindings and wrappers with those abstractions for popular optimized platform libraries. @@ -55,150 +56,181 @@ 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 ### [examples](examples) + > > **Maturity**: EXPERIMENTAL ### [kmath-ast](kmath-ast) + > > **Maturity**: EXPERIMENTAL > > **Features:** -> - [expression-language](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/parser.kt) : Expression language and its parser -> - [mst-jvm-codegen](kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt) : Dynamic MST to JVM bytecode compiler +> - [expression-language](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/parser.kt) : Expression language and + its parser +> - [mst-jvm-codegen](kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt) : Dynamic MST to JVM bytecode + compiler > - [mst-js-codegen](kmath-ast/src/jsMain/kotlin/space/kscience/kmath/estree/estree.kt) : Dynamic MST to JS compiler -> - [rendering](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/MathRenderer.kt) : Extendable MST rendering - +> - [rendering](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/MathRenderer.kt) : Extendable MST + rendering ### [kmath-commons](kmath-commons) + > Commons math binding for kmath > > **Maturity**: EXPERIMENTAL ### [kmath-complex](kmath-complex) + > Complex numbers and quaternions. > > **Maturity**: PROTOTYPE > > **Features:** > - [complex](kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt) : Complex numbers operations -> - [quaternion](kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their composition - +> - [quaternion](kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their + composition ### [kmath-core](kmath-core) + > Core classes, algebra definitions, basic linear algebra > > **Maturity**: DEVELOPMENT > > **Features:** -> - [algebras](kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces and fields. -> - [nd](kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and operations on them. -> - [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. +> - [algebras](kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like + rings, spaces and fields. +> - [nd](kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures + and operations on them. +> - [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. +> - [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 - +> - [autodiff](kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic + differentiation ### [kmath-coroutines](kmath-coroutines) + > > **Maturity**: EXPERIMENTAL ### [kmath-dimensions](kmath-dimensions) + > A proof of concept module for adding type-safe dimensions to structures > > **Maturity**: PROTOTYPE ### [kmath-ejml](kmath-ejml) + > > **Maturity**: PROTOTYPE > > **Features:** > - [ejml-vector](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlVector.kt) : Point implementations. > - [ejml-matrix](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrix.kt) : Matrix implementation. -> - [ejml-linear-space](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace implementations. - +> - [ejml-linear-space](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace + implementations. ### [kmath-for-real](kmath-for-real) + > Extension module that should be used to achieve numpy-like behavior. -All operations are specialized to work with `Double` numbers without declaring algebraic contexts. -One can still use generic algebras though. +> All operations are specialized to work with `Double` numbers without declaring algebraic contexts. +> One can still use generic algebras though. > > **Maturity**: EXPERIMENTAL > > **Features:** -> - [DoubleVector](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for Buffers/Points -> - [DoubleMatrix](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like operations for 2d real structures +> - [DoubleVector](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like + operations for Buffers/Points +> - [DoubleMatrix](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like + operations for 2d real structures > - [grids](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/structures/grids.kt) : Uniform grid generators - ### [kmath-functions](kmath-functions) + > Functions, integration and interpolation > > **Maturity**: EXPERIMENTAL > > **Features:** -> - [piecewise](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions. -> - [polynomials](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial functions. -> - [linear interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : Linear XY interpolator. -> - [spline interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline XY interpolator. +> - [piecewise](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise + functions. +> - [polynomials](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial + functions. +> - [linear interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : + Linear XY interpolator. +> - [spline interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : + Cubic spline XY interpolator. > - [integration](kmath-functions/#) : Univariate and multivariate quadratures - ### [kmath-geometry](kmath-geometry) + > > **Maturity**: PROTOTYPE ### [kmath-histograms](kmath-histograms) + > > **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 - +> - [jafama-double](kmath-jafama/src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations + based on Jafama ### [kmath-jupyter](kmath-jupyter) + > > **Maturity**: PROTOTYPE ### [kmath-kotlingrad](kmath-kotlingrad) + > Kotlin∇ integration module > > **Maturity**: EXPERIMENTAL > > **Features:** -> - [differentiable-mst-expression](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based DifferentiableExpression. -> - [scalars-adapters](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s SFun and MST - +> - [differentiable-mst-expression](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : + MST based DifferentiableExpression. +> - [scalars-adapters](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : + Conversions between Kotlin∇'s SFun and MST ### [kmath-memory](kmath-memory) + > An API and basic implementation for arranging objects in a continuous memory block. > > **Maturity**: DEVELOPMENT ### [kmath-multik](kmath-multik) + > JetBrains Multik connector > > **Maturity**: PROTOTYPE ### [kmath-nd4j](kmath-nd4j) + > ND4J NDStructure implementation and according NDAlgebra classes > > **Maturity**: DEPRECATED @@ -208,45 +240,52 @@ One can still use generic algebras though. > - [nd4jarrayrings](kmath-nd4j/#) : Rings over Nd4jArrayStructure of Int and Long > - [nd4jarrayfields](kmath-nd4j/#) : Fields over Nd4jArrayStructure of Float and Double - ### [kmath-optimization](kmath-optimization) + > > **Maturity**: EXPERIMENTAL ### [kmath-stat](kmath-stat) + > > **Maturity**: EXPERIMENTAL ### [kmath-symja](kmath-symja) + > Symja integration module > > **Maturity**: PROTOTYPE ### [kmath-tensorflow](kmath-tensorflow) + > Google tensorflow connector > > **Maturity**: PROTOTYPE ### [kmath-tensors](kmath-tensors) + > > **Maturity**: PROTOTYPE > > **Features:** -> - [tensor algebra](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic linear algebra operations on tensors (plus, dot, etc.) -> - [tensor algebra with broadcasting](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) : Basic linear algebra operations implemented with broadcasting. -> - [linear algebra operations](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc. - +> - [tensor algebra](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic + linear algebra operations on tensors (plus, dot, etc.) +> - [tensor algebra with broadcasting](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) : + Basic linear algebra operations implemented with broadcasting. +> - [linear algebra operations](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : + Advanced linear algebra operations like LU decomposition, SVD, etc. ### [kmath-viktor](kmath-viktor) + > Binding for https://github.com/JetBrains-Research/viktor > > **Maturity**: DEVELOPMENT ### [test-utils](test-utils) + > > **Maturity**: EXPERIMENTAL - ## Multi-platform support KMath is developed as a multi-platform library, which means that most of the interfaces are declared in the @@ -257,16 +296,19 @@ feedback are also welcome. ## Performance -Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to achieve both +Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to +achieve both performance and flexibility. We expect to focus on creating a convenient universal API first and then work on increasing performance for specific cases. We expect the worst KMath benchmarks will perform better than native Python, but worse than optimized -native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be better than SciPy. +native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be +better than SciPy. ## Requirements -KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or Oracle GraalVM for execution to get better performance. +KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or +Oracle GraalVM for execution to get better performance. ### Repositories @@ -289,4 +331,7 @@ dependencies { ## Contributing The project requires a lot of additional work. The most important thing we need is feedback about what features are -required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues marked with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) label. \ No newline at end of file +required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues +marked +with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) +label. \ No newline at end of file diff --git a/attributes-kt/src/commonMain/kotlin/space/kscience/attributes/PolymorphicAttribute.kt b/attributes-kt/src/commonMain/kotlin/space/kscience/attributes/PolymorphicAttribute.kt index 80767421a..e81d88e46 100644 --- a/attributes-kt/src/commonMain/kotlin/space/kscience/attributes/PolymorphicAttribute.kt +++ b/attributes-kt/src/commonMain/kotlin/space/kscience/attributes/PolymorphicAttribute.kt @@ -22,7 +22,8 @@ public abstract class PolymorphicAttribute(public val type: SafeType) : At * Get a polymorphic attribute using attribute factory */ @UnstableAttributesAPI -public operator fun Attributes.get(attributeKeyBuilder: () -> PolymorphicAttribute): T? = get(attributeKeyBuilder()) +public operator fun Attributes.get(attributeKeyBuilder: () -> PolymorphicAttribute): T? = + get(attributeKeyBuilder()) /** * Set a polymorphic attribute using its factory diff --git a/benchmarks/src/jsMain/kotlin/space/kscience/kmath/benchmarks/ExpressionsInterpretersBenchmark.kt b/benchmarks/src/jsMain/kotlin/space/kscience/kmath/benchmarks/ExpressionsInterpretersBenchmark.kt index 4fa5be9f1..29d4cde79 100644 --- a/benchmarks/src/jsMain/kotlin/space/kscience/kmath/benchmarks/ExpressionsInterpretersBenchmark.kt +++ b/benchmarks/src/jsMain/kotlin/space/kscience/kmath/benchmarks/ExpressionsInterpretersBenchmark.kt @@ -94,6 +94,7 @@ class ExpressionsInterpretersBenchmark { } private val mst = node.toExpression(Float64Field) + @OptIn(UnstableKMathAPI::class) private val wasm = node.wasmCompileToExpression(Float64Field) private val estree = node.estreeCompileToExpression(Float64Field) diff --git a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BigIntBenchmark.kt b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BigIntBenchmark.kt index a67f52b67..a4c2855f1 100644 --- a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BigIntBenchmark.kt +++ b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BigIntBenchmark.kt @@ -67,7 +67,7 @@ internal class BigIntBenchmark { @Benchmark fun kmMultiplyLarge(blackhole: Blackhole) = BigIntField { - blackhole.consume(kmLargeNumber*kmLargeNumber) + blackhole.consume(kmLargeNumber * kmLargeNumber) } @Benchmark @@ -77,7 +77,7 @@ internal class BigIntBenchmark { @Benchmark fun jvmMultiplyLarge(blackhole: Blackhole) = JBigIntegerField { - blackhole.consume(jvmLargeNumber*jvmLargeNumber) + blackhole.consume(jvmLargeNumber * jvmLargeNumber) } @Benchmark diff --git a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BufferBenchmark.kt b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BufferBenchmark.kt index 9f665709c..a37d12ffb 100644 --- a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BufferBenchmark.kt +++ b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/BufferBenchmark.kt @@ -75,6 +75,6 @@ internal class BufferBenchmark { private companion object { private const val size = 100 - private val reversedIndices = IntArray(size){it}.apply { reverse() } + private val reversedIndices = IntArray(size) { it }.apply { reverse() } } } diff --git a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/IntegrationBenchmark.kt b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/IntegrationBenchmark.kt index 021c654a1..00f2d908d 100644 --- a/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/IntegrationBenchmark.kt +++ b/benchmarks/src/jvmMain/kotlin/space/kscience/kmath/benchmarks/IntegrationBenchmark.kt @@ -24,7 +24,7 @@ internal class IntegrationBenchmark { fun doubleIntegration(blackhole: Blackhole) { val res = Double.algebra.gaussIntegrator.integrate(0.0..1.0, intervals = 1000) { x: Double -> //sin(1 / x) - 1/x + 1 / x }.value blackhole.consume(res) } @@ -33,7 +33,7 @@ internal class IntegrationBenchmark { fun complexIntegration(blackhole: Blackhole) = with(Complex.algebra) { val res = gaussIntegrator.integrate(0.0..1.0, intervals = 1000) { x: Double -> // sin(1 / x) + i * cos(1 / x) - 1/x - i/x + 1 / x - i / x }.value blackhole.consume(res) } diff --git a/build.gradle.kts b/build.gradle.kts index 9ee719967..537cc2708 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -65,7 +65,7 @@ ksciencePublish { useApache2Licence() useSPCTeam() } - repository("spc","https://maven.sciprog.center/kscience") + repository("spc", "https://maven.sciprog.center/kscience") sonatype("https://oss.sonatype.org") } diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 89bb32b15..ba4c391d8 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -24,8 +24,8 @@ dependencies { implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.+") } -kotlin{ - jvmToolchain{ +kotlin { + jvmToolchain { languageVersion.set(JavaLanguageVersion.of(11)) } sourceSets.all { diff --git a/buildSrc/src/main/kotlin/space/kscience/kmath/benchmarks/addBenchmarkProperties.kt b/buildSrc/src/main/kotlin/space/kscience/kmath/benchmarks/addBenchmarkProperties.kt index fc04c82cf..ae2083c5f 100644 --- a/buildSrc/src/main/kotlin/space/kscience/kmath/benchmarks/addBenchmarkProperties.kt +++ b/buildSrc/src/main/kotlin/space/kscience/kmath/benchmarks/addBenchmarkProperties.kt @@ -63,7 +63,8 @@ fun Project.addBenchmarkProperties() { 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 = jsonMapper.readValue>(resDirectory.resolve("jvm.json")) + val reports: List = + jsonMapper.readValue>(resDirectory.resolve("jvm.json")) buildString { appendLine("
") @@ -76,16 +77,20 @@ fun Project.addBenchmarkProperties() { appendLine("* Run on ${first.vmName} (build ${first.vmVersion}) with Java process:") appendLine() appendLine("```") - appendLine("${first.jvm} ${ - first.jvmArgs.joinToString(" ") - }") + 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( + "* 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 |") diff --git a/docs/buffers.md b/docs/buffers.md index e7573497e..ce56d58c4 100644 --- a/docs/buffers.md +++ b/docs/buffers.md @@ -17,4 +17,4 @@ own `MemoryBuffer.create()` factory). ## Buffer performance One should avoid using default boxing buffer wherever it is possible. Try to use primitive buffers or memory buffers -instead . +instead . diff --git a/docs/codestyle.md b/docs/codestyle.md index 73ba5f754..fb18e5103 100644 --- a/docs/codestyle.md +++ b/docs/codestyle.md @@ -1,27 +1,35 @@ # Coding Conventions -Generally, KMath code follows general [Kotlin coding conventions](https://kotlinlang.org/docs/reference/coding-conventions.html), but with a number of small changes and clarifications. +Generally, KMath code follows +general [Kotlin coding conventions](https://kotlinlang.org/docs/reference/coding-conventions.html), but with a number of +small changes and clarifications. ## Utility Class Naming -Filename should coincide with a name of one of the classes contained in the file or start with small letter and describe its contents. +Filename should coincide with a name of one of the classes contained in the file or start with small letter and describe +its contents. -The code convention [here](https://kotlinlang.org/docs/reference/coding-conventions.html#source-file-names) says that file names should start with a capital letter even if file does not contain classes. Yet starting utility classes and aggregators with a small letter seems to be a good way to visually separate those files. +The code convention [here](https://kotlinlang.org/docs/reference/coding-conventions.html#source-file-names) says that +file names should start with a capital letter even if file does not contain classes. Yet starting utility classes and +aggregators with a small letter seems to be a good way to visually separate those files. This convention could be changed in future in a non-breaking way. ## Private Variable Naming -Private variables' names may start with underscore `_` for of the private mutable variable is shadowed by the public read-only value with the same meaning. +Private variables' names may start with underscore `_` for of the private mutable variable is shadowed by the public +read-only value with the same meaning. -This rule does not permit underscores in names, but it is sometimes useful to "underscore" the fact that public and private versions draw up the same entity. It is allowed only for private variables. +This rule does not permit underscores in names, but it is sometimes useful to "underscore" the fact that public and +private versions draw up the same entity. It is allowed only for private variables. This convention could be changed in future in a non-breaking way. ## Functions and Properties One-liners -Use one-liners when they occupy single code window line both for functions and properties with getters like -`val b: String get() = "fff"`. The same should be performed with multiline expressions when they could be +Use one-liners when they occupy single code window line both for functions and properties with getters like +`val b: String get() = "fff"`. The same should be performed with multiline expressions when they could be cleanly separated. -There is no universal consensus whenever use `fun a() = ...` or `fun a() { return ... }`. Yet from reader outlook one-lines seem to better show that the property or function is easily calculated. +There is no universal consensus whenever use `fun a() = ...` or `fun a() { return ... }`. Yet from reader outlook +one-lines seem to better show that the property or function is easily calculated. diff --git a/docs/expressions.md b/docs/expressions.md index e6250110c..cb9deca45 100644 --- a/docs/expressions.md +++ b/docs/expressions.md @@ -1,21 +1,24 @@ # Expressions -Expressions is a feature, which allows constructing lazily or immediately calculated parametric mathematical expressions. +Expressions is a feature, which allows constructing lazily or immediately calculated parametric mathematical +expressions. The potential use-cases for it (so far) are following: * lazy evaluation (in general simple lambda is better, but there are some border cases); * automatic differentiation in single-dimension and in multiple dimensions; * generation of mathematical syntax trees with subsequent code generation for other languages; -* symbolic computations, especially differentiation (and some other actions with `kmath-symja` integration with Symja's `IExpr`—integration, simplification, and more); +* symbolic computations, especially differentiation (and some other actions with `kmath-symja` integration with + Symja's `IExpr`—integration, simplification, and more); * visualization with `kmath-jupyter`. -The workhorse of this API is `Expression` interface, which exposes single `operator fun invoke(arguments: Map): T` +The workhorse of this API is `Expression` interface, which exposes +single `operator fun invoke(arguments: Map): T` method. `ExpressionAlgebra` is used to generate expressions and introduce variables. Currently there are two implementations: * Generic `ExpressionField` in `kmath-core` which allows construction of custom lazy expressions -* Auto-differentiation expression in `kmath-commons` module allows using full power of `DerivativeStructure` -from commons-math. **TODO: add example** +* Auto-differentiation expression in `kmath-commons` module allows using full power of `DerivativeStructure` + from commons-math. **TODO: add example** diff --git a/docs/linear.md b/docs/linear.md index 2a05499ef..3ded92ffe 100644 --- a/docs/linear.md +++ b/docs/linear.md @@ -1,8 +1,12 @@ ## Basic linear algebra layout -KMath support for linear algebra organized in a context-oriented way, which means that operations are in most cases declared in context classes, and are not the members of classes that store data. This allows more flexible approach to maintain multiple back-ends. The new operations added as extensions to contexts instead of being member functions of data structures. +KMath support for linear algebra organized in a context-oriented way, which means that operations are in most cases +declared in context classes, and are not the members of classes that store data. This allows more flexible approach to +maintain multiple back-ends. The new operations added as extensions to contexts instead of being member functions of +data structures. -The main context for linear algebra over matrices and vectors is `LinearSpace`, which defines addition and dot products of matrices and vectors: +The main context for linear algebra over matrices and vectors is `LinearSpace`, which defines addition and dot products +of matrices and vectors: ```kotlin import space.kscience.kmath.linear.* @@ -28,4 +32,5 @@ LinearSpace.Companion.real { ## Backends overview ### EJML + ### Commons Math diff --git a/docs/nd-structure.md b/docs/nd-structure.md index 3e9203ec0..8f2e504db 100644 --- a/docs/nd-structure.md +++ b/docs/nd-structure.md @@ -8,6 +8,7 @@ One of the most sought after features of mathematical libraries is the high-perf structures. In `kmath` performance depends on which particular context was used for operation. Let us consider following contexts: + ```kotlin // automatically build context most suited for given type. val autoField = NDField.auto(DoubleField, dim, dim) @@ -16,6 +17,7 @@ Let us consider following contexts: //A generic boxing field. It should be used for objects, not primitives. val genericField = NDField.buffered(DoubleField, dim, dim) ``` + Now let us perform several tests and see, which implementation is best suited for each case: ## Test case @@ -24,7 +26,9 @@ To test performance we will take 2d-structures with `dim = 1000` and add a struc to it `n = 1000` times. ## Specialized + The code to run this looks like: + ```kotlin specializedField.run { var res: NDBuffer = one @@ -33,13 +37,16 @@ The code to run this looks like: } } ``` + The performance of this code is the best of all tests since it inlines all operations and is specialized for operation with doubles. We will measure everything else relative to this one, so time for this test will be `1x` (real time on my computer is about 4.5 seconds). The only problem with this approach is that it requires specifying type from the beginning. Everyone does so anyway, so it is the recommended approach. ## Automatic + Let's do the same with automatic field inference: + ```kotlin autoField.run { var res = one @@ -48,13 +55,16 @@ Let's do the same with automatic field inference: } } ``` + Ths speed of this operation is approximately the same as for specialized case since `NDField.auto` just returns the same `RealNDField` in this case. Of course, it is usually better to use specialized method to be sure. ## Lazy + Lazy field does not produce a structure when asked, instead it generates an empty structure and fills it on-demand using coroutines to parallelize computations. When one calls + ```kotlin lazyField.run { var res = one @@ -63,12 +73,14 @@ When one calls } } ``` + The result will be calculated almost immediately but the result will be empty. To get the full result structure one needs to call all its elements. In this case computation overhead will be huge. So this field never should be used if one expects to use the full result structure. Though if one wants only small fraction, it could save a lot of time. This field still could be used with reasonable performance if call code is changed: + ```kotlin lazyField.run { val res = one.map { @@ -82,10 +94,13 @@ This field still could be used with reasonable performance if call code is chang res.elements().forEach { it.second } } ``` + In this case it completes in about `4x-5x` time due to boxing. ## Boxing + The boxing field produced by + ```kotlin genericField.run { var res: NDBuffer = one @@ -94,18 +109,22 @@ The boxing field produced by } } ``` + is the slowest one, because it requires boxing and unboxing the `double` on each operation. It takes about `15x` time (**TODO: there seems to be a problem here, it should be slow, but not that slow**). This field should never be used for primitives. ## Element operation + Let us also check the speed for direct operations on elements: + ```kotlin var res = genericField.one repeat(n) { res += 1.0 } ``` + One would expect to be at least as slow as field operation, but in fact, this one takes only `2x` time to complete. It happens, because in this particular case it does not use actual `NDField` but instead calculated directly via extension function. @@ -114,6 +133,7 @@ via extension function. Usually it is bad idea to compare the direct numerical operation performance in different languages, but it hard to work completely without frame of reference. In this case, simple numpy code: + ```python import numpy as np @@ -121,7 +141,9 @@ res = np.ones((1000,1000)) for i in range(1000): res = res + 1.0 ``` -gives the completion time of about `1.1x`, which means that specialized kotlin code in fact is working faster (I think it is + +gives the completion time of about `1.1x`, which means that specialized kotlin code in fact is working faster (I think +it is because better memory management). Of course if one writes `res += 1.0`, the performance will be different, but it would be different case, because numpy overrides `+=` with in-place operations. In-place operations are available in `kmath` with `MutableNDStructure` but there is no field for it (one can still work with mapping diff --git a/docs/polynomials.md b/docs/polynomials.md index b255acda1..5fdce0a91 100644 --- a/docs/polynomials.md +++ b/docs/polynomials.md @@ -1,27 +1,54 @@ # Polynomials and Rational Functions -KMath provides a way to work with uni- and multivariate polynomials and rational functions. It includes full support of arithmetic operations of integers, **constants** (elements of ring polynomials are build over), variables (for certain multivariate implementations), polynomials and rational functions encapsulated in so-called **polynomial space** and **rational function space** and some other utilities such as algebraic differentiation and substitution. +KMath provides a way to work with uni- and multivariate polynomials and rational functions. It includes full support of +arithmetic operations of integers, **constants** (elements of ring polynomials are build over), variables (for certain +multivariate implementations), polynomials and rational functions encapsulated in so-called **polynomial space** and * +*rational function space** and some other utilities such as algebraic differentiation and substitution. ## Concrete realizations There are 3 approaches to represent polynomials: -1. For univariate polynomials one can represent and store polynomial as a list of coefficients for each power of the variable. I.e. polynomial $a_0 + \dots + a_n x^n $ can be represented as a finite sequence $(a_0; \dots; a_n)$. (Compare to sequential definition of polynomials.) -2. For multivariate polynomials one can represent and store polynomial as a matching (in programming it is called "map" or "dictionary", in math it is called [functional relation](https://en.wikipedia.org/wiki/Binary_relation#Special_types_of_binary_relations)) of each "**term signature**" (that describes what variables and in what powers appear in the term) with corresponding coefficient of the term. But there are 2 possible approaches of term signature representation: - 1. One can number all the variables, so term signature can be represented as a sequence describing powers of the variables. I.e. signature of term $c \\; x_0^{d_0} \dots x_n^{d_n} $ (for natural or zero $d_i $) can be represented as a finite sequence $(d_0; \dots; d_n)$. - 2. One can represent variables as objects ("**labels**"), so term signature can be also represented as a matching of each appeared variable with its power in the term. I.e. signature of term $c \\; x_0^{d_0} \dots x_n^{d_n} $ (for natural non-zero $d_i $) can be represented as a finite matching $(x_0 \to d_1; \dots; x_n \to d_n)$. -All that three approaches are implemented by "list", "numbered", and "labeled" versions of polynomials and polynomial spaces respectively. Whereas all rational functions are represented as fractions with corresponding polynomial numerator and denominator, and rational functions' spaces are implemented in the same way as usual field of rational numbers (or more precisely, as any field of fractions over integral domain) should be implemented. +1. For univariate polynomials one can represent and store polynomial as a list of coefficients for each power of the + variable. I.e. polynomial $a_0 + \dots + a_n x^n $ can be represented as a finite sequence $(a_0; \dots; a_n)$. ( + Compare to sequential definition of polynomials.) +2. For multivariate polynomials one can represent and store polynomial as a matching (in programming it is called "map" + or "dictionary", in math it is + called [functional relation](https://en.wikipedia.org/wiki/Binary_relation#Special_types_of_binary_relations)) of + each "**term signature**" (that describes what variables and in what powers appear in the term) with corresponding + coefficient of the term. But there are 2 possible approaches of term signature representation: + 1. One can number all the variables, so term signature can be represented as a sequence describing powers of the + variables. I.e. signature of term $c \\; x_0^{d_0} \dots x_n^{d_n} $ (for natural or zero $d_i $) can be + represented as a finite sequence $(d_0; \dots; d_n)$. + 2. One can represent variables as objects ("**labels**"), so term signature can be also represented as a matching of + each appeared variable with its power in the term. I.e. signature of term $c \\; x_0^{d_0} \dots x_n^{d_n} $ (for + natural non-zero $d_i $) can be represented as a finite matching $(x_0 \to d_1; \dots; x_n \to d_n)$. + +All that three approaches are implemented by "list", "numbered", and "labeled" versions of polynomials and polynomial +spaces respectively. Whereas all rational functions are represented as fractions with corresponding polynomial numerator +and denominator, and rational functions' spaces are implemented in the same way as usual field of rational numbers (or +more precisely, as any field of fractions over integral domain) should be implemented. So here are a bit of details. Let `C` by type of constants. Then: -1. `ListPolynomial`, `ListPolynomialSpace`, `ListRationalFunction` and `ListRationalFunctionSpace` implement the first scenario. `ListPolynomial` stores polynomial $a_0 + \dots + a_n x^n $ as a coefficients list `listOf(a_0, ..., a_n)` (of type `List`). - - They also have variation `ScalableListPolynomialSpace` that replaces former polynomials and implements `ScaleOperations`. -2. `NumberedPolynomial`, `NumberedPolynomialSpace`, `NumberedRationalFunction` and `NumberedRationalFunctionSpace` implement second scenario. `NumberedPolynomial` stores polynomials as structures of type `Map, C>`. Signatures are stored as `List`. To prevent ambiguity signatures should not end with zeros. -3. `LabeledPolynomial`, `LabeledPolynomialSpace`, `LabeledRationalFunction` and `LabeledRationalFunctionSpace` implement third scenario using common `Symbol` as variable type. `LabeledPolynomial` stores polynomials as structures of type `Map, C>`. Signatures are stored as `Map`. To prevent ambiguity each signature should not map any variable to zero. + +1. `ListPolynomial`, `ListPolynomialSpace`, `ListRationalFunction` and `ListRationalFunctionSpace` implement the first + scenario. `ListPolynomial` stores polynomial $a_0 + \dots + a_n x^n $ as a coefficients + list `listOf(a_0, ..., a_n)` (of type `List`). + + They also have variation `ScalableListPolynomialSpace` that replaces former polynomials and + implements `ScaleOperations`. +2. `NumberedPolynomial`, `NumberedPolynomialSpace`, `NumberedRationalFunction` and `NumberedRationalFunctionSpace` + implement second scenario. `NumberedPolynomial` stores polynomials as structures of type `Map, C>`. + Signatures are stored as `List`. To prevent ambiguity signatures should not end with zeros. +3. `LabeledPolynomial`, `LabeledPolynomialSpace`, `LabeledRationalFunction` and `LabeledRationalFunctionSpace` implement + third scenario using common `Symbol` as variable type. `LabeledPolynomial` stores polynomials as structures of + type `Map, C>`. Signatures are stored as `Map`. To prevent ambiguity each signature + should not map any variable to zero. ### Example: `ListPolynomial` -For example, polynomial $2 - 3x + x^2 $ (with `Int` coefficients) is represented +For example, polynomial $2 - 3x + x^2 $ (with `Int` coefficients) is represented + ```kotlin val polynomial: ListPolynomial = ListPolynomial(listOf(2, -3, 1)) // or @@ -29,6 +56,7 @@ val polynomial: ListPolynomial = ListPolynomial(2, -3, 1) ``` All algebraic operations can be used in corresponding space: + ```kotlin val computationResult = Int.algebra.listPolynomialSpace { ListPolynomial(2, -3, 1) + ListPolynomial(0, 6) == ListPolynomial(2, 3, 1) @@ -41,7 +69,8 @@ For more see [examples](../examples/src/main/kotlin/space/kscience/kmath/functio ### Example: `NumberedPolynomial` -For example, polynomial $3 + 5 x_1 - 7 x_0^2 x_2 $ (with `Int` coefficients) is represented +For example, polynomial $3 + 5 x_1 - 7 x_0^2 x_2 $ (with `Int` coefficients) is represented + ```kotlin val polynomial: NumberedPolynomial = NumberedPolynomial( mapOf( @@ -59,6 +88,7 @@ val polynomial: NumberedPolynomial = NumberedPolynomial( ``` All algebraic operations can be used in corresponding space: + ```kotlin val computationResult = Int.algebra.numberedPolynomialSpace { NumberedPolynomial( @@ -83,7 +113,8 @@ For more see [examples](../examples/src/main/kotlin/space/kscience/kmath/functio ### Example: `LabeledPolynomial` -For example, polynomial $3 + 5 y - 7 x^2 z $ (with `Int` coefficients) is represented +For example, polynomial $3 + 5 y - 7 x^2 z $ (with `Int` coefficients) is represented + ```kotlin val polynomial: LabeledPolynomial = LabeledPolynomial( mapOf( @@ -101,6 +132,7 @@ val polynomial: LabeledPolynomial = LabeledPolynomial( ``` All algebraic operations can be used in corresponding space: + ```kotlin val computationResult = Int.algebra.labeledPolynomialSpace { LabeledPolynomial( @@ -150,23 +182,42 @@ classDiagram PolynomialSpaceOfFractions <|-- MultivariatePolynomialSpaceOfFractions ``` -There are implemented `Polynomial` and `RationalFunction` interfaces as abstractions of polynomials and rational functions respectively (although, there is not a lot of logic in them) and `PolynomialSpace` and `RationalFunctionSpace` (that implement `Ring` interface) as abstractions of polynomials' and rational functions' spaces respectively. More precisely, that means they allow to declare common logic of interaction with such objects and spaces: +There are implemented `Polynomial` and `RationalFunction` interfaces as abstractions of polynomials and rational +functions respectively (although, there is not a lot of logic in them) and `PolynomialSpace` +and `RationalFunctionSpace` (that implement `Ring` interface) as abstractions of polynomials' and rational functions' +spaces respectively. More precisely, that means they allow to declare common logic of interaction with such objects and +spaces: + - `Polynomial` does not provide any logic. It is marker interface. - `RationalFunction` provides numerator and denominator of rational function and destructuring declaration for them. -- `PolynomialSpace` provides all possible arithmetic interactions of integers, constants (of type `C`), and polynomials (of type `P`) like addition, subtraction, multiplication, and some others and common properties like degree of polynomial. -- `RationalFunctionSpace` provides the same as `PolynomialSpace` but also for rational functions: all possible arithmetic interactions of integers, constants (of type `C`), polynomials (of type `P`), and rational functions (of type `R`) like addition, subtraction, multiplication, division (in some cases), and some others and common properties like degree of polynomial. +- `PolynomialSpace` provides all possible arithmetic interactions of integers, constants (of type `C`), and + polynomials (of type `P`) like addition, subtraction, multiplication, and some others and common properties like + degree of polynomial. +- `RationalFunctionSpace` provides the same as `PolynomialSpace` but also for rational functions: all possible + arithmetic interactions of integers, constants (of type `C`), polynomials (of type `P`), and rational functions (of + type `R`) like addition, subtraction, multiplication, division (in some cases), and some others and common properties + like degree of polynomial. -Then to add abstraction of similar behaviour with variables (in multivariate case) there are implemented `MultivariatePolynomialSpace` and `MultivariateRationalFunctionSpace`. They just include variables (of type `V`) in the interactions of the entities. +Then to add abstraction of similar behaviour with variables (in multivariate case) there are +implemented `MultivariatePolynomialSpace` and `MultivariateRationalFunctionSpace`. They just include variables (of +type `V`) in the interactions of the entities. Also, to remove boilerplates there were provided helping subinterfaces and abstract subclasses: -- `PolynomialSpaceOverRing` allows to replace implementation of interactions of integers and constants with implementations from provided ring over constants (of type `A: Ring`). + +- `PolynomialSpaceOverRing` allows to replace implementation of interactions of integers and constants with + implementations from provided ring over constants (of type `A: Ring`). - `RationalFunctionSpaceOverRing` — the same but for `RationalFunctionSpace`. -- `RationalFunctionSpaceOverPolynomialSpace` — the same but "the inheritance" includes interactions with polynomials from provided `PolynomialSpace`. -- `PolynomialSpaceOfFractions` is actually abstract subclass of `RationalFunctionSpace` that implements all fractions boilerplates with provided (`protected`) constructor of rational functions by polynomial numerator and denominator. -- `MultivariateRationalFunctionSpaceOverMultivariatePolynomialSpace` and `MultivariatePolynomialSpaceOfFractions` — the same stories of operators inheritance and fractions boilerplates respectively but in multivariate case. +- `RationalFunctionSpaceOverPolynomialSpace` — the same but "the inheritance" includes interactions with + polynomials from provided `PolynomialSpace`. +- `PolynomialSpaceOfFractions` is actually abstract subclass of `RationalFunctionSpace` that implements all fractions + boilerplates with provided (`protected`) constructor of rational functions by polynomial numerator and denominator. +- `MultivariateRationalFunctionSpaceOverMultivariatePolynomialSpace` and `MultivariatePolynomialSpaceOfFractions` + — the same stories of operators inheritance and fractions boilerplates respectively but in multivariate case. ## Utilities -For all kinds of polynomials there are provided (implementation details depend on kind of polynomials) such common utilities as: +For all kinds of polynomials there are provided (implementation details depend on kind of polynomials) such common +utilities as: + 1. differentiation and anti-differentiation, 2. substitution, invocation and functional representation. \ No newline at end of file diff --git a/docs/templates/ARTIFACT-TEMPLATE.md b/docs/templates/ARTIFACT-TEMPLATE.md index 121c673fb..f6f37dcef 100644 --- a/docs/templates/ARTIFACT-TEMPLATE.md +++ b/docs/templates/ARTIFACT-TEMPLATE.md @@ -3,6 +3,7 @@ The Maven coordinates of this project are `${group}:${name}:${version}`. **Gradle:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/docs/templates/README-TEMPLATE.md b/docs/templates/README-TEMPLATE.md index 850f63413..0844500ea 100644 --- a/docs/templates/README-TEMPLATE.md +++ b/docs/templates/README-TEMPLATE.md @@ -25,7 +25,8 @@ experience could be achieved with [kmath-for-real](/kmath-for-real) extension mo # Goal -* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and Wasm). +* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and + Wasm). * Provide basic multiplatform implementations for those abstractions (without significant performance optimization). * Provide bindings and wrappers with those abstractions for popular optimized platform libraries. @@ -67,16 +68,19 @@ feedback are also welcome. ## Performance -Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to achieve both +Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to +achieve both performance and flexibility. We expect to focus on creating a convenient universal API first and then work on increasing performance for specific cases. We expect the worst KMath benchmarks will perform better than native Python, but worse than optimized -native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be better than SciPy. +native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be +better than SciPy. ## Requirements -KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or Oracle GraalVM for execution to get better performance. +KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or +Oracle GraalVM for execution to get better performance. ### Repositories @@ -99,4 +103,7 @@ dependencies { ## Contributing The project requires a lot of additional work. The most important thing we need is feedback about what features are -required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues marked with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) label. \ No newline at end of file +required the most. Feel free to create feature requests. We are also welcome to code contributions, especially in issues +marked +with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) +label. \ No newline at end of file diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts index b155f2653..b74d6edca 100644 --- a/examples/build.gradle.kts +++ b/examples/build.gradle.kts @@ -67,7 +67,7 @@ kotlin { } tasks.withType { - compilerOptions{ + compilerOptions { freeCompilerArgs.addAll("-Xjvm-default=all", "-Xopt-in=kotlin.RequiresOptIn", "-Xlambdas=indy") } } diff --git a/examples/src/main/kotlin/space/kscience/kmath/expressions/autodiff.kt b/examples/src/main/kotlin/space/kscience/kmath/expressions/autodiff.kt index 7bcb80da0..b9d7d4aa8 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/expressions/autodiff.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/expressions/autodiff.kt @@ -6,6 +6,7 @@ package space.kscience.kmath.expressions import space.kscience.kmath.UnstableKMathAPI + // Only kmath-core is needed. // Let's declare some variables @@ -51,7 +52,7 @@ fun main() { // >>> 0.0 // But in case you forgot to specify bound symbol's value, exception is thrown: - println( runCatching { someExpression(z to 4.0) } ) + println(runCatching { someExpression(z to 4.0) }) // >>> Failure(java.lang.IllegalStateException: Symbol 'x' is not supported in ...) // The reason is that the expression is evaluated lazily, diff --git a/examples/src/main/kotlin/space/kscience/kmath/fit/chiSquared.kt b/examples/src/main/kotlin/space/kscience/kmath/fit/chiSquared.kt index 14cd5bc76..5c00e2d81 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/fit/chiSquared.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/fit/chiSquared.kt @@ -77,7 +77,7 @@ suspend fun main() { val result = chi2.optimizeWith( CMOptimizer, mapOf(a to 1.5, b to 0.9, c to 1.0), - ){ + ) { FunctionOptimizationTarget(OptimizationDirection.MINIMIZE) } diff --git a/examples/src/main/kotlin/space/kscience/kmath/operations/mixedNDOperations.kt b/examples/src/main/kotlin/space/kscience/kmath/operations/mixedNDOperations.kt index 940a20324..7af026759 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/operations/mixedNDOperations.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/operations/mixedNDOperations.kt @@ -8,7 +8,6 @@ package space.kscience.kmath.operations import space.kscience.kmath.commons.linear.CMLinearSpace import space.kscience.kmath.linear.matrix import space.kscience.kmath.nd.Float64BufferND -import space.kscience.kmath.nd.ShapeND import space.kscience.kmath.nd.Structure2D import space.kscience.kmath.nd.mutableStructureND import space.kscience.kmath.nd.ndAlgebra diff --git a/examples/src/main/kotlin/space/kscience/kmath/series/analyzeDif.kt b/examples/src/main/kotlin/space/kscience/kmath/series/analyzeDif.kt index 4742b1f62..e6d3ef56b 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/series/analyzeDif.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/series/analyzeDif.kt @@ -44,10 +44,10 @@ fun main() = with(Double.seriesAlgebra()) { Plotly.page { h1 { +"This is my plot" } - p{ + p { +"Kolmogorov-smirnov test for s1 and s2: ${kmTest.value}" } - plot{ + plot { plotSeries("s1", s1) plotSeries("s2", s2) plotSeries("s3", s3) diff --git a/examples/src/main/kotlin/space/kscience/kmath/structures/StreamDoubleFieldND.kt b/examples/src/main/kotlin/space/kscience/kmath/structures/StreamDoubleFieldND.kt index 8c34ad4f1..3a59423d4 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/structures/StreamDoubleFieldND.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/structures/StreamDoubleFieldND.kt @@ -53,7 +53,10 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND Double): MutableBufferND { + override fun mutableStructureND( + shape: ShapeND, + initializer: DoubleField.(IntArray) -> Double, + ): MutableBufferND { val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset -> val index = strides.index(offset) DoubleField.initializer(index) diff --git a/examples/src/main/kotlin/space/kscience/kmath/structures/buffers.kt b/examples/src/main/kotlin/space/kscience/kmath/structures/buffers.kt index d4dfa60cb..82d2f8eb3 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/structures/buffers.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/structures/buffers.kt @@ -12,7 +12,7 @@ import space.kscience.kmath.operations.withSize inline fun MutableBuffer.Companion.same( n: Int, - value: R + value: R, ): MutableBuffer = MutableBuffer(n) { value } diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticDifficultTest.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticDifficultTest.kt index a6903baca..490e5d6a4 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticDifficultTest.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticDifficultTest.kt @@ -31,7 +31,7 @@ fun main() { val exampleNumber = 1 - var y_hat = funcDifficultForLm(t_example, p_example, exampleNumber) + var y_hat = funcDifficultForLm(t_example, p_example, exampleNumber) var p_init = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(Nparams, 1))).as2D() for (i in 0 until Nparams) { @@ -51,7 +51,8 @@ fun main() { val opts = doubleArrayOf(3.0, 10000.0, 1e-6, 1e-6, 1e-6, 1e-6, 1e-2, 11.0, 9.0, 1.0) // val opts = doubleArrayOf(3.0, 10000.0, 1e-6, 1e-6, 1e-6, 1e-6, 1e-3, 11.0, 9.0, 1.0) - val inputData = LMInput(::funcDifficultForLm, + val inputData = LMInput( + ::funcDifficultForLm, p_init.as2D(), t, y_dat, @@ -64,7 +65,8 @@ fun main() { doubleArrayOf(opts[6], opts[7], opts[8]), opts[9].toInt(), 10, - 1) + 1 + ) val result = DoubleTensorAlgebra.levenbergMarquardt(inputData) @@ -76,7 +78,7 @@ fun main() { println() println("Y true and y received:") - var y_hat_after = funcDifficultForLm(t_example, result.resultParameters, exampleNumber) + var y_hat_after = funcDifficultForLm(t_example, result.resultParameters, exampleNumber) for (i in 0 until y_hat.shape.component1()) { val x = (y_hat[i, 0] * 10000).roundToInt() / 10000.0 val y = (y_hat_after[i, 0] * 10000).roundToInt() / 10000.0 diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticEasyTest.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticEasyTest.kt index ab50d17e1..1b5abbd36 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticEasyTest.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticEasyTest.kt @@ -18,7 +18,8 @@ import kotlin.math.roundToInt fun main() { val startedData = getStartDataForFuncEasy() - val inputData = LMInput(::funcEasyForLm, + val inputData = LMInput( + ::funcEasyForLm, DoubleTensorAlgebra.ones(ShapeND(intArrayOf(4, 1))).as2D(), startedData.t, startedData.y_dat, @@ -31,7 +32,8 @@ fun main() { doubleArrayOf(startedData.opts[6], startedData.opts[7], startedData.opts[8]), startedData.opts[9].toInt(), 10, - startedData.example_number) + startedData.example_number + ) val result = DoubleTensorAlgebra.levenbergMarquardt(inputData) @@ -43,7 +45,7 @@ fun main() { println() println("Y true and y received:") - var y_hat_after = funcDifficultForLm(startedData.t, result.resultParameters, startedData.example_number) + var y_hat_after = funcDifficultForLm(startedData.t, result.resultParameters, startedData.example_number) for (i in 0 until startedData.y_dat.shape.component1()) { val x = (startedData.y_dat[i, 0] * 10000).roundToInt() / 10000.0 val y = (y_hat_after[i, 0] * 10000).roundToInt() / 10000.0 diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticMiddleTest.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticMiddleTest.kt index aa8aa73f8..ac26debb9 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticMiddleTest.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StaticLm/staticMiddleTest.kt @@ -15,6 +15,7 @@ import space.kscience.kmath.tensors.core.DoubleTensorAlgebra import space.kscience.kmath.tensors.core.LMInput import space.kscience.kmath.tensors.core.levenbergMarquardt import kotlin.math.roundToInt + fun main() { val NData = 100 var t_example = DoubleTensorAlgebra.ones(ShapeND(intArrayOf(NData, 1))).as2D() @@ -30,7 +31,7 @@ fun main() { val exampleNumber = 1 - var y_hat = funcMiddleForLm(t_example, p_example, exampleNumber) + var y_hat = funcMiddleForLm(t_example, p_example, exampleNumber) var p_init = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(Nparams, 1))).as2D() for (i in 0 until Nparams) { @@ -49,7 +50,8 @@ fun main() { p_min = p_min.div(1.0 / 50.0) val opts = doubleArrayOf(3.0, 7000.0, 1e-5, 1e-5, 1e-5, 1e-5, 1e-5, 11.0, 9.0, 1.0) - val inputData = LMInput(::funcMiddleForLm, + val inputData = LMInput( + ::funcMiddleForLm, p_init.as2D(), t, y_dat, @@ -62,7 +64,8 @@ fun main() { doubleArrayOf(opts[6], opts[7], opts[8]), opts[9].toInt(), 10, - 1) + 1 + ) val result = DoubleTensorAlgebra.levenbergMarquardt(inputData) @@ -74,7 +77,7 @@ fun main() { println() - var y_hat_after = funcMiddleForLm(t_example, result.resultParameters, exampleNumber) + var y_hat_after = funcMiddleForLm(t_example, result.resultParameters, exampleNumber) for (i in 0 until y_hat.shape.component1()) { val x = (y_hat[i, 0] * 10000).roundToInt() / 10000.0 val y = (y_hat_after[i, 0] * 10000).roundToInt() / 10000.0 diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamLm.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamLm.kt index f77adab7e..dca7325ce 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamLm.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamLm.kt @@ -6,18 +6,23 @@ package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.* -import space.kscience.kmath.nd.* +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +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.tensors.LevenbergMarquardt.StartDataLm import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra.zeros import space.kscience.kmath.tensors.core.DoubleTensorAlgebra import space.kscience.kmath.tensors.core.LMInput import space.kscience.kmath.tensors.core.levenbergMarquardt import kotlin.random.Random -import kotlin.reflect.KFunction3 -fun streamLm(lm_func: (MutableStructure2D, MutableStructure2D, Int) -> (MutableStructure2D), - startData: StartDataLm, launchFrequencyInMs: Long, numberOfLaunches: Int): Flow> = flow{ +fun streamLm( + lm_func: (MutableStructure2D, MutableStructure2D, Int) -> (MutableStructure2D), + startData: StartDataLm, launchFrequencyInMs: Long, numberOfLaunches: Int, +): Flow> = flow { var example_number = startData.example_number var p_init = startData.p_init @@ -32,7 +37,8 @@ fun streamLm(lm_func: (MutableStructure2D, MutableStructure2D, I var steps = numberOfLaunches val isEndless = (steps <= 0) - val inputData = LMInput(lm_func, + val inputData = LMInput( + lm_func, p_init, t, y_dat, @@ -45,7 +51,8 @@ fun streamLm(lm_func: (MutableStructure2D, MutableStructure2D, I doubleArrayOf(opts[6], opts[7], opts[8]), opts[9].toInt(), 10, - example_number) + example_number + ) while (isEndless || steps > 0) { val result = DoubleTensorAlgebra.levenbergMarquardt(inputData) @@ -57,7 +64,7 @@ fun streamLm(lm_func: (MutableStructure2D, MutableStructure2D, I } } -fun generateNewYDat(y_dat: MutableStructure2D, delta: Double): MutableStructure2D{ +fun generateNewYDat(y_dat: MutableStructure2D, delta: Double): MutableStructure2D { val n = y_dat.shape.component1() val y_dat_new = zeros(ShapeND(intArrayOf(n, 1))).as2D() for (i in 0 until n) { diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamingLmTest.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamingLmTest.kt index 2c53146b7..cd9115e7b 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamingLmTest.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/StreamingLm/streamingLmTest.kt @@ -5,14 +5,15 @@ package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm -import space.kscience.kmath.nd.* -import space.kscience.kmath.tensors.LevenbergMarquardt.* +import space.kscience.kmath.nd.component1 +import space.kscience.kmath.tensors.LevenbergMarquardt.funcDifficultForLm +import space.kscience.kmath.tensors.LevenbergMarquardt.getStartDataForFuncDifficult import kotlin.math.roundToInt -suspend fun main(){ +suspend fun main() { val startData = getStartDataForFuncDifficult() // Создание потока: - val lmFlow = streamLm(::funcDifficultForLm, startData, 0, 100) + val lmFlow = streamLm(::funcDifficultForLm, startData, 0, 100) var initialTime = System.currentTimeMillis() var lastTime: Long val launches = mutableListOf() diff --git a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/functionsToOptimize.kt b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/functionsToOptimize.kt index 4aefa1e0a..9a4b613b2 100644 --- a/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/functionsToOptimize.kt +++ b/examples/src/main/kotlin/space/kscience/kmath/tensors/LevenbergMarquardt/functionsToOptimize.kt @@ -18,7 +18,7 @@ import space.kscience.kmath.tensors.core.DoubleTensorAlgebra.Companion.pow import space.kscience.kmath.tensors.core.DoubleTensorAlgebra.Companion.times import space.kscience.kmath.tensors.core.asDoubleTensor -public data class StartDataLm ( +public data class StartDataLm( var lm_matx_y_dat: MutableStructure2D, var example_number: Int, var p_init: MutableStructure2D, @@ -29,10 +29,14 @@ public data class StartDataLm ( var p_min: MutableStructure2D, var p_max: MutableStructure2D, var consts: MutableStructure2D, - var opts: DoubleArray + var opts: DoubleArray, ) -fun funcEasyForLm(t: MutableStructure2D, p: MutableStructure2D, exampleNumber: Int): MutableStructure2D { +fun funcEasyForLm( + t: MutableStructure2D, + p: MutableStructure2D, + exampleNumber: Int, +): MutableStructure2D { val m = t.shape.component1() var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1))) @@ -40,15 +44,13 @@ fun funcEasyForLm(t: MutableStructure2D, p: MutableStructure2D, y_hat = DoubleTensorAlgebra.exp((t.times(-1.0 / p[1, 0]))).times(p[0, 0]) + t.times(p[2, 0]).times( DoubleTensorAlgebra.exp((t.times(-1.0 / p[3, 0]))) ) - } - else if (exampleNumber == 2) { + } else if (exampleNumber == 2) { val mt = t.max() y_hat = (t.times(1.0 / mt)).times(p[0, 0]) + (t.times(1.0 / mt)).pow(2).times(p[1, 0]) + (t.times(1.0 / mt)).pow(3).times(p[2, 0]) + (t.times(1.0 / mt)).pow(4).times(p[3, 0]) - } - else if (exampleNumber == 3) { + } else if (exampleNumber == 3) { y_hat = DoubleTensorAlgebra.exp((t.times(-1.0 / p[1, 0]))) .times(p[0, 0]) + DoubleTensorAlgebra.sin((t.times(1.0 / p[3, 0]))).times(p[2, 0]) } @@ -56,32 +58,40 @@ fun funcEasyForLm(t: MutableStructure2D, p: MutableStructure2D, return y_hat.as2D() } -fun funcMiddleForLm(t: MutableStructure2D, p: MutableStructure2D, exampleNumber: Int): MutableStructure2D { +fun funcMiddleForLm( + t: MutableStructure2D, + p: MutableStructure2D, + exampleNumber: Int, +): MutableStructure2D { val m = t.shape.component1() - var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1))) + var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1))) val mt = t.max() - for(i in 0 until p.shape.component1()){ + for (i in 0 until p.shape.component1()) { y_hat += (t.times(1.0 / mt)).times(p[i, 0]) } - for(i in 0 until 5){ + for (i in 0 until 5) { y_hat = funcEasyForLm(y_hat.as2D(), p, exampleNumber).asDoubleTensor() } return y_hat.as2D() } -fun funcDifficultForLm(t: MutableStructure2D, p: MutableStructure2D, exampleNumber: Int): MutableStructure2D { +fun funcDifficultForLm( + t: MutableStructure2D, + p: MutableStructure2D, + exampleNumber: Int, +): MutableStructure2D { val m = t.shape.component1() - var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1))) + var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1))) val mt = t.max() - for(i in 0 until p.shape.component1()){ - y_hat = y_hat.plus( (t.times(1.0 / mt)).times(p[i, 0]) ) + for (i in 0 until p.shape.component1()) { + y_hat = y_hat.plus((t.times(1.0 / mt)).times(p[i, 0])) } - for(i in 0 until 4){ + for (i in 0 until 4) { y_hat = funcEasyForLm((y_hat.as2D() + t).as2D(), p, exampleNumber).asDoubleTensor() } @@ -89,7 +99,7 @@ fun funcDifficultForLm(t: MutableStructure2D, p: MutableStructure2D : WithType { ) : TypedMst { init { - require(left.type==right.type){"Left and right expressions must be of the same type"} + require(left.type == right.type) { "Left and right expressions must be of the same type" } } override val type: SafeType get() = left.type diff --git a/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt b/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt index 9fcabefbc..d9eb3ba29 100644 --- a/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt +++ b/kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/features.kt @@ -426,11 +426,13 @@ public class InverseTrigonometricOperations(operations: Collection?) : U * The default instance configured with [TrigonometricOperations.ACOS_OPERATION], * [TrigonometricOperations.ASIN_OPERATION], [TrigonometricOperations.ATAN_OPERATION]. */ - public val Default: InverseTrigonometricOperations = InverseTrigonometricOperations(setOf( - TrigonometricOperations.ACOS_OPERATION, - TrigonometricOperations.ASIN_OPERATION, - TrigonometricOperations.ATAN_OPERATION, - )) + public val Default: InverseTrigonometricOperations = InverseTrigonometricOperations( + setOf( + TrigonometricOperations.ACOS_OPERATION, + TrigonometricOperations.ASIN_OPERATION, + TrigonometricOperations.ATAN_OPERATION, + ) + ) } } @@ -452,10 +454,12 @@ public class InverseHyperbolicOperations(operations: Collection?) : Unar * The default instance configured with [ExponentialOperations.ACOSH_OPERATION], * [ExponentialOperations.ASINH_OPERATION], and [ExponentialOperations.ATANH_OPERATION]. */ - public val Default: InverseHyperbolicOperations = InverseHyperbolicOperations(setOf( - ExponentialOperations.ACOSH_OPERATION, - ExponentialOperations.ASINH_OPERATION, - ExponentialOperations.ATANH_OPERATION, - )) + public val Default: InverseHyperbolicOperations = InverseHyperbolicOperations( + setOf( + ExponentialOperations.ACOSH_OPERATION, + ExponentialOperations.ASINH_OPERATION, + ExponentialOperations.ATANH_OPERATION, + ) + ) } } diff --git a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestFeatures.kt b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestFeatures.kt index 158abbdeb..6ccf73232 100644 --- a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestFeatures.kt +++ b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestFeatures.kt @@ -17,7 +17,8 @@ internal class TestFeatures { fun printNumeric() { val num = object : Number() { override fun toByte(): Byte = throw UnsupportedOperationException() -// override fun toChar(): Char = throw UnsupportedOperationException() + + // override fun toChar(): Char = throw UnsupportedOperationException() override fun toDouble(): Double = throw UnsupportedOperationException() override fun toFloat(): Float = throw UnsupportedOperationException() override fun toInt(): Int = throw UnsupportedOperationException() diff --git a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestMathML.kt b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestMathML.kt index abf761d23..2a5857069 100644 --- a/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestMathML.kt +++ b/kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/rendering/TestMathML.kt @@ -81,8 +81,10 @@ internal class TestMathML { @Test fun radicalWithIndex() = - testMathML(RadicalWithIndexSyntax("", SymbolSyntax("x"), SymbolSyntax("y")), - "yx") + testMathML( + RadicalWithIndexSyntax("", SymbolSyntax("x"), SymbolSyntax("y")), + "yx" + ) @Test fun multiplication() { diff --git a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/binaryen/index.binaryen.kt b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/binaryen/index.binaryen.kt index d40f3e0f5..6380d9b6c 100644 --- a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/binaryen/index.binaryen.kt +++ b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/binaryen/index.binaryen.kt @@ -52,7 +52,7 @@ internal external fun createType(types: Array): Type internal external fun expandType(type: Type): Array -internal external enum class ExpressionIds { +internal external enum class ExpressionIds { Invalid, Block, If, @@ -1656,27 +1656,27 @@ internal open external class Module { open fun `if`( condition: ExpressionRef, ifTrue: ExpressionRef, - ifFalse: ExpressionRef = definedExternally + ifFalse: ExpressionRef = definedExternally, ): ExpressionRef open fun loop(label: String, body: ExpressionRef): ExpressionRef open fun br( label: String, condition: ExpressionRef = definedExternally, - value: ExpressionRef = definedExternally + value: ExpressionRef = definedExternally, ): ExpressionRef open fun br_if( label: String, condition: ExpressionRef = definedExternally, - value: ExpressionRef = definedExternally + value: ExpressionRef = definedExternally, ): ExpressionRef open fun switch( labels: Array, defaultLabel: String, condition: ExpressionRef, - value: ExpressionRef = definedExternally + value: ExpressionRef = definedExternally, ): ExpressionRef open fun call(name: String, operands: Array, returnType: Type): ExpressionRef @@ -1685,14 +1685,14 @@ internal open external class Module { target: ExpressionRef, operands: Array, params: Type, - results: Type + results: Type, ): ExpressionRef open fun return_call_indirect( target: ExpressionRef, operands: Array, params: Type, - results: Type + results: Type, ): ExpressionRef open var local: `T$2` @@ -1730,7 +1730,7 @@ internal open external class Module { condition: ExpressionRef, ifTrue: ExpressionRef, ifFalse: ExpressionRef, - type: Type = definedExternally + type: Type = definedExternally, ): ExpressionRef open fun drop(value: ExpressionRef): ExpressionRef @@ -1754,7 +1754,7 @@ internal open external class Module { externalModuleName: String, externalBaseName: String, params: Type, - results: Type + results: Type, ) open fun addTableImport(internalName: String, externalModuleName: String, externalBaseName: String) @@ -1763,7 +1763,7 @@ internal open external class Module { internalName: String, externalModuleName: String, externalBaseName: String, - globalType: Type + globalType: Type, ) open fun addEventImport( @@ -1772,7 +1772,7 @@ internal open external class Module { externalBaseName: String, attribute: Number, params: Type, - results: Type + results: Type, ) open fun addFunctionExport(internalName: String, externalName: String): ExportRef @@ -1786,7 +1786,7 @@ internal open external class Module { initial: Number, maximum: Number, funcNames: Array, - offset: ExpressionRef = definedExternally + offset: ExpressionRef = definedExternally, ) open fun getFunctionTable(): `T$26` @@ -1796,7 +1796,7 @@ internal open external class Module { exportName: String? = definedExternally, segments: Array? = definedExternally, flags: Array? = definedExternally, - shared: Boolean = definedExternally + shared: Boolean = definedExternally, ) open fun getNumMemorySegments(): Number @@ -1827,7 +1827,7 @@ internal open external class Module { expr: ExpressionRef, fileIndex: Number, lineNumber: Number, - columnNumber: Number + columnNumber: Number, ) open fun copyExpression(expr: ExpressionRef): ExpressionRef @@ -2231,7 +2231,7 @@ internal open external class Relooper(module: Module) { from: RelooperBlockRef, to: RelooperBlockRef, indexes: Array, - code: ExpressionRef + code: ExpressionRef, ) open fun renderAndDispose(entry: RelooperBlockRef, labelHelper: Number): ExpressionRef diff --git a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.extensions.kt b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.extensions.kt index 7549f6514..db0723163 100644 --- a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.extensions.kt +++ b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/estree/estree.extensions.kt @@ -30,12 +30,13 @@ internal fun Identifier(name: String) = object : Identifier { override var name = name } -internal fun FunctionExpression(id: Identifier?, params: Array, body: BlockStatement) = object : FunctionExpression { - override var params = params - override var type = "FunctionExpression" - override var id: Identifier? = id - override var body = body -} +internal fun FunctionExpression(id: Identifier?, params: Array, body: BlockStatement) = + object : FunctionExpression { + override var params = params + override var type = "FunctionExpression" + override var id: Identifier? = id + override var body = body + } internal fun BlockStatement(vararg body: dynamic) = object : BlockStatement { override var type = "BlockStatement" diff --git a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/tsstdlib/lib.es5.kt b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/tsstdlib/lib.es5.kt index 07fd53fec..ee17edbc8 100644 --- a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/tsstdlib/lib.es5.kt +++ b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/tsstdlib/lib.es5.kt @@ -91,6 +91,6 @@ internal typealias Extract = Any internal external interface PromiseLike { fun then( onfulfilled: ((value: T) -> Any?)? = definedExternally, - onrejected: ((reason: Any) -> Any?)? = definedExternally + onrejected: ((reason: Any) -> Any?)? = definedExternally, ): PromiseLike } diff --git a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/webassembly/lib.dom.WebAssembly.module_dukat.kt b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/webassembly/lib.dom.WebAssembly.module_dukat.kt index 15332a413..c3e79c864 100644 --- a/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/webassembly/lib.dom.WebAssembly.module_dukat.kt +++ b/kmath-ast/src/jsMain/kotlin/space/kscience/kmath/internal/webassembly/lib.dom.WebAssembly.module_dukat.kt @@ -15,11 +15,11 @@ package space.kscience.kmath.internal.webassembly -import space.kscience.kmath.internal.tsstdlib.PromiseLike import org.khronos.webgl.ArrayBuffer import org.khronos.webgl.ArrayBufferView import org.khronos.webgl.Uint8Array import org.w3c.fetch.Response +import space.kscience.kmath.internal.tsstdlib.PromiseLike import kotlin.js.Promise @Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE") diff --git a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt index cd115cd4f..ac35562d2 100644 --- a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt +++ b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt @@ -91,7 +91,7 @@ public inline fun MST.compile(algebra: Algebra, vararg argu * @author Iaroslav Postovalov */ @UnstableKMathAPI -public fun MST.compileToExpression(algebra: Int32Ring): IntExpression { +public fun MST.compileToExpression(algebra: Int32Ring): IntExpression { val typed = evaluateConstants(algebra) return if (typed is TypedMst.Constant) object : IntExpression { diff --git a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/PrimitiveAsmBuilder.kt b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/PrimitiveAsmBuilder.kt index 9c27a25b5..3f003bb09 100644 --- a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/PrimitiveAsmBuilder.kt +++ b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/PrimitiveAsmBuilder.kt @@ -332,7 +332,7 @@ internal sealed class PrimitiveAsmBuilder>( private fun visitVariables( node: TypedMst, arrayMode: Boolean, - alreadyLoaded: MutableList = mutableListOf() + alreadyLoaded: MutableList = mutableListOf(), ): Unit = when (node) { is TypedMst.Variable -> if (node.symbol !in alreadyLoaded) { alreadyLoaded += node.symbol diff --git a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/codegenUtils.kt b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/codegenUtils.kt index e3565df23..e0d3a0ef4 100644 --- a/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/codegenUtils.kt +++ b/kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/internal/codegenUtils.kt @@ -8,7 +8,6 @@ package space.kscience.kmath.asm.internal import org.objectweb.asm.* import org.objectweb.asm.commons.InstructionAdapter import space.kscience.kmath.expressions.Expression -import space.kscience.kmath.expressions.MST import kotlin.contracts.InvocationKind import kotlin.contracts.contract diff --git a/kmath-commons/README.md b/kmath-commons/README.md index 2b5f3146d..7ca7dacf8 100644 --- a/kmath-commons/README.md +++ b/kmath-commons/README.md @@ -9,6 +9,7 @@ Commons math binding for kmath The Maven coordinates of this project are `space.kscience:kmath-commons:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/integration/CMGaussRuleIntegrator.kt b/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/integration/CMGaussRuleIntegrator.kt index c016c0f62..b4680bace 100644 --- a/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/integration/CMGaussRuleIntegrator.kt +++ b/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/integration/CMGaussRuleIntegrator.kt @@ -35,11 +35,13 @@ public class CMGaussRuleIntegrator( range.start, range.endInclusive ) + GaussRule.LEGENDREHP -> factory.legendreHighPrecision( numpoints, range.start, range.endInclusive ) + GaussRule.UNIFORM -> GaussIntegrator( getUniformRule( range.start, @@ -80,7 +82,7 @@ public class CMGaussRuleIntegrator( type: GaussRule = GaussRule.LEGENDRE, function: (Double) -> Double, ): Double = CMGaussRuleIntegrator(numPoints, type).integrate( - UnivariateIntegrand({IntegrationRange(range)},function) + UnivariateIntegrand({ IntegrationRange(range) }, function) ).value } } \ No newline at end of file diff --git a/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt b/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt index 6b31fcd88..0c15d1016 100644 --- a/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt +++ b/kmath-commons/src/jvmMain/kotlin/space/kscience/kmath/commons/linear/CMSolver.kt @@ -48,9 +48,11 @@ public fun CMLinearSpace.inverse( public fun CMLinearSpace.solver(decomposition: CMDecomposition): LinearSolver = object : LinearSolver { - override fun solve(a: Matrix, b: Matrix): Matrix = solver(a, decomposition).solve(b.toCM().origin).wrap() + override fun solve(a: Matrix, b: Matrix): Matrix = + solver(a, decomposition).solve(b.toCM().origin).wrap() - override fun solve(a: Matrix, b: Point): Point = solver(a, decomposition).solve(b.toCM().origin).toPoint() + override fun solve(a: Matrix, b: Point): Point = + solver(a, decomposition).solve(b.toCM().origin).toPoint() override fun inverse(matrix: Matrix): Matrix = solver(matrix, decomposition).inverse.wrap() } diff --git a/kmath-commons/src/jvmTest/kotlin/space/kscience/kmath/commons/optimization/OptimizeTest.kt b/kmath-commons/src/jvmTest/kotlin/space/kscience/kmath/commons/optimization/OptimizeTest.kt index 177a01b43..8b314cf1a 100644 --- a/kmath-commons/src/jvmTest/kotlin/space/kscience/kmath/commons/optimization/OptimizeTest.kt +++ b/kmath-commons/src/jvmTest/kotlin/space/kscience/kmath/commons/optimization/OptimizeTest.kt @@ -73,7 +73,7 @@ internal class OptimizeTest { val result: FunctionOptimization = chi2.optimizeWith( CMOptimizer, mapOf(a to 1.5, b to 0.9, c to 1.0), - ){ + ) { FunctionOptimizationTarget(OptimizationDirection.MINIMIZE) } println(result) diff --git a/kmath-complex/README.md b/kmath-complex/README.md index eec989eb3..b5e4b9d58 100644 --- a/kmath-complex/README.md +++ b/kmath-complex/README.md @@ -2,15 +2,15 @@ Complex and hypercomplex number systems in KMath. - - [complex](src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt) : Complex numbers operations - - [quaternion](src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their composition - +- [complex](src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt) : Complex numbers operations +- [quaternion](src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their composition ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-complex:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt index 87e750387..89c57527c 100644 --- a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt +++ b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt @@ -148,8 +148,8 @@ public object ComplexField : exp(pow * ln(arg)) } - public fun power(arg: Complex, pow: Complex): Complex = if(arg == zero || arg == (-0.0).toComplex()){ - if(pow == zero){ + public fun power(arg: Complex, pow: Complex): Complex = if (arg == zero || arg == (-0.0).toComplex()) { + if (pow == zero) { one } else { zero diff --git a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/ComplexFieldND.kt b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/ComplexFieldND.kt index 8fbf41732..3fce2c882 100644 --- a/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/ComplexFieldND.kt +++ b/kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/ComplexFieldND.kt @@ -19,7 +19,8 @@ import kotlin.contracts.contract */ @OptIn(UnstableKMathAPI::class) public sealed class ComplexFieldOpsND : BufferedFieldOpsND(ComplexField.bufferAlgebra), - ScaleOperations>, ExtendedFieldOps>, PowerOperations> { + ScaleOperations>, ExtendedFieldOps>, + PowerOperations> { @OptIn(PerformancePitfall::class) override fun StructureND.toBufferND(): BufferND = when (this) { @@ -53,7 +54,7 @@ public sealed class ComplexFieldOpsND : BufferedFieldOpsND): BufferND = mapInline(arg.toBufferND()) { atanh(it) } override fun power(arg: StructureND, pow: Number): StructureND = - mapInline(arg.toBufferND()) { power(it,pow) } + mapInline(arg.toBufferND()) { power(it, pow) } public companion object : ComplexFieldOpsND() } diff --git a/kmath-core/README.md b/kmath-core/README.md index f1f42210b..dd3935764 100644 --- a/kmath-core/README.md +++ b/kmath-core/README.md @@ -2,23 +2,28 @@ The core interfaces of KMath. - - [algebras](src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces and fields. - - [nd](src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and operations on them. - - [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 - - [linear.parallel](#) : Parallel implementation for `LinearAlgebra` - +- [algebras](src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces + and fields. +- [nd](src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and + operations on them. +- [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 +- [linear.parallel](#) : Parallel implementation for `LinearAlgebra` ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-core:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-core/build.gradle.kts b/kmath-core/build.gradle.kts index 0e061c6dd..699dd82e2 100644 --- a/kmath-core/build.gradle.kts +++ b/kmath-core/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() @@ -73,8 +73,8 @@ readme { ) { "Automatic differentiation" } feature( - id="Parallel linear algebra" - ){ + id = "Parallel linear algebra" + ) { """ Parallel implementation for `LinearAlgebra` """.trimIndent() diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYErrorColumnarData.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYErrorColumnarData.kt index 312894612..258ddc198 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYErrorColumnarData.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/data/XYErrorColumnarData.kt @@ -27,7 +27,7 @@ public interface XYErrorColumnarData : XYColumnarData of( - x: Buffer, y: Buffer, yErr: Buffer + x: Buffer, y: Buffer, yErr: Buffer, ): XYErrorColumnarData { require(x.size == y.size) { "Buffer size mismatch. x buffer size is ${x.size}, y buffer size is ${y.size}" } require(y.size == yErr.size) { "Buffer size mismatch. y buffer size is ${x.size}, yErr buffer size is ${y.size}" } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/MST.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/MST.kt index 55c3049b7..2d9dcd13d 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/MST.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/MST.kt @@ -58,6 +58,7 @@ public fun MST.interpret(algebra: Algebra, arguments: Map): T this.operation, algebra.number(this.value.value), ) + else -> algebra.unaryOperationFunction(this.operation)(this.value.interpret(algebra, arguments)) } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt index 58831f38d..03859ba83 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/LupDecomposition.kt @@ -83,7 +83,7 @@ internal fun > LinearSpace>.abs(value: T): T = public fun > Field.lup( matrix: Matrix, checkSingular: (T) -> Boolean, -): GenericLupDecomposition { +): GenericLupDecomposition { require(matrix.rowNum == matrix.colNum) { "LU decomposition supports only square matrices" } val m = matrix.colNum val pivot = IntArray(matrix.rowNum) @@ -110,7 +110,7 @@ public fun > Field.lup( // upper for (row in 0 until col) { var sum = lu[row, col] - for (i in 0 until row){ + for (i in 0 until row) { sum -= lu[row, i] * lu[i, col] } lu[row, col] = sum @@ -122,7 +122,7 @@ public fun > Field.lup( for (row in col until m) { var sum = lu[row, col] - for (i in 0 until col){ + for (i in 0 until col) { sum -= lu[row, i] * lu[i, col] } lu[row, col] = sum @@ -226,7 +226,7 @@ private fun Field.solve( public fun > LinearSpace>.lupSolver( singularityCheck: (T) -> Boolean, ): LinearSolver = object : LinearSolver { - override fun solve(a: Matrix, b: Matrix): Matrix = elementAlgebra{ + override fun solve(a: Matrix, b: Matrix): Matrix = elementAlgebra { // Use existing decomposition if it is provided by matrix or linear space itself val decomposition = a.getOrComputeAttribute(LUP) ?: lup(a, singularityCheck) return solve(decomposition, b) diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Int16RingND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Int16RingND.kt index 2f91a3326..d76120c59 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Int16RingND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/Int16RingND.kt @@ -18,12 +18,11 @@ public sealed class Int16RingOpsND : BufferedRingOpsND(Int16Ri @OptIn(UnstableKMathAPI::class) public class Int16RingND( - override val shape: ShapeND + override val shape: ShapeND, ) : Int16RingOpsND(), RingND, NumbersAddOps> { override fun number(value: Number): BufferND { - val short - = value.toShort() // minimize conversions + val short = value.toShort() // minimize conversions return structureND(shape) { short } } } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/IntRingND.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/IntRingND.kt index 128badda4..dfcf39965 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/IntRingND.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/IntRingND.kt @@ -35,7 +35,7 @@ public sealed class IntRingOpsND : BufferedRingOpsND(Int32Ring.b @OptIn(UnstableKMathAPI::class) public class IntRingND( - override val shape: ShapeND + override val shape: ShapeND, ) : IntRingOpsND(), RingND, NumbersAddOps> { override fun number(value: Number): BufferND { diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/algebraNDExtentions.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/algebraNDExtentions.kt index 2cada103d..7bd5f8350 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/algebraNDExtentions.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/nd/algebraNDExtentions.kt @@ -14,13 +14,13 @@ import kotlin.jvm.JvmName public fun > AlgebraND.structureND( shapeFirst: Int, vararg shapeRest: Int, - initializer: A.(IntArray) -> T + initializer: A.(IntArray) -> T, ): StructureND = structureND(ShapeND(shapeFirst, *shapeRest), initializer) public fun > AlgebraND.mutableStructureND( shapeFirst: Int, vararg shapeRest: Int, - initializer: A.(IntArray) -> T + initializer: A.(IntArray) -> T, ): MutableStructureND = mutableStructureND(ShapeND(shapeFirst, *shapeRest), initializer) public fun > AlgebraND.zero(shape: ShapeND): StructureND = structureND(shape) { zero } diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt index de26b0cf0..c10237324 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/BigInt.kt @@ -454,10 +454,12 @@ public fun String.parseBigInteger(): BigInt? { sign = +1 1 } + '-' -> { sign = -1 1 } + else -> { sign = +1 0 diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Float64BufferField.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Float64BufferField.kt index 5defbd7c5..1c4bda18f 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Float64BufferField.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Float64BufferField.kt @@ -33,7 +33,7 @@ public class Float64BufferField(public val size: Int) : ExtendedField: Algebra { +public interface PowerOperations : Algebra { /** * Raises [arg] to a power if possible (negative number could not be raised to a fractional power). diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/algebraExtensions.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/algebraExtensions.kt index 872d72857..9daccfb30 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/algebraExtensions.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/algebraExtensions.kt @@ -99,9 +99,10 @@ public fun Iterable.sumWith(group: Group): T = group.sum(this) * @param group tha algebra that provides addition * @param extractor the (inline) lambda function to extract value */ -public inline fun Iterable.sumWithGroupOf(group: Group, extractor: (T) -> R): R = this.fold(group.zero) { left: R, right: T -> - group.add(left, extractor(right)) -} +public inline fun Iterable.sumWithGroupOf(group: Group, extractor: (T) -> R): R = + this.fold(group.zero) { left: R, right: T -> + group.add(left, extractor(right)) + } /** * Returns the sum of all elements in the sequence in provided space. diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/integerFields.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/integerFields.kt index 17f6f2889..79fb0edb7 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/integerFields.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/integerFields.kt @@ -34,7 +34,7 @@ public object Int16Field : Field, Norm, NumericAlgebra, Norm, NumericAlgebra, Norm, NumericAlgebra(internal val array: Array) : MutableBuffer< /** * Returns an [ArrayBuffer] that wraps the original array. */ -public fun Array.asBuffer(): ArrayBuffer = ArrayBuffer( this) +public fun Array.asBuffer(): ArrayBuffer = ArrayBuffer(this) diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/FlaggedBuffer.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/FlaggedBuffer.kt index ce31163a9..043d65cd4 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/FlaggedBuffer.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/FlaggedBuffer.kt @@ -55,7 +55,7 @@ public fun FlaggedBuffer<*>.isMissing(index: Int): Boolean = hasFlag(index, Valu */ public class FlaggedDoubleBuffer( public val values: DoubleArray, - public val flags: ByteArray + public val flags: ByteArray, ) : FlaggedBuffer, Buffer { init { diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/Float32Buffer.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/Float32Buffer.kt index 7ad6c2a0d..a6b27e7a7 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/Float32Buffer.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/Float32Buffer.kt @@ -37,7 +37,8 @@ public typealias FloatBuffer = Float32Buffer * The function [init] is called for each array element sequentially starting from the first one. * It should return the value for a buffer element given its index. */ -public inline fun Float32Buffer(size: Int, init: (Int) -> Float): Float32Buffer = Float32Buffer(FloatArray(size) { init(it) }) +public inline fun Float32Buffer(size: Int, init: (Int) -> Float): Float32Buffer = + Float32Buffer(FloatArray(size) { init(it) }) /** * Returns a new [Float32Buffer] of given elements. diff --git a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/MutableBuffer.kt b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/MutableBuffer.kt index be0c76618..eeee5faad 100644 --- a/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/MutableBuffer.kt +++ b/kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/MutableBuffer.kt @@ -14,7 +14,7 @@ import kotlin.reflect.typeOf * * @param T the type of elements contained in the buffer. */ -public interface MutableBuffer : Buffer{ +public interface MutableBuffer : Buffer { /** * Sets the array element at the specified [index] to the specified [value]. @@ -65,20 +65,21 @@ public interface MutableBuffer : Buffer{ /** * Returns a shallow copy of the buffer. */ -public fun Buffer.copy(bufferFactory: BufferFactory): Buffer =if(this is ArrayBuffer){ +public fun Buffer.copy(bufferFactory: BufferFactory): Buffer = if (this is ArrayBuffer) { ArrayBuffer(array.copyOf()) -}else{ - bufferFactory(size,::get) +} else { + bufferFactory(size, ::get) } /** * Returns a mutable shallow copy of the buffer. */ -public fun Buffer.mutableCopy(bufferFactory: MutableBufferFactory): MutableBuffer =if(this is ArrayBuffer){ - ArrayBuffer(array.copyOf()) -}else{ - bufferFactory(size,::get) -} +public fun Buffer.mutableCopy(bufferFactory: MutableBufferFactory): MutableBuffer = + if (this is ArrayBuffer) { + ArrayBuffer(array.copyOf()) + } else { + bufferFactory(size, ::get) + } /** diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/DoubleLUSolverTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/DoubleLUSolverTest.kt index 901b1157c..037fdf3e5 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/DoubleLUSolverTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/linear/DoubleLUSolverTest.kt @@ -21,14 +21,14 @@ fun assertMatrixEquals(expected: StructureND, actual: StructureND.pow(power: Int): Matrix { var res = this repeat(power - 1) { - res = res dot this@pow + res = res dot this@pow } return res } diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/misc/PermSortTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/misc/PermSortTest.kt index a8fc1c765..f17f32738 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/misc/PermSortTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/misc/PermSortTest.kt @@ -29,7 +29,7 @@ class PermSortTest { */ @Test fun testOnEmptyBuffer() { - val emptyBuffer = Int32Buffer(0) {it} + val emptyBuffer = Int32Buffer(0) { it } var permutations = emptyBuffer.indicesSorted() assertTrue(permutations.isEmpty(), "permutation on an empty buffer should return an empty result") permutations = emptyBuffer.indicesSortedDescending() @@ -67,10 +67,14 @@ class PermSortTest { assertContentEquals(expected, permutations.map { platforms[it] }, "PermSort using custom ascending comparator") permutations = platforms.indicesSortedWith(compareByDescending { it.name.length }) - assertContentEquals(expected.reversed(), permutations.map { platforms[it] }, "PermSort using custom descending comparator") + assertContentEquals( + expected.reversed(), + permutations.map { platforms[it] }, + "PermSort using custom descending comparator" + ) } - private fun testPermutation(bufferSize: Int) { + private fun testPermutation(bufferSize: Int) { val seed = Random.nextLong() println("Test randomization seed: $seed") @@ -82,23 +86,23 @@ class PermSortTest { // Ensure no doublon is present in indices assertEquals(indices.toSet().size, indices.size) - for (i in 0 until (bufferSize-1)) { + for (i in 0 until (bufferSize - 1)) { val current = buffer[indices[i]] - val next = buffer[indices[i+1]] + val next = buffer[indices[i + 1]] assertTrue(current <= next, "Permutation indices not properly sorted") } val descIndices = buffer.indicesSortedDescending() - assertEquals(bufferSize, descIndices.size) + assertEquals(bufferSize, descIndices.size) // Ensure no doublon is present in indices assertEquals(descIndices.toSet().size, descIndices.size) - for (i in 0 until (bufferSize-1)) { + for (i in 0 until (bufferSize - 1)) { val current = buffer[descIndices[i]] - val next = buffer[descIndices[i+1]] + val next = buffer[descIndices[i + 1]] assertTrue(current >= next, "Permutation indices not properly sorted in descending order") } } - private fun Random.buffer(size : Int) = Int32Buffer(size) { nextInt() } + private fun Random.buffer(size: Int) = Int32Buffer(size) { nextInt() } } diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/NdOperationsTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/NdOperationsTest.kt index d0f79bb15..d3c1dbc3b 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/NdOperationsTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/NdOperationsTest.kt @@ -18,7 +18,7 @@ class NdOperationsTest { println(StructureND.toString(structure)) - val rolled = structure.roll(0,-1) + val rolled = structure.roll(0, -1) println(StructureND.toString(rolled)) diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/StridesTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/StridesTest.kt index 1c26c215c..224968e14 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/StridesTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/nd/StridesTest.kt @@ -12,10 +12,10 @@ class StridesTest { fun checkRowBasedStrides() { val strides = RowStrides(ShapeND(3, 3)) var counter = 0 - for(i in 0..2){ - for(j in 0..2){ + for (i in 0..2) { + for (j in 0..2) { // print(strides.offset(intArrayOf(i,j)).toString() + "\t") - require(strides.offset(intArrayOf(i,j)) == counter) + require(strides.offset(intArrayOf(i, j)) == counter) counter++ } println() @@ -26,10 +26,10 @@ class StridesTest { fun checkColumnBasedStrides() { val strides = ColumnStrides(ShapeND(3, 3)) var counter = 0 - for(i in 0..2){ - for(j in 0..2){ + for (i in 0..2) { + for (j in 0..2) { // print(strides.offset(intArrayOf(i,j)).toString() + "\t") - require(strides.offset(intArrayOf(j,i)) == counter) + require(strides.offset(intArrayOf(j, i)) == counter) counter++ } println() diff --git a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/structures/BufferExpandedTest.kt b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/structures/BufferExpandedTest.kt index 0a9b1d897..37cc4a533 100644 --- a/kmath-core/src/commonTest/kotlin/space/kscience/kmath/structures/BufferExpandedTest.kt +++ b/kmath-core/src/commonTest/kotlin/space/kscience/kmath/structures/BufferExpandedTest.kt @@ -13,7 +13,7 @@ internal class BufferExpandedTest { private val buffer = (0..100).toList().asBuffer() @Test - fun shrink(){ + fun shrink() { val view = buffer.slice(20..30) assertEquals(20, view[0]) assertEquals(30, view[10]) @@ -21,10 +21,10 @@ internal class BufferExpandedTest { } @Test - fun expandNegative(){ - val view: BufferView = buffer.expand(-20..113,0) - assertEquals(0,view[4]) - assertEquals(0,view[123]) + fun expandNegative() { + val view: BufferView = buffer.expand(-20..113, 0) + assertEquals(0, view[4]) + assertEquals(0, view[123]) assertEquals(100, view[120]) assertFails { view[-2] } assertFails { view[134] } diff --git a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/linear/Float64ParallelLinearSpace.kt b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/linear/Float64ParallelLinearSpace.kt index fd200d9f8..1fb5625b3 100644 --- a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/linear/Float64ParallelLinearSpace.kt +++ b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/linear/Float64ParallelLinearSpace.kt @@ -41,7 +41,7 @@ public object Float64ParallelLinearSpace : LinearSpace { } override fun buildVector(size: Int, initializer: Float64Field.(Int) -> Double): Float64Buffer = - IntStream.range(0, size).parallel().mapToDouble{ Float64Field.initializer(it) }.toArray().asBuffer() + IntStream.range(0, size).parallel().mapToDouble { Float64Field.initializer(it) }.toArray().asBuffer() override fun Matrix.unaryMinus(): Matrix = Floa64FieldOpsND { asND().map { -it }.as2D() diff --git a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/operations/isInteger.kt b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/operations/isInteger.kt index fa75860d8..e0b1cbe83 100644 --- a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/operations/isInteger.kt +++ b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/operations/isInteger.kt @@ -8,4 +8,5 @@ package space.kscience.kmath.operations /** * Check if number is an integer */ -public actual fun Number.isInteger(): Boolean = (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0) \ No newline at end of file +public actual fun Number.isInteger(): Boolean = + (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0) \ No newline at end of file diff --git a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/structures/parallelMutableBuffer.kt b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/structures/parallelMutableBuffer.kt index 7eeb0dbbd..d19f50dba 100644 --- a/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/structures/parallelMutableBuffer.kt +++ b/kmath-core/src/jvmMain/kotlin/space/kscience/kmath/structures/parallelMutableBuffer.kt @@ -33,7 +33,8 @@ public fun MutableBuffer.Companion.parallel( typeOf() -> IntStream.range(0, size).parallel().mapToDouble { initializer(it) as Float64 }.toArray() .asBuffer() as MutableBuffer //TODO add unsigned types - else -> IntStream.range(0, size).parallel().mapToObj { initializer(it) }.collect(Collectors.toList()).asMutableBuffer() + else -> IntStream.range(0, size).parallel().mapToObj { initializer(it) }.collect(Collectors.toList()) + .asMutableBuffer() } public class ParallelBufferFactory(override val type: SafeType) : MutableBufferFactory { diff --git a/kmath-core/src/jvmTest/kotlin/space/kscience/kmath/linear/ParallelMatrixTest.kt b/kmath-core/src/jvmTest/kotlin/space/kscience/kmath/linear/ParallelMatrixTest.kt index 915ec3c5e..2abc36c8e 100644 --- a/kmath-core/src/jvmTest/kotlin/space/kscience/kmath/linear/ParallelMatrixTest.kt +++ b/kmath-core/src/jvmTest/kotlin/space/kscience/kmath/linear/ParallelMatrixTest.kt @@ -19,14 +19,14 @@ import kotlin.test.assertTrue class ParallelMatrixTest { @Test - fun testTranspose() = Float64Field.linearSpace.parallel{ + fun testTranspose() = Float64Field.linearSpace.parallel { val matrix = one(3, 3) val transposed = matrix.transposed() assertTrue { StructureND.contentEquals(matrix, transposed) } } @Test - fun testBuilder() = Float64Field.linearSpace.parallel{ + fun testBuilder() = Float64Field.linearSpace.parallel { val matrix = matrix(2, 3)( 1.0, 0.0, 0.0, 0.0, 1.0, 2.0 @@ -36,7 +36,7 @@ class ParallelMatrixTest { } @Test - fun testMatrixExtension() = Float64Field.linearSpace.parallel{ + fun testMatrixExtension() = Float64Field.linearSpace.parallel { val transitionMatrix: Matrix = VirtualMatrix(6, 6) { row, col -> when { col == 0 -> .50 @@ -49,7 +49,7 @@ class ParallelMatrixTest { infix fun Matrix.pow(power: Int): Matrix { var res = this repeat(power - 1) { - res = res dot this@pow + res = res dot this@pow } return res } diff --git a/kmath-core/src/nativeMain/kotlin/space/kscience/kmath/operations/isInteger.kt b/kmath-core/src/nativeMain/kotlin/space/kscience/kmath/operations/isInteger.kt index fa75860d8..e0b1cbe83 100644 --- a/kmath-core/src/nativeMain/kotlin/space/kscience/kmath/operations/isInteger.kt +++ b/kmath-core/src/nativeMain/kotlin/space/kscience/kmath/operations/isInteger.kt @@ -8,4 +8,5 @@ package space.kscience.kmath.operations /** * Check if number is an integer */ -public actual fun Number.isInteger(): Boolean = (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0) \ No newline at end of file +public actual fun Number.isInteger(): Boolean = + (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0) \ No newline at end of file diff --git a/kmath-coroutines/README.md b/kmath-coroutines/README.md index 4b7081bb1..5b64ccc0a 100644 --- a/kmath-coroutines/README.md +++ b/kmath-coroutines/README.md @@ -1,7 +1,5 @@ # Module kmath-coroutines - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-coroutines:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-coroutines/src/jvmMain/kotlin/space/kscience/kmath/structures/LazyStructureND.kt b/kmath-coroutines/src/jvmMain/kotlin/space/kscience/kmath/structures/LazyStructureND.kt index 6acf5c1c8..86e7bcfef 100644 --- a/kmath-coroutines/src/jvmMain/kotlin/space/kscience/kmath/structures/LazyStructureND.kt +++ b/kmath-coroutines/src/jvmMain/kotlin/space/kscience/kmath/structures/LazyStructureND.kt @@ -25,6 +25,7 @@ public class LazyStructureND( } public suspend fun await(index: IntArray): T = async(index).await() + @PerformancePitfall override operator fun get(index: IntArray): T = runBlocking { async(index).await() } @@ -57,4 +58,4 @@ public inline fun StructureND.mapAsyncIndexed( public inline fun StructureND.mapAsync( scope: CoroutineScope, crossinline function: suspend (T) -> R, -): LazyStructureND = LazyStructureND(scope, shape) { index -> function(get(index)) } +): LazyStructureND = LazyStructureND(scope, shape) { index -> function(get(index)) } diff --git a/kmath-dimensions/README.md b/kmath-dimensions/README.md index c1c5e0dc2..f2482f965 100644 --- a/kmath-dimensions/README.md +++ b/kmath-dimensions/README.md @@ -9,6 +9,7 @@ A proof of concept module for adding type-safe dimensions to structures The Maven coordinates of this project are `space.kscience:kmath-dimensions:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-dimensions/build.gradle.kts b/kmath-dimensions/build.gradle.kts index 0ed6a8949..36f080899 100644 --- a/kmath-dimensions/build.gradle.kts +++ b/kmath-dimensions/build.gradle.kts @@ -2,13 +2,13 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() wasm() - dependencies{ + dependencies { api(projects.kmathCore) } diff --git a/kmath-ejml/README.md b/kmath-ejml/README.md index dcde8efd3..a2c38ce8e 100644 --- a/kmath-ejml/README.md +++ b/kmath-ejml/README.md @@ -2,16 +2,16 @@ EJML based linear algebra implementation. - - [ejml-vector](src/main/kotlin/space/kscience/kmath/ejml/EjmlVector.kt) : Point implementations. - - [ejml-matrix](src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrix.kt) : Matrix implementation. - - [ejml-linear-space](src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace implementations. - +- [ejml-vector](src/main/kotlin/space/kscience/kmath/ejml/EjmlVector.kt) : Point implementations. +- [ejml-matrix](src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrix.kt) : Matrix implementation. +- [ejml-linear-space](src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace implementations. ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-ejml:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/implementations.kt b/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/implementations.kt index d196f5f1a..df4941c52 100644 --- a/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/implementations.kt +++ b/kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/implementations.kt @@ -674,15 +674,17 @@ public object EjmlLinearSpaceDSCC : EjmlLinearSpace { - val res = DMatrixRMaj(origin.numRows,origin.numCols) - CommonOps_DSCC.invert(origin,res) + val res = DMatrixRMaj(origin.numRows, origin.numCols) + CommonOps_DSCC.invert(origin, res) res.wrapMatrix() } Determinant -> CommonOps_DSCC.det(origin) QR -> object : QRDecomposition { - val ejmlQr by lazy { DecompositionFactory_DSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } } + val ejmlQr by lazy { + DecompositionFactory_DSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } + } override val q: Matrix get() = ejmlQr.getQ(null, false).wrapMatrix() override val r: Matrix get() = ejmlQr.getR(null, false).wrapMatrix() } @@ -895,15 +897,17 @@ public object EjmlLinearSpaceFSCC : EjmlLinearSpace { - val res = FMatrixRMaj(origin.numRows,origin.numCols) - CommonOps_FSCC.invert(origin,res) + val res = FMatrixRMaj(origin.numRows, origin.numCols) + CommonOps_FSCC.invert(origin, res) res.wrapMatrix() } Determinant -> CommonOps_FSCC.det(origin) QR -> object : QRDecomposition { - val ejmlQr by lazy { DecompositionFactory_FSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } } + val ejmlQr by lazy { + DecompositionFactory_FSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } + } override val q: Matrix get() = ejmlQr.getQ(null, false).wrapMatrix() override val r: Matrix get() = ejmlQr.getR(null, false).wrapMatrix() } diff --git a/kmath-for-real/README.md b/kmath-for-real/README.md index 2c880f4f9..46762269e 100644 --- a/kmath-for-real/README.md +++ b/kmath-for-real/README.md @@ -2,16 +2,18 @@ Specialization of KMath APIs for Double numbers. - - [DoubleVector](src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for Buffers/Points - - [DoubleMatrix](src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like operations for 2d real structures - - [grids](src/commonMain/kotlin/space/kscience/kmath/structures/grids.kt) : Uniform grid generators - +- [DoubleVector](src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for + Buffers/Points +- [DoubleMatrix](src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like operations for 2d real + structures +- [grids](src/commonMain/kotlin/space/kscience/kmath/structures/grids.kt) : Uniform grid generators ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-for-real:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt index d36537d71..208c82c6d 100644 --- a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt +++ b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/RealMatrix.kt @@ -48,7 +48,7 @@ public fun Sequence.toMatrix(): RealMatrix = toList().let { } public fun RealMatrix.repeatStackVertical(n: Int): RealMatrix = - VirtualMatrix( rowNum * n, colNum) { row, col -> + VirtualMatrix(rowNum * n, colNum) { row, col -> get(if (row == 0) 0 else row % rowNum, col) } diff --git a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/grids.kt b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/grids.kt index f1b099cde..3a25739c3 100644 --- a/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/grids.kt +++ b/kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/grids.kt @@ -39,7 +39,7 @@ public fun Buffer.Companion.withFixedStep(range: ClosedFloatingPointRange return Float64Buffer(range.start) } val numberOfPoints = floor(normalizedRange.length / step).toInt() + 1 - return Float64Buffer(numberOfPoints) { normalizedRange.start + step * it } + return Float64Buffer(numberOfPoints) { normalizedRange.start + step * it } } /** diff --git a/kmath-for-real/src/commonTest/kotlin/space/kscience/kmath/real/GridTest.kt b/kmath-for-real/src/commonTest/kotlin/space/kscience/kmath/real/GridTest.kt index 861995a19..035eccb9e 100644 --- a/kmath-for-real/src/commonTest/kotlin/space/kscience/kmath/real/GridTest.kt +++ b/kmath-for-real/src/commonTest/kotlin/space/kscience/kmath/real/GridTest.kt @@ -20,9 +20,9 @@ class GridTest { } @Test - fun testIterateGrid(){ + fun testIterateGrid() { var res = 0.0 - for(d in 0.0..1.0 step 0.2){ + for (d in 0.0..1.0 step 0.2) { res = d } assertEquals(1.0, res) diff --git a/kmath-functions/README.md b/kmath-functions/README.md index 1ee4149bd..25c802077 100644 --- a/kmath-functions/README.md +++ b/kmath-functions/README.md @@ -2,18 +2,20 @@ Functions and interpolations. - - [piecewise](src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions. - - [polynomials](src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial functions. - - [linear interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : Linear XY interpolator. - - [spline interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline XY interpolator. - - [integration](#) : Univariate and multivariate quadratures - +- [piecewise](src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions. +- [polynomials](src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial functions. +- [linear interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : Linear XY + interpolator. +- [spline interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline + XY interpolator. +- [integration](#) : Univariate and multivariate quadratures ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-functions:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-functions/build.gradle.kts b/kmath-functions/build.gradle.kts index 9296aaaf0..e7fcab84a 100644 --- a/kmath-functions/build.gradle.kts +++ b/kmath-functions/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/polynomialUtil.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/polynomialUtil.kt index 31e2406fa..e85f698c4 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/polynomialUtil.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/polynomialUtil.kt @@ -64,7 +64,7 @@ public fun Polynomial.differentiate( ): Polynomial where A : Ring, A : NumericAlgebra = ring { Polynomial( buildList(max(0, coefficients.size - 1)) { - for (deg in 1 .. coefficients.lastIndex) add(number(deg) * coefficients[deg]) + for (deg in 1..coefficients.lastIndex) add(number(deg) * coefficients[deg]) } ) } diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/GaussIntegratorRuleFactory.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/GaussIntegratorRuleFactory.kt index 42ba2e3de..60777bfdb 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/GaussIntegratorRuleFactory.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/GaussIntegratorRuleFactory.kt @@ -16,7 +16,7 @@ import kotlin.native.concurrent.ThreadLocal public interface GaussIntegratorRuleFactory { public fun build(numPoints: Int): Pair, Buffer> - public companion object: IntegrandAttribute{ + public companion object : IntegrandAttribute { public fun double(numPoints: Int, range: ClosedRange): Pair, Buffer> = GaussLegendreRuleFactory.build(numPoints, range) } diff --git a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt index f5c98e9d9..babc86c54 100644 --- a/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt +++ b/kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/Integrand.kt @@ -23,8 +23,8 @@ public interface Integrand : AttributeContainer { public operator fun Integrand<*>.get(attribute: Attribute): T? = attributes[attribute] -public sealed class IntegrandValue private constructor(): IntegrandAttribute{ - public companion object: IntegrandValue(){ +public sealed class IntegrandValue private constructor() : IntegrandAttribute { + public companion object : IntegrandValue() { @Suppress("UNCHECKED_CAST") public fun forType(): IntegrandValue = this as IntegrandValue } diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialTest.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialTest.kt index c320212f3..80f50fcc0 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialTest.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialTest.kt @@ -8,7 +8,8 @@ package space.kscience.kmath.functions import space.kscience.kmath.functions.testUtils.* -import kotlin.test.* +import kotlin.test.Test +import kotlin.test.assertEquals class PolynomialTest { @@ -52,6 +53,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_Constant_minus() { RationalField.polynomialSpace { @@ -92,6 +94,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_Constant_times() { IntModuloRing(35).polynomialSpace { @@ -107,6 +110,7 @@ class PolynomialTest { ) } } + @Test fun test_Constant_Polynomial_plus() { RationalField.polynomialSpace { @@ -147,6 +151,7 @@ class PolynomialTest { ) } } + @Test fun test_Constant_Polynomial_minus() { RationalField.polynomialSpace { @@ -187,6 +192,7 @@ class PolynomialTest { ) } } + @Test fun test_Constant_Polynomial_times() { IntModuloRing(35).polynomialSpace { @@ -202,6 +208,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_unaryMinus() { RationalField.polynomialSpace { @@ -217,6 +224,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_Polynomial_plus() { RationalField.polynomialSpace { @@ -250,6 +258,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_Polynomial_minus() { RationalField.polynomialSpace { @@ -283,6 +292,7 @@ class PolynomialTest { ) } } + @Test fun test_Polynomial_Polynomial_times() { IntModuloRing(35).polynomialSpace { diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialUtilTest.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialUtilTest.kt index e91535506..b38afdd9e 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialUtilTest.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/PolynomialUtilTest.kt @@ -53,6 +53,7 @@ class PolynomialUtilTest { "test 5" ) } + @Test fun test_Polynomial_value_Constant() { assertEquals( @@ -85,6 +86,7 @@ class PolynomialUtilTest { "test 5" ) } + @Test fun test_Polynomial_differentiate() { assertEquals( @@ -94,20 +96,27 @@ class PolynomialUtilTest { ) assertEquals( Polynomial(Rational(-8, 3), Rational(8, 9), Rational(15, 7), Rational(-20, 9)), - Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate(RationalField), + Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate( + RationalField + ), "test 2" ) assertEquals( Polynomial(Rational(0), Rational(8, 9), Rational(15, 7), Rational(-20, 9)), - Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate(RationalField), + Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate( + RationalField + ), "test 3" ) assertEquals( Polynomial(Rational(-8, 3), Rational(8, 9), Rational(15, 7), Rational(0)), - Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).differentiate(RationalField), + Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).differentiate( + RationalField + ), "test 4" ) } + @Test fun test_Polynomial_integrate() { assertEquals( @@ -117,17 +126,23 @@ class PolynomialUtilTest { ) assertEquals( Polynomial(Rational(0), Rational(1, 5), Rational(-4, 3), Rational(4, 27), Rational(5, 28), Rational(-1, 9)), - Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate(RationalField), + Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate( + RationalField + ), "test 2" ) assertEquals( Polynomial(Rational(0), Rational(0), Rational(0), Rational(4, 27), Rational(5, 28), Rational(-1, 9)), - Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate(RationalField), + Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate( + RationalField + ), "test 3" ) assertEquals( Polynomial(Rational(0), Rational(1, 5), Rational(-4, 3), Rational(4, 27), Rational(5, 28), Rational(0)), - Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).integrate(RationalField), + Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).integrate( + RationalField + ), "test 4" ) } diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModulo.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModulo.kt index d53a1ac2b..ceb80d7dd 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModulo.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModulo.kt @@ -37,6 +37,7 @@ class IntModulo { modulus, toCheckInput = false ) + operator fun plus(other: IntModulo): IntModulo { require(modulus == other.modulus) { "can not add two residue different modulo" } return IntModulo( @@ -45,12 +46,14 @@ class IntModulo { toCheckInput = false ) } + operator fun plus(other: Int): IntModulo = IntModulo( (residue + other) % modulus, modulus, toCheckInput = false ) + operator fun minus(other: IntModulo): IntModulo { require(modulus == other.modulus) { "can not subtract two residue different modulo" } return IntModulo( @@ -59,12 +62,14 @@ class IntModulo { toCheckInput = false ) } + operator fun minus(other: Int): IntModulo = IntModulo( (residue - other) % modulus, modulus, toCheckInput = false ) + operator fun times(other: IntModulo): IntModulo { require(modulus == other.modulus) { "can not multiply two residue different modulo" } return IntModulo( @@ -73,12 +78,14 @@ class IntModulo { toCheckInput = false ) } + operator fun times(other: Int): IntModulo = IntModulo( (residue * other) % modulus, modulus, toCheckInput = false ) + operator fun div(other: IntModulo): IntModulo { require(modulus == other.modulus) { "can not divide two residue different modulo" } val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other.residue, modulus) @@ -89,6 +96,7 @@ class IntModulo { toCheckInput = false ) } + operator fun div(other: Int): IntModulo { val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other, modulus) require(gcdOfOtherResidueAndModulus == 1) { "can not divide to residue that has non-trivial GCD with modulo" } @@ -98,6 +106,7 @@ class IntModulo { toCheckInput = false ) } + override fun equals(other: Any?): Boolean = when (other) { is IntModulo -> residue == other.residue && modulus == other.modulus diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModuloUtils.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModuloUtils.kt index ce9a0270c..c6a8e16cd 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModuloUtils.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/IntModuloUtils.kt @@ -11,6 +11,7 @@ import space.kscience.kmath.functions.PolynomialSpace fun PolynomialSpace.Polynomial(vararg coefs: Int): Polynomial = Polynomial(coefs.map { IntModulo(it, ring.modulus) }) + fun IntModuloRing.Polynomial(vararg coefs: Int): Polynomial = Polynomial(coefs.map { IntModulo(it, modulus) }) diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/Rational.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/Rational.kt index c810cba2e..0160b2c97 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/Rational.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/Rational.kt @@ -57,18 +57,21 @@ class Rational { toCheckInput = false ) } + operator fun plus(other: Int): Rational = Rational( numerator + denominator * other.toLong(), denominator, toCheckInput = false ) + operator fun plus(other: Long): Rational = Rational( numerator + denominator * other, denominator, toCheckInput = false ) + operator fun minus(other: Rational): Rational { val denominatorsGcd = gcd(denominator, other.denominator) val dividedThisDenominator = denominator / denominatorsGcd @@ -81,18 +84,21 @@ class Rational { toCheckInput = false ) } + operator fun minus(other: Int): Rational = Rational( numerator - denominator * other.toLong(), denominator, toCheckInput = false ) + operator fun minus(other: Long): Rational = Rational( numerator - denominator * other, denominator, toCheckInput = false ) + operator fun times(other: Rational): Rational { val thisDenominatorAndOtherNumeratorGcd = gcd(denominator, other.numerator) val otherDenominatorAndThisNumeratorGcd = gcd(other.denominator, numerator) @@ -102,6 +108,7 @@ class Rational { toCheckInput = false ) } + operator fun times(other: Int): Rational { val other = other.toLong() val denominatorAndOtherGcd = gcd(denominator, other) @@ -111,6 +118,7 @@ class Rational { toCheckInput = false ) } + operator fun times(other: Long): Rational { val denominatorAndOtherGcd = gcd(denominator, other) return Rational( @@ -119,6 +127,7 @@ class Rational { toCheckInput = false ) } + operator fun div(other: Rational): Rational { val denominatorsGcd = gcd(denominator, other.denominator) val numeratorsGcd = gcd(numerator, other.numerator) @@ -127,6 +136,7 @@ class Rational { (denominator / denominatorsGcd) * (other.numerator / numeratorsGcd) ) } + operator fun div(other: Int): Rational { val other = other.toLong() val numeratorAndOtherGcd = gcd(numerator, other) @@ -136,6 +146,7 @@ class Rational { toCheckInput = false ) } + operator fun div(other: Long): Rational { val numeratorAndOtherGcd = gcd(numerator, other) return Rational( @@ -144,6 +155,7 @@ class Rational { toCheckInput = false ) } + override fun equals(other: Any?): Boolean = when (other) { is Rational -> numerator == other.numerator && denominator == other.denominator diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/misc.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/misc.kt index 267fae83b..6f728a53d 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/misc.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/functions/testUtils/misc.kt @@ -14,13 +14,41 @@ internal tailrec fun gcd(a: Long, b: Long): Long = if (a == 0L) abs(b) else gcd( internal fun bezoutIdentityWithGCD(a: Int, b: Int): BezoutIdentityWithGCD = when { - a < 0 && b < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, -b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(-first, -second, gcd) } - a < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(-first, second, gcd) } - b < 0 -> with(bezoutIdentityWithGCDInternalLogic(a, -b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(first, -second, gcd) } + a < 0 && b < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, -b, 1, 0, 0, 1)) { + BezoutIdentityWithGCD( + -first, + -second, + gcd + ) + } + + a < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, b, 1, 0, 0, 1)) { + BezoutIdentityWithGCD( + -first, + second, + gcd + ) + } + + b < 0 -> with(bezoutIdentityWithGCDInternalLogic(a, -b, 1, 0, 0, 1)) { + BezoutIdentityWithGCD( + first, + -second, + gcd + ) + } + else -> bezoutIdentityWithGCDInternalLogic(a, b, 1, 0, 0, 1) } -internal tailrec fun bezoutIdentityWithGCDInternalLogic(a: Int, b: Int, m1: Int, m2: Int, m3: Int, m4: Int): BezoutIdentityWithGCD = +internal tailrec fun bezoutIdentityWithGCDInternalLogic( + a: Int, + b: Int, + m1: Int, + m2: Int, + m3: Int, + m4: Int, +): BezoutIdentityWithGCD = if (b == 0) BezoutIdentityWithGCD(m1, m3, a) else { val quotient = a / b diff --git a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/integration/GaussIntegralTest.kt b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/integration/GaussIntegralTest.kt index 0e8f9ddfb..db6bdc6bd 100644 --- a/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/integration/GaussIntegralTest.kt +++ b/kmath-functions/src/commonTest/kotlin/space/kscience/kmath/integration/GaussIntegralTest.kt @@ -25,7 +25,7 @@ class GaussIntegralTest { @Test fun gaussUniform() { val res = Float64Field.gaussIntegrator.integrate(35.0..100.0) { x -> - if(x in 30.0..50.0){ + if (x in 30.0..50.0) { 1.0 } else { 0.0 diff --git a/kmath-geometry/README.md b/kmath-geometry/README.md index 601610d3d..263df3a87 100644 --- a/kmath-geometry/README.md +++ b/kmath-geometry/README.md @@ -1,7 +1,5 @@ # Module kmath-geometry - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-geometry:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-geometry/build.gradle.kts b/kmath-geometry/build.gradle.kts index 4bf768f4b..58bbbf5d0 100644 --- a/kmath-geometry/build.gradle.kts +++ b/kmath-geometry/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() @@ -10,7 +10,7 @@ kscience{ useContextReceivers() useSerialization() - dependencies{ + dependencies { api(projects.kmath.kmathComplex) } diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/GeometrySpace.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/GeometrySpace.kt index 8b9fcd396..d11378795 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/GeometrySpace.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/GeometrySpace.kt @@ -14,7 +14,7 @@ import space.kscience.kmath.operations.ScaleOperations * @param V the type of vector object * @param D the type of distance */ -public interface GeometrySpace> : Group, ScaleOperations, Norm { +public interface GeometrySpace> : Group, ScaleOperations, Norm { /** * L2 distance */ diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Polygon.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Polygon.kt index d7b450ab0..1d832cb8a 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Polygon.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/Polygon.kt @@ -9,6 +9,6 @@ package space.kscience.kmath.geometry /** * A closed polygon in 2D space */ -public interface Polygon { +public interface Polygon { public val points: List } \ No newline at end of file diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/angles.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/angles.kt index ff3efc126..8598bdcc9 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/angles.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/angles.kt @@ -30,7 +30,7 @@ public sealed interface Angle : Comparable { public operator fun div(other: Angle): Double public operator fun unaryMinus(): Angle - public companion object: Group { + public companion object : Group { override val zero: Radians = Radians(0.0) public val pi: Radians = Radians(PI) public val piTimes2: Radians = Radians(PI * 2) diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean2d/Float64Space2D.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean2d/Float64Space2D.kt index 37e11ba87..3925f8195 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean2d/Float64Space2D.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean2d/Float64Space2D.kt @@ -27,7 +27,6 @@ public typealias Float64Vector2D = Vector2D public typealias DoubleVector2D = Float64Vector2D - /** * 2D Euclidean space */ diff --git a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean3d/rotations3D.kt b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean3d/rotations3D.kt index 1275ad630..cebad79a2 100644 --- a/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean3d/rotations3D.kt +++ b/kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean3d/rotations3D.kt @@ -90,7 +90,7 @@ public fun Float64Space3D.rotate( /** * Rotate a [Float64] vector in 3D space with a rotation matrix */ -public fun Float64Space3D.rotate(vector: Float64Vector3D, matrix: Matrix): Vector3D { +public fun Float64Space3D.rotate(vector: Float64Vector3D, matrix: Matrix): Vector3D { require(matrix.colNum == 3 && matrix.rowNum == 3) { "Square 3x3 rotation matrix is required" } return with(linearSpace) { (matrix dot vector).asVector3D() } } diff --git a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/ProjectionAlongTest.kt b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/ProjectionAlongTest.kt index 0c2267e8b..ae4ee84e0 100644 --- a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/ProjectionAlongTest.kt +++ b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/ProjectionAlongTest.kt @@ -44,7 +44,7 @@ internal class ProjectionAlongTest { } @Test - fun projectOntoPlane() = with(Float64Space3D){ + fun projectOntoPlane() = with(Float64Space3D) { val normal = vector(1.0, 3.5, 0.07) val base = vector(2.0, -0.0037, 11.1111) diff --git a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/RotationTest.kt b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/RotationTest.kt index 9e62a086c..c802470b2 100644 --- a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/RotationTest.kt +++ b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/RotationTest.kt @@ -27,7 +27,7 @@ class RotationTest { } @Test - fun matrixConversion() = with(QuaternionAlgebra){ + fun matrixConversion() = with(QuaternionAlgebra) { val q = Quaternion(1.0, 2.0, -3.0, 4.0).normalized() @@ -45,9 +45,9 @@ class RotationTest { val reconstructed = Quaternion.fromEuler(angles, ro) - if( reconstructed.w>0) { + if (reconstructed.w > 0) { assertBufferEquals(q, reconstructed) - } else{ + } else { assertBufferEquals(q, -reconstructed) } } diff --git a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/testUtils.kt b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/testUtils.kt index 3f9c86add..22b58d260 100644 --- a/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/testUtils.kt +++ b/kmath-geometry/src/commonTest/kotlin/space/kscience/kmath/geometry/testUtils.kt @@ -18,7 +18,7 @@ fun ClosedRange.generateList(step: Double): List = generateSeque fun grid( xRange: ClosedRange, yRange: ClosedRange, - step: Double + step: Double, ): List> { val xs = xRange.generateList(step) val ys = yRange.generateList(step) @@ -26,12 +26,12 @@ fun grid( return xs.flatMap { x -> ys.map { y -> x to y } } } -fun assertVectorEquals(expected: Vector2D, actual: Vector2D, absoluteTolerance: Double = 1e-3) { +fun assertVectorEquals(expected: Vector2D, actual: Vector2D, absoluteTolerance: Double = 1e-3) { assertEquals(expected.x, actual.x, absoluteTolerance) assertEquals(expected.y, actual.y, absoluteTolerance) } -fun assertVectorEquals(expected: Vector3D, actual: Vector3D, absoluteTolerance: Double = 1e-6) { +fun assertVectorEquals(expected: Vector3D, actual: Vector3D, absoluteTolerance: Double = 1e-6) { assertEquals(expected.x, actual.x, absoluteTolerance) assertEquals(expected.y, actual.y, absoluteTolerance) assertEquals(expected.z, actual.z, absoluteTolerance) @@ -43,7 +43,7 @@ fun GeometrySpace.isCollinear(a: V, b: V, absoluteTolerance return aDist < absoluteTolerance || bDist < absoluteTolerance || abs(abs((a dot b) / (aDist * bDist)) - 1) < absoluteTolerance } -fun GeometrySpace.isOrthogonal(a: V, b: V, absoluteTolerance: Double = 1e-6): Boolean = +fun GeometrySpace.isOrthogonal(a: V, b: V, absoluteTolerance: Double = 1e-6): Boolean = abs(a dot b) < absoluteTolerance fun Double.equalFloat(other: Double, maxFloatDelta: Double = 0.000001): diff --git a/kmath-histograms/README.md b/kmath-histograms/README.md index e9aaad3a8..88f0c2dd4 100644 --- a/kmath-histograms/README.md +++ b/kmath-histograms/README.md @@ -1,7 +1,5 @@ # Module kmath-histograms - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-histograms:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-histograms/build.gradle.kts b/kmath-histograms/build.gradle.kts index 63791d61c..b7802054a 100644 --- a/kmath-histograms/build.gradle.kts +++ b/kmath-histograms/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() diff --git a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Counter.kt b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Counter.kt index acd889bf0..a931b957d 100644 --- a/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Counter.kt +++ b/kmath-histograms/src/commonMain/kotlin/space/kscience/kmath/histogram/Counter.kt @@ -19,7 +19,7 @@ public interface Counter { public companion object { public fun ofDouble(): ObjectCounter = ObjectCounter(Float64Field) - public fun of(group: Group): ObjectCounter = ObjectCounter(group) + public fun of(group: Group): ObjectCounter = ObjectCounter(group) } } diff --git a/kmath-histograms/src/jvmTest/kotlin/space/kscience/kmath/histogram/TreeHistogramTest.kt b/kmath-histograms/src/jvmTest/kotlin/space/kscience/kmath/histogram/TreeHistogramTest.kt index 25ffbbca5..3b605e9c1 100644 --- a/kmath-histograms/src/jvmTest/kotlin/space/kscience/kmath/histogram/TreeHistogramTest.kt +++ b/kmath-histograms/src/jvmTest/kotlin/space/kscience/kmath/histogram/TreeHistogramTest.kt @@ -18,14 +18,14 @@ class TreeHistogramTest { @Test fun normalFill() { - val random = Random(123) + val random = Random(123) val histogram = Histogram.custom1D(Float64Field, 0.0..1.0 step 0.1).produce { repeat(100_000) { putValue(random.nextDouble()) } } - assertTrue { histogram.bins.count() > 8} + assertTrue { histogram.bins.count() > 8 } assertEquals(100_000, histogram.bins.sumOf { it.binValue }.toInt()) } } \ No newline at end of file diff --git a/kmath-jafama/README.md b/kmath-jafama/README.md index dc183ca37..314ad47ab 100644 --- a/kmath-jafama/README.md +++ b/kmath-jafama/README.md @@ -2,14 +2,14 @@ Integration with [Jafama](https://github.com/jeffhain/jafama). - - [jafama-double](src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations based on Jafama - +- [jafama-double](src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations based on Jafama ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-jafama:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") @@ -39,6 +39,7 @@ fun main() { ## Performance -According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that on Hotspot Jafama is a bit faster. +According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that +on Hotspot Jafama is a bit faster. > **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**. diff --git a/kmath-jafama/docs/README-TEMPLATE.md b/kmath-jafama/docs/README-TEMPLATE.md index 54348467b..2973fca3b 100644 --- a/kmath-jafama/docs/README-TEMPLATE.md +++ b/kmath-jafama/docs/README-TEMPLATE.md @@ -24,6 +24,7 @@ fun main() { ## Performance -According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that on Hotspot Jafama is a bit faster. +According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that +on Hotspot Jafama is a bit faster. ${benchmarkJafamaDouble} diff --git a/kmath-jupyter/README.md b/kmath-jupyter/README.md index 525ae673b..21531f632 100644 --- a/kmath-jupyter/README.md +++ b/kmath-jupyter/README.md @@ -1,7 +1,5 @@ # Module kmath-jupyter - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-jupyter:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-kotlingrad/README.md b/kmath-kotlingrad/README.md index a66c31686..2948799d3 100644 --- a/kmath-kotlingrad/README.md +++ b/kmath-kotlingrad/README.md @@ -2,15 +2,17 @@ [Kotlin∇](https://github.com/breandan/kotlingrad) integration module. - - [differentiable-mst-expression](src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based DifferentiableExpression. - - [scalars-adapters](src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s SFun and MST - +- [differentiable-mst-expression](src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based + DifferentiableExpression. +- [scalars-adapters](src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s + SFun and MST ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-kotlingrad:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-memory/README.md b/kmath-memory/README.md index d6824add0..8d66fe37d 100644 --- a/kmath-memory/README.md +++ b/kmath-memory/README.md @@ -1,7 +1,5 @@ # Module kmath-memory - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-memory:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/Memory.kt b/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/Memory.kt index c80eb1072..7b5e0438e 100644 --- a/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/Memory.kt +++ b/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/Memory.kt @@ -43,7 +43,7 @@ public interface Memory { /** * The interface to read primitive types in this memory. */ -public interface MemoryReader: AutoCloseable { +public interface MemoryReader : AutoCloseable { /** * The underlying memory. */ @@ -96,7 +96,7 @@ public inline fun Memory.read(block: MemoryReader.() -> R): R { /** * The interface to write primitive types into this memory. */ -public interface MemoryWriter: AutoCloseable { +public interface MemoryWriter : AutoCloseable { /** * The underlying memory. */ diff --git a/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/MemorySpec.kt b/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/MemorySpec.kt index ac5dc7b92..1a8c2d74a 100644 --- a/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/MemorySpec.kt +++ b/kmath-memory/src/commonMain/kotlin/space/kscience/kmath/memory/MemorySpec.kt @@ -12,7 +12,7 @@ import space.kscience.attributes.WithType * * @param T the type of object this spec manages. */ -public interface MemorySpec: WithType { +public interface MemorySpec : WithType { /** * Size of [T] in bytes after serialization. diff --git a/kmath-memory/src/commonTest/kotlin/space/kscience/kmath/memory/MemoryTest.kt b/kmath-memory/src/commonTest/kotlin/space/kscience/kmath/memory/MemoryTest.kt index 6ca792839..57003201d 100644 --- a/kmath-memory/src/commonTest/kotlin/space/kscience/kmath/memory/MemoryTest.kt +++ b/kmath-memory/src/commonTest/kotlin/space/kscience/kmath/memory/MemoryTest.kt @@ -20,18 +20,18 @@ class MemoryTest { val memory = Memory.allocate(memorySize) memory.write { for (i in 0 until (memory.size / 4)) { - writeInt(i*4, data[i]) + writeInt(i * 4, data[i]) } } val result = memory.read { buildList { for (i in 0 until (memory.size / 4)) { - add(readInt(i*4)) + add(readInt(i * 4)) } } } - assertEquals(data,result) + assertEquals(data, result) } } \ No newline at end of file diff --git a/kmath-multik/README.md b/kmath-multik/README.md index f0bf10208..0bfc71a82 100644 --- a/kmath-multik/README.md +++ b/kmath-multik/README.md @@ -9,6 +9,7 @@ JetBrains Multik connector The Maven coordinates of this project are `space.kscience:kmath-multik:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-multik/build.gradle.kts b/kmath-multik/build.gradle.kts index 85c4d52cb..e3f27effe 100644 --- a/kmath-multik/build.gradle.kts +++ b/kmath-multik/build.gradle.kts @@ -11,16 +11,16 @@ kscience { js() } -kotlin{ - sourceSets{ - commonMain{ - dependencies{ +kotlin { + sourceSets { + commonMain { + dependencies { api(projects.kmathTensors) api("org.jetbrains.kotlinx:multik-core:$multikVersion") } } - commonTest{ - dependencies{ + commonTest { + dependencies { api("org.jetbrains.kotlinx:multik-default:$multikVersion") } } diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikDoubleAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikDoubleAlgebra.kt index 295aee876..6a8749946 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikDoubleAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikDoubleAlgebra.kt @@ -16,20 +16,22 @@ import space.kscience.kmath.operations.Float64Field import space.kscience.kmath.operations.TrigonometricOperations public class MultikDoubleAlgebra( - multikEngine: Engine + multikEngine: Engine, ) : MultikDivisionTensorAlgebra(multikEngine), TrigonometricOperations>, ExponentialOperations> { override val elementAlgebra: Float64Field get() = Float64Field override val dataType: DataType get() = DataType.DoubleDataType - override fun sin(arg: StructureND): MultikTensor = multikMath.mathEx.sin(arg.asMultik().array).wrap() + override fun sin(arg: StructureND): MultikTensor = + multikMath.mathEx.sin(arg.asMultik().array).wrap() - override fun cos(arg: StructureND): MultikTensor = multikMath.mathEx.cos(arg.asMultik().array).wrap() + override fun cos(arg: StructureND): MultikTensor = + multikMath.mathEx.cos(arg.asMultik().array).wrap() override fun tan(arg: StructureND): MultikTensor = sin(arg) / cos(arg) @PerformancePitfall - override fun asin(arg: StructureND): MultikTensor = arg.map { asin(it) } + override fun asin(arg: StructureND): MultikTensor = arg.map { asin(it) } @PerformancePitfall override fun acos(arg: StructureND): MultikTensor = arg.map { acos(it) } @@ -37,7 +39,8 @@ public class MultikDoubleAlgebra( @PerformancePitfall override fun atan(arg: StructureND): MultikTensor = arg.map { atan(it) } - override fun exp(arg: StructureND): MultikTensor = multikMath.mathEx.exp(arg.asMultik().array).wrap() + override fun exp(arg: StructureND): MultikTensor = + multikMath.mathEx.exp(arg.asMultik().array).wrap() override fun ln(arg: StructureND): MultikTensor = multikMath.mathEx.log(arg.asMultik().array).wrap() @@ -60,7 +63,7 @@ public class MultikDoubleAlgebra( @PerformancePitfall override fun atanh(arg: StructureND): MultikTensor = arg.map { atanh(it) } - override fun scalar(value: Double): MultikTensor = Multik.ndarrayOf(value).wrap() + override fun scalar(value: Double): MultikTensor = Multik.ndarrayOf(value).wrap() } //public val Double.Companion.multikAlgebra: MultikTensorAlgebra get() = MultikDoubleAlgebra diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikFloatAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikFloatAlgebra.kt index 8ce6a791c..54a60e38a 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikFloatAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikFloatAlgebra.kt @@ -12,7 +12,7 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType import space.kscience.kmath.operations.Float32Field public class MultikFloatAlgebra( - multikEngine: Engine + multikEngine: Engine, ) : MultikDivisionTensorAlgebra(multikEngine) { override val elementAlgebra: Float32Field get() = Float32Field override val dataType: DataType get() = DataType.FloatDataType diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikIntAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikIntAlgebra.kt index 06b44ece7..c6cbae554 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikIntAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikIntAlgebra.kt @@ -12,11 +12,11 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType import space.kscience.kmath.operations.Int32Ring public class MultikIntAlgebra( - multikEngine: Engine + multikEngine: Engine, ) : MultikTensorAlgebra(multikEngine) { override val elementAlgebra: Int32Ring get() = Int32Ring override val dataType: DataType get() = DataType.IntDataType - override fun scalar(value: Int): MultikTensor = Multik.ndarrayOf(value).wrap() + override fun scalar(value: Int): MultikTensor = Multik.ndarrayOf(value).wrap() } //public val Int.Companion.multikAlgebra: MultikTensorAlgebra get() = MultikIntAlgebra diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikLongAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikLongAlgebra.kt index d977326af..b30eaa580 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikLongAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikLongAlgebra.kt @@ -12,12 +12,12 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType import space.kscience.kmath.operations.Int64Ring public class MultikLongAlgebra( - multikEngine: Engine + multikEngine: Engine, ) : MultikTensorAlgebra(multikEngine) { override val elementAlgebra: Int64Ring get() = Int64Ring override val dataType: DataType get() = DataType.LongDataType - override fun scalar(value: Long): MultikTensor = Multik.ndarrayOf(value).wrap() + override fun scalar(value: Long): MultikTensor = Multik.ndarrayOf(value).wrap() } diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikShortAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikShortAlgebra.kt index caf07fef9..9403e8d6d 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikShortAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikShortAlgebra.kt @@ -12,11 +12,11 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType import space.kscience.kmath.operations.Int16Ring public class MultikShortAlgebra( - multikEngine: Engine + multikEngine: Engine, ) : MultikTensorAlgebra(multikEngine) { override val elementAlgebra: Int16Ring get() = Int16Ring override val dataType: DataType get() = DataType.ShortDataType - override fun scalar(value: Short): MultikTensor = Multik.ndarrayOf(value).wrap() + override fun scalar(value: Short): MultikTensor = Multik.ndarrayOf(value).wrap() } //public val Short.Companion.multikAlgebra: MultikTensorAlgebra get() = MultikShortAlgebra diff --git a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikTensorAlgebra.kt b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikTensorAlgebra.kt index f0212b467..c0209338c 100644 --- a/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikTensorAlgebra.kt +++ b/kmath-multik/src/commonMain/kotlin/space/kscience/kmath/multik/MultikTensorAlgebra.kt @@ -251,7 +251,12 @@ public abstract class MultikTensorAlgebra>( TODO("Not implemented for broadcasting") } - override fun diagonalEmbedding(diagonalEntries: StructureND, offset: Int, dim1: Int, dim2: Int): MultikTensor { + override fun diagonalEmbedding( + diagonalEntries: StructureND, + offset: Int, + dim1: Int, + dim2: Int, + ): MultikTensor { TODO("Diagonal embedding not implemented") } diff --git a/kmath-nd4j/README.md b/kmath-nd4j/README.md index 55d6844bc..393a2a3e4 100644 --- a/kmath-nd4j/README.md +++ b/kmath-nd4j/README.md @@ -2,16 +2,16 @@ ND4J based implementations of KMath abstractions. - - [nd4jarraystructure](#) : NDStructure wrapper for INDArray - - [nd4jarrayrings](#) : Rings over Nd4jArrayStructure of Int and Long - - [nd4jarrayfields](#) : Fields over Nd4jArrayStructure of Float and Double - +- [nd4jarraystructure](#) : NDStructure wrapper for INDArray +- [nd4jarrayrings](#) : Rings over Nd4jArrayStructure of Int and Long +- [nd4jarrayfields](#) : Fields over Nd4jArrayStructure of Float and Double ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-nd4j:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebra.kt b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebra.kt index cf0ec11c3..648e5e318 100644 --- a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebra.kt +++ b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebra.kt @@ -225,7 +225,8 @@ public open class DoubleNd4jArrayFieldOps : Nd4jArrayExtendedFieldOps +public class DoubleNd4jArrayField(override val shape: ShapeND) : DoubleNd4jArrayFieldOps(), + FieldND public fun Float64Field.nd4j(shapeFirst: Int, vararg shapeRest: Int): DoubleNd4jArrayField = DoubleNd4jArrayField(ShapeND(shapeFirst, * shapeRest)) diff --git a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jTensorAlgebra.kt b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jTensorAlgebra.kt index c69e46292..095715070 100644 --- a/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jTensorAlgebra.kt +++ b/kmath-nd4j/src/main/kotlin/space/kscience/kmath/nd4j/Nd4jTensorAlgebra.kt @@ -144,7 +144,9 @@ public sealed interface Nd4jTensorAlgebra> : AnalyticTe override fun atanh(arg: StructureND): Nd4jArrayStructure = Transforms.atanh(arg.ndArray).wrap() override fun power(arg: StructureND, pow: Number): StructureND = Transforms.pow(arg.ndArray, pow).wrap() override fun ceil(arg: StructureND): Nd4jArrayStructure = Transforms.ceil(arg.ndArray).wrap() - override fun floor(structureND: StructureND): Nd4jArrayStructure = Transforms.floor(structureND.ndArray).wrap() + override fun floor(structureND: StructureND): Nd4jArrayStructure = + Transforms.floor(structureND.ndArray).wrap() + override fun std(structureND: StructureND, dim: Int, keepDim: Boolean): Tensor = structureND.ndArray.std(true, keepDim, dim).wrap() @@ -178,7 +180,10 @@ public object DoubleNd4jTensorAlgebra : Nd4jTensorAlgebra override fun INDArray.wrap(): Nd4jArrayStructure = asDoubleStructure() @OptIn(UnsafeKMathAPI::class) - override fun mutableStructureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): Nd4jArrayStructure { + override fun mutableStructureND( + shape: ShapeND, + initializer: Float64Field.(IntArray) -> Double, + ): Nd4jArrayStructure { val array: INDArray = Nd4j.zeros(*shape.asArray()) val indices = ColumnStrides(shape) indices.asSequence().forEach { index -> diff --git a/kmath-nd4j/src/test/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebraTest.kt b/kmath-nd4j/src/test/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebraTest.kt index 704b28cd9..042dd72ac 100644 --- a/kmath-nd4j/src/test/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebraTest.kt +++ b/kmath-nd4j/src/test/kotlin/space/kscience/kmath/nd4j/Nd4jArrayAlgebraTest.kt @@ -57,7 +57,7 @@ internal class Nd4jArrayAlgebraTest { } @Test - fun testSin() = Float64Field.nd4j{ + fun testSin() = Float64Field.nd4j { val initial = structureND(2, 2) { (i, j) -> if (i == j) PI / 2 else 0.0 } val transformed = sin(initial) val expected = structureND(2, 2) { (i, j) -> if (i == j) 1.0 else 0.0 } diff --git a/kmath-optimization/README.md b/kmath-optimization/README.md index 52a018a4e..e1e44fa4d 100644 --- a/kmath-optimization/README.md +++ b/kmath-optimization/README.md @@ -1,7 +1,5 @@ # Module kmath-optimization - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-optimization:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-optimization/build.gradle.kts b/kmath-optimization/build.gradle.kts index f908b127d..d69858339 100644 --- a/kmath-optimization/build.gradle.kts +++ b/kmath-optimization/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() diff --git a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/FunctionOptimization.kt b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/FunctionOptimization.kt index a891b0a7f..263576d77 100644 --- a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/FunctionOptimization.kt +++ b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/FunctionOptimization.kt @@ -20,7 +20,7 @@ public enum class OptimizationDirection { MINIMIZE } -public object FunctionOptimizationTarget: OptimizationAttribute +public object FunctionOptimizationTarget : OptimizationAttribute public class FunctionOptimization( public val expression: DifferentiableExpression, @@ -47,7 +47,7 @@ public class FunctionOptimization( return result } - override fun toString(): String = "FunctionOptimization(features=$attributes)" + override fun toString(): String = "FunctionOptimization(attributes=$attributes)" public companion object } @@ -76,7 +76,7 @@ public suspend fun DifferentiableExpression.optimizeWith( startingPoint: Map, modifier: AttributesBuilder>.() -> Unit = {}, ): FunctionOptimization { - val problem = FunctionOptimization(this){ + val problem = FunctionOptimization(this) { startAt(startingPoint) modifier() } diff --git a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/OptimizationProblem.kt b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/OptimizationProblem.kt index b9530f83c..2ba80251b 100644 --- a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/OptimizationProblem.kt +++ b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/OptimizationProblem.kt @@ -35,7 +35,7 @@ public class OptimizationCovariance : OptimizationAttribute>, PolymorphicAttribute>(safeTypeOf()) public fun AttributesBuilder>.covariance(covariance: NamedMatrix) { - set(OptimizationCovariance(),covariance) + set(OptimizationCovariance(), covariance) } diff --git a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/QowOptimizer.kt b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/QowOptimizer.kt index eba637a83..07fa97efb 100644 --- a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/QowOptimizer.kt +++ b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/QowOptimizer.kt @@ -16,7 +16,7 @@ import space.kscience.kmath.structures.Float64Buffer import kotlin.math.abs -public object QowRuns: OptimizationAttribute +public object QowRuns : OptimizationAttribute /** diff --git a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/logLikelihood.kt b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/logLikelihood.kt index 98ec198da..a3ccbfab4 100644 --- a/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/logLikelihood.kt +++ b/kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/logLikelihood.kt @@ -64,7 +64,7 @@ public suspend fun Optimizer>.maximumLogLik FunctionOptimizationTarget(OptimizationDirection.MAXIMIZE) } ) - return XYFit(problem.data,problem.model, result.attributes) + return XYFit(problem.data, problem.model, result.attributes) } @UnstableKMathAPI diff --git a/kmath-optimization/src/commonMain/tmp/QowFit.kt b/kmath-optimization/src/commonMain/tmp/QowFit.kt index c78aef401..493ef8d12 100644 --- a/kmath-optimization/src/commonMain/tmp/QowFit.kt +++ b/kmath-optimization/src/commonMain/tmp/QowFit.kt @@ -319,10 +319,12 @@ public class QowFit( * generateErrors. */ private fun generateErrors(): Matrix { - logger?.log { """ + logger?.log { + """ Starting errors estimation using quasioptimal weights method. The starting weight is: ${curWeight.theta} - """.trimIndent()} + """.trimIndent() + } val curWeight = QoWeight(startingPoint) val covar = getCovariance(curWeight) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/CombinedMinimumBuilder.kt b/kmath-optimization/src/commonMain/tmp/minuit/CombinedMinimumBuilder.kt index 8c5452575..7cade49dc 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/CombinedMinimumBuilder.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/CombinedMinimumBuilder.kt @@ -33,7 +33,7 @@ internal class CombinedMinimumBuilder : MinimumBuilder { seed: MinimumSeed?, strategy: MnStrategy?, maxfcn: Int, - toler: Double + toler: Double, ): FunctionMinimum { val min: FunctionMinimum = theVMMinimizer.minimize(fcn!!, gc, seed, strategy, maxfcn, toler) if (!min.isValid()) { diff --git a/kmath-optimization/src/commonMain/tmp/minuit/ContoursError.kt b/kmath-optimization/src/commonMain/tmp/minuit/ContoursError.kt index 214d94c80..a9dcf652a 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/ContoursError.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/ContoursError.kt @@ -28,7 +28,7 @@ class ContoursError internal constructor( points: List, xmnos: MinosError, ymnos: MinosError, - nfcn: Int + nfcn: Int, ) { private val theNFcn: Int private val thePoints: List = points diff --git a/kmath-optimization/src/commonMain/tmp/minuit/DavidonErrorUpdator.kt b/kmath-optimization/src/commonMain/tmp/minuit/DavidonErrorUpdator.kt index 9eb2443e4..7fde0346c 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/DavidonErrorUpdator.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/DavidonErrorUpdator.kt @@ -34,8 +34,10 @@ internal class DavidonErrorUpdator : MinimumErrorUpdator { var Vupd: MnAlgebraicSymMatrix = MnUtils.sub(MnUtils.div(MnUtils.outerProduct(dx), delgam), MnUtils.div(MnUtils.outerProduct(vg), gvg)) if (delgam > gvg) { - Vupd = MnUtils.add(Vupd, - MnUtils.mul(MnUtils.outerProduct(MnUtils.sub(MnUtils.div(dx, delgam), MnUtils.div(vg, gvg))), gvg)) + Vupd = MnUtils.add( + Vupd, + MnUtils.mul(MnUtils.outerProduct(MnUtils.sub(MnUtils.div(dx, delgam), MnUtils.div(vg, gvg))), gvg) + ) } val sum_upd: Double = MnUtils.absoluteSumOfElements(Vupd) Vupd = MnUtils.add(Vupd, V0) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/FunctionMinimum.kt b/kmath-optimization/src/commonMain/tmp/minuit/FunctionMinimum.kt index e43523291..5ffc72e43 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/FunctionMinimum.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/FunctionMinimum.kt @@ -46,11 +46,15 @@ class FunctionMinimum { internal constructor(seed: MinimumSeed, up: Double) { theSeed = seed theStates = ArrayList() - theStates.add(MinimumState(seed.parameters(), - seed.error(), - seed.gradient(), - seed.parameters().fval(), - seed.nfcn())) + theStates.add( + MinimumState( + seed.parameters(), + seed.error(), + seed.gradient(), + seed.parameters().fval(), + seed.nfcn() + ) + ) theErrorDef = up theUserState = MnUserParameterState() } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MINUITFitter.kt b/kmath-optimization/src/commonMain/tmp/minuit/MINUITFitter.kt index a26321249..3838fa8af 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MINUITFitter.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MINUITFitter.kt @@ -97,6 +97,7 @@ class MINUITFitter : Fitter { when (method) { MINUIT_MINOS, MINUIT_MINIMIZE -> minuit = MnMinimize(fcn, MINUITUtils.getFitParameters(pars, fitPars), strategy) + MINUIT_SIMPLEX -> minuit = MnSimplex(fcn, MINUITUtils.getFitParameters(pars, fitPars), strategy) else -> minuit = MnMigrad(fcn, MINUITUtils.getFitParameters(pars, fitPars), strategy) } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MINUITPlugin.kt b/kmath-optimization/src/commonMain/tmp/minuit/MINUITPlugin.kt index 7eaefd9d2..4fc5822ce 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MINUITPlugin.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MINUITPlugin.kt @@ -13,10 +13,12 @@ import hep.dataforge.context.* * @author Darksnake * @version $Id: $Id */ -@PluginDef(group = "hep.dataforge", +@PluginDef( + group = "hep.dataforge", name = "MINUIT", dependsOn = ["hep.dataforge:fitting"], - info = "The MINUIT fitter engine for DataForge fitting") + info = "The MINUIT fitter engine for DataForge fitting" +) class MINUITPlugin : BasicPlugin() { fun attach(@NotNull context: Context?) { super.attach(context) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MinimumBuilder.kt b/kmath-optimization/src/commonMain/tmp/minuit/MinimumBuilder.kt index 7d918c339..8876c9575 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MinimumBuilder.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MinimumBuilder.kt @@ -40,6 +40,6 @@ interface MinimumBuilder { seed: MinimumSeed?, strategy: MnStrategy?, maxfcn: Int, - toler: Double + toler: Double, ): FunctionMinimum } \ No newline at end of file diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnApplication.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnApplication.kt index 025eea4ae..45944ac85 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnApplication.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnApplication.kt @@ -254,14 +254,16 @@ abstract class MnApplication { if (maxfcn == 0) { maxfcn = 200 + 100 * npar + 5 * npar * npar } - val min: FunctionMinimum = minimizer().minimize(theFCN, + val min: FunctionMinimum = minimizer().minimize( + theFCN, theState, theStrategy, maxfcn, toler, theErrorDef, useAnalyticalDerivatives, - checkAnalyticalDerivatives) + checkAnalyticalDerivatives + ) theNumCall += min.nfcn() theState = min.userState() return min diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnContours.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnContours.kt index 1b700f4e2..39eda5877 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnContours.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnContours.kt @@ -113,9 +113,11 @@ class MnContours(fcn: MultiFunction?, min: FunctionMinimum?, stra: MnStrategy?) return ContoursError(px, py, result, mex, mey, nfcn) } val ey: Range = mey.range() - val migrad = MnMigrad(theFCN, + val migrad = MnMigrad( + theFCN, theMinimum!!.userState().copy(), - MnStrategy(max(0, theStrategy!!.strategy() - 1))) + MnStrategy(max(0, theStrategy!!.strategy() - 1)) + ) migrad.fix(px) migrad.setValue(px, valx + ex.getSecond()) val exy_up: FunctionMinimum = migrad.minimize() @@ -131,9 +133,11 @@ class MnContours(fcn: MultiFunction?, min: FunctionMinimum?, stra: MnStrategy?) MINUITPlugin.logStatic("MnContours is unable to find lower y value for x parameter $px.") return ContoursError(px, py, result, mex, mey, nfcn) } - val migrad1 = MnMigrad(theFCN, + val migrad1 = MnMigrad( + theFCN, theMinimum!!.userState().copy(), - MnStrategy(max(0, theStrategy!!.strategy() - 1))) + MnStrategy(max(0, theStrategy!!.strategy() - 1)) + ) migrad1.fix(py) migrad1.setValue(py, valy + ey.getSecond()) val eyx_up: FunctionMinimum = migrad1.minimize() diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnFunctionCross.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnFunctionCross.kt index a05590e53..da1bed482 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnFunctionCross.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnFunctionCross.kt @@ -28,7 +28,7 @@ internal class MnFunctionCross( state: MnUserParameterState, fval: Double, stra: MnStrategy?, - errorDef: Double + errorDef: Double, ) { private val theErrorDef: Double private val theFCN: MultiFunction? @@ -249,10 +249,13 @@ internal class MnFunctionCross( } } do { - val parbol: MnParabola = MnParabolaFactory.create(MnParabolaPoint(alsb[0], flsb[0]), + val parbol: MnParabola = MnParabolaFactory.create( + MnParabolaPoint(alsb[0], flsb[0]), MnParabolaPoint(alsb[1], flsb[1]), MnParabolaPoint( - alsb[2], flsb[2])) + alsb[2], flsb[2] + ) + ) val coeff1: Double = parbol.c() val coeff2: Double = parbol.b() val coeff3: Double = parbol.a() diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnHesse.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnHesse.kt index 3bb6c4551..998324ad8 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnHesse.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnHesse.kt @@ -161,7 +161,7 @@ class MnHesse { fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, - maxcalls: Int + maxcalls: Int, ): MnUserParameterState { return calculate(fcn, MnUserParameterState(par, cov), maxcalls) } @@ -186,10 +186,12 @@ class MnHesse { val gc = Numerical2PGradientCalculator(mfcn, state.getTransformation(), theStrategy) val par = MinimumParameters(x, amin) val gra: FunctionGradient = gc.gradient(par) - val tmp: MinimumState = calculate(mfcn, + val tmp: MinimumState = calculate( + mfcn, MinimumState(par, MinimumError(MnAlgebraicSymMatrix(n), 1.0), gra, state.edm(), state.nfcn()), state.getTransformation(), - maxcalls) + maxcalls + ) return MnUserParameterState(tmp, errDef, state.getTransformation()) } @@ -326,11 +328,13 @@ class MnHesse { MINUITPlugin.logStatic("MnHesse: matrix is invalid!") MINUITPlugin.logStatic("MnHesse: matrix is not pos. def.!") MINUITPlugin.logStatic("MnHesse: matrix was forced pos. def.") - return MinimumState(st.parameters(), + return MinimumState( + st.parameters(), MinimumError(vhmat, MnMadePosDef()), gr, st.edm(), - mfcn.numOfCalls()) + mfcn.numOfCalls() + ) } //calculate edm @@ -346,11 +350,13 @@ class MnHesse { vhmat[j, j] = if (tmp < prec.eps2()) 1.0 else tmp j++ } - MinimumState(st.parameters(), + MinimumState( + st.parameters(), MinimumError(vhmat, MnHesseFailed()), st.gradient(), st.edm(), - st.nfcn() + mfcn.numOfCalls()) + st.nfcn() + mfcn.numOfCalls() + ) } } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnLineSearch.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnLineSearch.kt index 7b1171d3c..6d42ad6ac 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnLineSearch.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnLineSearch.kt @@ -28,7 +28,7 @@ internal object MnLineSearch { st: MinimumParameters, step: RealVector, gdel: Double, - prec: MnMachinePrecision + prec: MnMachinePrecision, ): MnParabolaPoint { var overal = 1000.0 var undral = -100.0 @@ -154,7 +154,8 @@ internal object MnLineSearch { val toler9: Double = max(toler8, abs(toler8 * slam)) // min. of parabola at one point if (abs(p0.x() - slam) < toler9 || abs(p1.x() - slam) < toler9 || abs( - p2.x() - slam) < toler9 + p2.x() - slam + ) < toler9 ) { return MnParabolaPoint(xvmin, fvmin) } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnMigrad.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnMigrad.kt index 22616a1a6..2c0b85561 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnMigrad.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnMigrad.kt @@ -58,9 +58,11 @@ class MnMigrad * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this( + fcn, MnUserParameterState(par, err), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + double[] for parameters and @@ -81,9 +83,11 @@ class MnMigrad * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters with default @@ -101,9 +105,11 @@ class MnMigrad * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this( + fcn, MnUserParameterState(par), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -113,10 +119,12 @@ class MnMigrad * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this( + fcn, par, cov, - DEFAULT_STRATEGY) + DEFAULT_STRATEGY + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -126,9 +134,11 @@ class MnMigrad * @param fcn a [MultiFunction] object. * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) override fun minimizer(): ModularFunctionMinimizer { return theMinimizer diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnMinimize.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnMinimize.kt index ea14a5453..dfafebba8 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnMinimize.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnMinimize.kt @@ -55,9 +55,11 @@ class MnMinimize * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this( + fcn, MnUserParameterState(par, err), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + double[] for parameters and @@ -78,9 +80,11 @@ class MnMinimize * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters with default @@ -98,9 +102,11 @@ class MnMinimize * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this( + fcn, MnUserParameterState(par), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -110,10 +116,12 @@ class MnMinimize * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this( + fcn, par, cov, - DEFAULT_STRATEGY) + DEFAULT_STRATEGY + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -123,9 +131,11 @@ class MnMinimize * @param fcn a [MultiFunction] object. * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) override fun minimizer(): ModularFunctionMinimizer { return theMinimizer diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnPrint.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnPrint.kt index ce018c2a4..6c888f1d0 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnPrint.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnPrint.kt @@ -294,12 +294,14 @@ object MnPrint { os.println(me.upperState()) } os.println("# ext. || name || value@min || negative || positive ") - os.printf("%4d||%10s||%10g||%10g||%10g\n", + os.printf( + "%4d||%10s||%10g||%10g||%10g\n", me.parameter(), me.lowerState().name(me.parameter()), me.min(), me.lower(), - me.upper()) + me.upper() + ) os.println() } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnScan.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnScan.kt index 63e565b4f..cd253778b 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnScan.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnScan.kt @@ -51,9 +51,11 @@ class MnScan(fcn: MultiFunction?, par: MnUserParameterState, str: MnStrategy) : * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this( + fcn, MnUserParameterState(par, err), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + double[] for parameters and @@ -74,9 +76,11 @@ class MnScan(fcn: MultiFunction?, par: MnUserParameterState, str: MnStrategy) : * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters with default @@ -94,9 +98,11 @@ class MnScan(fcn: MultiFunction?, par: MnUserParameterState, str: MnStrategy) : * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this( + fcn, MnUserParameterState(par), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -106,10 +112,12 @@ class MnScan(fcn: MultiFunction?, par: MnUserParameterState, str: MnStrategy) : * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this( + fcn, par, cov, - DEFAULT_STRATEGY) + DEFAULT_STRATEGY + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -119,9 +127,11 @@ class MnScan(fcn: MultiFunction?, par: MnUserParameterState, str: MnStrategy) : * @param fcn a [MultiFunction] object. * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) override fun minimizer(): ModularFunctionMinimizer { return theMinimizer diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnSeedGenerator.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnSeedGenerator.kt index a42edf4f1..4dcf89c7c 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnSeedGenerator.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnSeedGenerator.kt @@ -51,10 +51,12 @@ internal class MnSeedGenerator : MinimumSeedGenerator { val calculated: Double = hgrd.getFirst().getGradient().getEntry(i) val delta: Double = hgrd.getSecond().getEntry(i) if (abs(calculated - provided) > delta) { - MINUITPlugin.logStatic("" - + "gradient discrepancy of external parameter \"%d\" " - + "(internal parameter \"%d\") too large. Expected: \"%f\", provided: \"%f\"", - st.getTransformation().extOfInt(i), i, provided, calculated) + MINUITPlugin.logStatic( + "" + + "gradient discrepancy of external parameter \"%d\" " + + "(internal parameter \"%d\") too large. Expected: \"%f\", provided: \"%f\"", + st.getTransformation().extOfInt(i), i, provided, calculated + ) // // MINUITPlugin.logStatic("gradient discrepancy of external parameter " @@ -82,8 +84,10 @@ internal class MnSeedGenerator : MinimumSeedGenerator { dcovar = 0.0 } else { for (i in 0 until n) { - mat[i, i] = if (abs(dgrad.getGradientDerivative() - .getEntry(i)) > prec.eps2() + mat[i, i] = if (abs( + dgrad.getGradientDerivative() + .getEntry(i) + ) > prec.eps2() ) 1.0 / dgrad.getGradientDerivative().getEntry(i) else 1.0 } } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnSimplex.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnSimplex.kt index b00745f26..ef617f0a1 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnSimplex.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnSimplex.kt @@ -59,9 +59,11 @@ class MnSimplex * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, err: DoubleArray, stra: Int) : this( + fcn, MnUserParameterState(par, err), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + double[] for parameters and @@ -82,9 +84,11 @@ class MnSimplex * @param fcn a [MultiFunction] object. * @param par an array of double. */ - constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: DoubleArray, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters with default @@ -102,9 +106,11 @@ class MnSimplex * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, stra: Int) : this( + fcn, MnUserParameterState(par), - MnStrategy(stra)) + MnStrategy(stra) + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -114,10 +120,12 @@ class MnSimplex * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. * @param fcn a [MultiFunction] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance) : this( + fcn, par, cov, - DEFAULT_STRATEGY) + DEFAULT_STRATEGY + ) /** * construct from MultiFunction + MnUserParameters + MnUserCovariance @@ -127,9 +135,11 @@ class MnSimplex * @param fcn a [MultiFunction] object. * @param par a [hep.dataforge.MINUIT.MnUserParameters] object. */ - constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this(fcn, + constructor(fcn: MultiFunction?, par: MnUserParameters, cov: MnUserCovariance, stra: Int) : this( + fcn, MnUserParameterState(par, cov), - MnStrategy(stra)) + MnStrategy(stra) + ) /** {@inheritDoc} */ override fun minimizer(): ModularFunctionMinimizer { diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnUserParameterState.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnUserParameterState.kt index e80dd60a1..0dd2d8ae9 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnUserParameterState.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnUserParameterState.kt @@ -194,10 +194,14 @@ class MnUserParameterState { fix(ipar.name()) } else if (ipar.hasLimits()) { val i: Int = trafo.intOfExt(ipar.number()) - val err: Double = if (st.hasCovariance()) sqrt(2.0 * up * st.error().invHessian()[i, i]) else st.parameters().dirin().getEntry(i) - add(ipar.name(), + val err: Double = + if (st.hasCovariance()) sqrt(2.0 * up * st.error().invHessian()[i, i]) else st.parameters().dirin() + .getEntry(i) + add( + ipar.name(), trafo.int2ext(i, st.vec().getEntry(i)), - trafo.int2extError(i, st.vec().getEntry(i), err)) + trafo.int2extError(i, st.vec().getEntry(i), err) + ) if (ipar.hasLowerLimit() && ipar.hasUpperLimit()) { setLimits(ipar.name(), ipar.lowerLimit(), ipar.upperLimit()) } else if (ipar.hasLowerLimit() && !ipar.hasUpperLimit()) { @@ -207,7 +211,9 @@ class MnUserParameterState { } } else { val i: Int = trafo.intOfExt(ipar.number()) - val err: Double = if (st.hasCovariance()) sqrt(2.0 * up * st.error().invHessian()[i, i]) else st.parameters().dirin().getEntry(i) + val err: Double = + if (st.hasCovariance()) sqrt(2.0 * up * st.error().invHessian()[i, i]) else st.parameters().dirin() + .getEntry(i) add(ipar.name(), st.vec().getEntry(i), err) } } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/MnUserTransformation.kt b/kmath-optimization/src/commonMain/tmp/minuit/MnUserTransformation.kt index 1066ac2da..c587d3244 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/MnUserTransformation.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/MnUserTransformation.kt @@ -112,9 +112,11 @@ class MnUserTransformation { val parm: MinuitParameter = theParameters[theExtOfInt[i]] if (parm.hasLimits()) { dd = if (parm.hasUpperLimit() && parm.hasLowerLimit()) { - theDoubleLimTrafo.dInt2Ext(`val`, + theDoubleLimTrafo.dInt2Ext( + `val`, parm.upperLimit(), - parm.lowerLimit()) + parm.lowerLimit() + ) } else if (parm.hasUpperLimit() && !parm.hasLowerLimit()) { theUpperLimTrafo.dInt2Ext(`val`, parm.upperLimit()) } else { @@ -145,18 +147,24 @@ class MnUserTransformation { val parm: MinuitParameter = theParameters[i] return if (parm.hasLimits()) { if (parm.hasUpperLimit() && parm.hasLowerLimit()) { - theDoubleLimTrafo.ext2int(`val`, + theDoubleLimTrafo.ext2int( + `val`, parm.upperLimit(), parm.lowerLimit(), - precision()) + precision() + ) } else if (parm.hasUpperLimit() && !parm.hasLowerLimit()) { - theUpperLimTrafo.ext2int(`val`, + theUpperLimTrafo.ext2int( + `val`, parm.upperLimit(), - precision()) + precision() + ) } else { - theLowerLimTrafo.ext2int(`val`, + theLowerLimTrafo.ext2int( + `val`, parm.lowerLimit(), - precision()) + precision() + ) } } else `val` } @@ -196,9 +204,11 @@ class MnUserTransformation { val parm: MinuitParameter = theParameters[theExtOfInt[i]] return if (parm.hasLimits()) { if (parm.hasUpperLimit() && parm.hasLowerLimit()) { - theDoubleLimTrafo.int2ext(`val`, + theDoubleLimTrafo.int2ext( + `val`, parm.upperLimit(), - parm.lowerLimit()) + parm.lowerLimit() + ) } else if (parm.hasUpperLimit() && !parm.hasLowerLimit()) { theUpperLimTrafo.int2ext(`val`, parm.upperLimit()) } else { diff --git a/kmath-optimization/src/commonMain/tmp/minuit/ModularFunctionMinimizer.kt b/kmath-optimization/src/commonMain/tmp/minuit/ModularFunctionMinimizer.kt index 84130d24f..cb61e5b03 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/ModularFunctionMinimizer.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/ModularFunctionMinimizer.kt @@ -33,7 +33,7 @@ abstract class ModularFunctionMinimizer { toler: Double, errorDef: Double, useAnalyticalGradient: Boolean, - checkGradient: Boolean + checkGradient: Boolean, ): FunctionMinimum { var maxfcn = maxfcn val mfcn = MnUserFcn(fcn, errorDef, st.getTransformation()) @@ -64,7 +64,7 @@ abstract class ModularFunctionMinimizer { seed: MinimumSeed?, strategy: MnStrategy?, maxfcn: Int, - toler: Double + toler: Double, ): FunctionMinimum { return builder().minimum(mfcn, gc, seed, strategy, maxfcn, toler * mfcn.errorDef()) } diff --git a/kmath-optimization/src/commonMain/tmp/minuit/NegativeG2LineSearch.kt b/kmath-optimization/src/commonMain/tmp/minuit/NegativeG2LineSearch.kt index 2e9ce5813..50266f45c 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/NegativeG2LineSearch.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/NegativeG2LineSearch.kt @@ -54,8 +54,10 @@ internal object NegativeG2LineSearch { var step: RealVector = ArrayRealVector(n) step.setEntry(i, dgrad.getStep().getEntry(i) * dgrad.getGradient().getEntry(i)) if (abs(dgrad.getGradient().getEntry(i)) > prec.eps2()) { - step.setEntry(i, - step.getEntry(i) * (-1.0 / abs(dgrad.getGradient().getEntry(i)))) + step.setEntry( + i, + step.getEntry(i) * (-1.0 / abs(dgrad.getGradient().getEntry(i))) + ) } val gdel: Double = step.getEntry(i) * dgrad.getGradient().getEntry(i) val pp: MnParabolaPoint = MnLineSearch.search(fcn, pa, step, gdel, prec) @@ -69,8 +71,10 @@ internal object NegativeG2LineSearch { } while (iter++ < 2 * n && iterate) val mat = MnAlgebraicSymMatrix(n) for (i in 0 until n) { - mat[i, i] = if (abs(dgrad.getGradientDerivative() - .getEntry(i)) > prec.eps2() + mat[i, i] = if (abs( + dgrad.getGradientDerivative() + .getEntry(i) + ) > prec.eps2() ) 1.0 / dgrad.getGradientDerivative().getEntry(i) else 1.0 } val err = MinimumError(mat, 1.0) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/ScanBuilder.kt b/kmath-optimization/src/commonMain/tmp/minuit/ScanBuilder.kt index 57f910a26..254281beb 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/ScanBuilder.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/ScanBuilder.kt @@ -33,7 +33,7 @@ internal class ScanBuilder : MinimumBuilder { seed: MinimumSeed, stra: MnStrategy?, maxfcn: Int, - toler: Double + toler: Double, ): FunctionMinimum { val x: RealVector = seed.parameters().vec().copy() val upst = MnUserParameterState(seed.state(), mfcn.errorDef(), seed.trafo()) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/SimplexBuilder.kt b/kmath-optimization/src/commonMain/tmp/minuit/SimplexBuilder.kt index 0b10155ff..08c4f40d0 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/SimplexBuilder.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/SimplexBuilder.kt @@ -31,7 +31,7 @@ internal class SimplexBuilder : MinimumBuilder { seed: MinimumSeed, strategy: MnStrategy?, maxfcn: Int, - minedm: Double + minedm: Double, ): FunctionMinimum { val prec: MnMachinePrecision = seed.precision() val x: RealVector = seed.parameters().vec().copy() diff --git a/kmath-optimization/src/commonMain/tmp/minuit/SimplexSeedGenerator.kt b/kmath-optimization/src/commonMain/tmp/minuit/SimplexSeedGenerator.kt index 577545fc3..5423820f6 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/SimplexSeedGenerator.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/SimplexSeedGenerator.kt @@ -41,8 +41,10 @@ internal class SimplexSeedGenerator : MinimumSeedGenerator { val mat = MnAlgebraicSymMatrix(n) val dcovar = 1.0 for (i in 0 until n) { - mat[i, i] = if (abs(dgrad.getGradientDerivative() - .getEntry(i)) > prec.eps2() + mat[i, i] = if (abs( + dgrad.getGradientDerivative() + .getEntry(i) + ) > prec.eps2() ) 1.0 / dgrad.getGradientDerivative().getEntry(i) else 1.0 } val err = MinimumError(mat, dcovar) diff --git a/kmath-optimization/src/commonMain/tmp/minuit/VariableMetricBuilder.kt b/kmath-optimization/src/commonMain/tmp/minuit/VariableMetricBuilder.kt index edc6783b6..a9e4faa36 100644 --- a/kmath-optimization/src/commonMain/tmp/minuit/VariableMetricBuilder.kt +++ b/kmath-optimization/src/commonMain/tmp/minuit/VariableMetricBuilder.kt @@ -41,7 +41,7 @@ internal class VariableMetricBuilder : MinimumBuilder { seed: MinimumSeed, strategy: MnStrategy, maxfcn: Int, - edmval: Double + edmval: Double, ): FunctionMinimum { val min: FunctionMinimum = minimum(fcn, gc, seed, maxfcn, edmval) if (strategy.strategy() === 2 || strategy.strategy() === 1 && min.error().dcovar() > 0.05) { diff --git a/kmath-stat/README.md b/kmath-stat/README.md index 55ef0f693..8de601893 100644 --- a/kmath-stat/README.md +++ b/kmath-stat/README.md @@ -1,7 +1,5 @@ # Module kmath-stat - - ## Usage ## Artifact: @@ -9,6 +7,7 @@ The Maven coordinates of this project are `space.kscience:kmath-stat:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-stat/build.gradle.kts b/kmath-stat/build.gradle.kts index 7d396b460..8116a8925 100644 --- a/kmath-stat/build.gradle.kts +++ b/kmath-stat/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/distributions/NormalDistribution.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/distributions/NormalDistribution.kt index f2a1bbfe8..f425c6285 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/distributions/NormalDistribution.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/distributions/NormalDistribution.kt @@ -6,11 +6,12 @@ package space.kscience.kmath.distributions import space.kscience.kmath.chains.BlockingDoubleChain -import space.kscience.kmath.chains.Chain import space.kscience.kmath.operations.Float64Field.pow import space.kscience.kmath.random.RandomGenerator -import space.kscience.kmath.samplers.* +import space.kscience.kmath.samplers.GaussianSampler import space.kscience.kmath.samplers.InternalErf +import space.kscience.kmath.samplers.NormalizedGaussianSampler +import space.kscience.kmath.samplers.ZigguratNormalizedGaussianSampler import kotlin.math.* /** diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/random/RandomChain.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/random/RandomChain.kt index 5d175c5ae..34a92efe1 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/random/RandomChain.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/random/RandomChain.kt @@ -25,7 +25,8 @@ public class RandomChain( /** * Create a generic random chain with provided [generator] */ -public fun RandomGenerator.chain(generator: suspend RandomGenerator.() -> R): RandomChain = RandomChain(this, generator) +public fun RandomGenerator.chain(generator: suspend RandomGenerator.() -> R): RandomChain = + RandomChain(this, generator) /** * A type-specific double chunk random chain diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/InternalGamma.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/InternalGamma.kt index ef4a97066..08fefe322 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/InternalGamma.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/InternalGamma.kt @@ -123,7 +123,7 @@ internal object InternalGamma { private fun regularizedGammaP( a: Double, x: Double, - maxIterations: Int = Int.MAX_VALUE + maxIterations: Int = Int.MAX_VALUE, ): Double = when { a.isNaN() || x.isNaN() || a <= 0.0 || x < 0.0 -> Double.NaN x == 0.0 -> 0.0 @@ -155,7 +155,7 @@ internal object InternalGamma { fun regularizedGammaQ( a: Double, x: Double, - maxIterations: Int = Int.MAX_VALUE + maxIterations: Int = Int.MAX_VALUE, ): Double = when { a.isNaN() || x.isNaN() || a <= 0.0 || x < 0.0 -> Double.NaN x == 0.0 -> 1.0 diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/Sampler.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/Sampler.kt index 146a3703f..44e099a52 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/Sampler.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/samplers/Sampler.kt @@ -34,7 +34,7 @@ public fun interface Sampler { public fun Sampler.sampleBuffer( generator: RandomGenerator, size: Int, - bufferFactory: BufferFactory + bufferFactory: BufferFactory, ): Chain> { require(size > 1) //creating temporary storage once @@ -59,7 +59,7 @@ public suspend fun Sampler.next(generator: RandomGenerator): T = sa * Generates [size] samples and chunks them into some buffers. */ @JvmName("sampleRealBuffer") -public inline fun Sampler.sampleBuffer(generator: RandomGenerator, size: Int): Chain> = +public inline fun Sampler.sampleBuffer(generator: RandomGenerator, size: Int): Chain> = sampleBuffer(generator, size, BufferFactory()) diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/series/SeriesAlgebra.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/series/SeriesAlgebra.kt index 6790f44e0..e47e4f69f 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/series/SeriesAlgebra.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/series/SeriesAlgebra.kt @@ -209,7 +209,7 @@ public open class SeriesAlgebra, out BA : BufferAlgebra * */ public inline fun Buffer.zipWithShift( shift: Int = 1, - crossinline operation: A.(left: T, right: T) -> T + crossinline operation: A.(left: T, right: T) -> T, ): Buffer { val shifted = this.moveBy(shift) return zip(shifted, operation) @@ -221,7 +221,7 @@ public open class SeriesAlgebra, out BA : BufferAlgebra override fun multiply(left: Buffer, right: Buffer): Buffer = left.zip(right) { l, r -> l * r } - public fun Buffer.difference(shift: Int=1): Buffer = this.zipWithShift(shift) {l, r -> r - l} + public fun Buffer.difference(shift: Int = 1): Buffer = this.zipWithShift(shift) { l, r -> r - l } public companion object } diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Mean.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Mean.kt index 843b06f2c..846e95b18 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Mean.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/Mean.kt @@ -13,7 +13,7 @@ import space.kscience.kmath.structures.indices * Arithmetic mean */ public class Mean( - private val field: Field + private val field: Field, ) : ComposableStatistic, T>, BlockingStatistic { override fun evaluateBlocking(data: Buffer): T = with(field) { @@ -38,7 +38,7 @@ public class Mean( with(field) { first.first + second.first } to (first.second + second.second) override suspend fun toResult(intermediate: Pair): T = with(field) { - intermediate.first/ intermediate.second + intermediate.first / intermediate.second } public companion object { diff --git a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/ValueAndErrorField.kt b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/ValueAndErrorField.kt index 8f0aa1729..dc9a10661 100644 --- a/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/ValueAndErrorField.kt +++ b/kmath-stat/src/commonMain/kotlin/space/kscience/kmath/stat/ValueAndErrorField.kt @@ -85,7 +85,7 @@ public object ValueAndErrorField : Field { ): MutableBuffer { val values: DoubleArray = DoubleArray(size) val ds = DoubleArray(size) - repeat(size){ + repeat(size) { val (v, d) = builder(it) values[it] = v ds[it] = d diff --git a/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestSeries.kt b/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestSeries.kt index 68c5af6fb..461edcaf5 100644 --- a/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestSeries.kt +++ b/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestSeries.kt @@ -16,13 +16,13 @@ import kotlin.test.assertEquals class TestSeries { @Test - fun zip() = with(Double.algebra.bufferAlgebra.seriesAlgebra()){ + fun zip() = with(Double.algebra.bufferAlgebra.seriesAlgebra()) { val s1 = series(100) { sin(2 * PI * it / 100) + 1.0 } val s2 = s1.slice(20..50).moveTo(40) val s3: Buffer = s1.zip(s2) { l, r -> l + r } //s1 + s2 - assertEquals(s3.getByOffset(40),s1.getByOffset(40) + s1.getByOffset(20)) + assertEquals(s3.getByOffset(40), s1.getByOffset(40) + s1.getByOffset(20)) } } \ No newline at end of file diff --git a/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestVarianceRatioTest.kt b/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestVarianceRatioTest.kt index b5ac44bc6..1d34628c1 100644 --- a/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestVarianceRatioTest.kt +++ b/kmath-stat/src/commonTest/kotlin/space/kscience/kmath/series/TestVarianceRatioTest.kt @@ -32,7 +32,7 @@ class TestVarianceRatioTest { @Test fun volatileData() { with(Double.algebra.bufferAlgebra.seriesAlgebra()) { - val volatileData = series(10) { sin(PI * it + PI/2) + 1.0} + val volatileData = series(10) { sin(PI * it + PI / 2) + 1.0 } val resultHomo = varianceRatioTest(volatileData, 2) assertEquals(0.0, resultHomo.varianceRatio, 1e-6) // homoscedastic zScore @@ -48,7 +48,7 @@ class TestVarianceRatioTest { @Test fun negativeData() { with(Double.algebra.bufferAlgebra.seriesAlgebra()) { - val negativeData = series(10) { sin(it * 1.2)} + val negativeData = series(10) { sin(it * 1.2) } val resultHomo = varianceRatioTest(negativeData, 3) assertEquals(1.240031, resultHomo.varianceRatio, 1e-6) // homoscedastic zScore diff --git a/kmath-stat/src/jvmTest/kotlin/space/kscience/kmath/stat/MCScopeTest.kt b/kmath-stat/src/jvmTest/kotlin/space/kscience/kmath/stat/MCScopeTest.kt index a95829eff..a58b84514 100644 --- a/kmath-stat/src/jvmTest/kotlin/space/kscience/kmath/stat/MCScopeTest.kt +++ b/kmath-stat/src/jvmTest/kotlin/space/kscience/kmath/stat/MCScopeTest.kt @@ -21,7 +21,7 @@ internal class MCScopeTest { mcScope(1111) { val res = Collections.synchronizedSet(HashSet()) - launch{ + launch { //println(random) repeat(10) { delay(10) diff --git a/kmath-symja/README.md b/kmath-symja/README.md index 250c0ae35..e1b1e2359 100644 --- a/kmath-symja/README.md +++ b/kmath-symja/README.md @@ -9,6 +9,7 @@ Symja integration module The Maven coordinates of this project are `space.kscience:kmath-symja:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-tensorflow/README.md b/kmath-tensorflow/README.md index 03666129d..51c49e853 100644 --- a/kmath-tensorflow/README.md +++ b/kmath-tensorflow/README.md @@ -9,6 +9,7 @@ Google tensorflow connector The Maven coordinates of this project are `space.kscience:kmath-tensorflow:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-tensorflow/src/test/kotlin/space/kscience/kmath/tensorflow/DoubleTensorFlowOps.kt b/kmath-tensorflow/src/test/kotlin/space/kscience/kmath/tensorflow/DoubleTensorFlowOps.kt index dd4f620c4..eefc39a11 100644 --- a/kmath-tensorflow/src/test/kotlin/space/kscience/kmath/tensorflow/DoubleTensorFlowOps.kt +++ b/kmath-tensorflow/src/test/kotlin/space/kscience/kmath/tensorflow/DoubleTensorFlowOps.kt @@ -30,7 +30,7 @@ class DoubleTensorFlowOps { } @Test - fun dot(){ + fun dot() { val dim = 1000 val tensor1 = DoubleTensorAlgebra.randomNormal(shape = ShapeND(dim, dim), 12224) @@ -42,14 +42,14 @@ class DoubleTensorFlowOps { } @Test - fun extensionOps(){ + fun extensionOps() { val res = Float64Field.produceWithTF { val i = structureND(2, 2) { 0.5 } sin(i).pow(2) + cos(i).pow(2) } - assertEquals(1.0, res[0,0],0.01) + assertEquals(1.0, res[0, 0], 0.01) } diff --git a/kmath-tensors/README.md b/kmath-tensors/README.md index 34cf33cb3..27ab26cbf 100644 --- a/kmath-tensors/README.md +++ b/kmath-tensors/README.md @@ -2,16 +2,19 @@ Common linear algebra operations on tensors. - - [tensor algebra](src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic linear algebra operations on tensors (plus, dot, etc.) - - [tensor algebra with broadcasting](src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) : Basic linear algebra operations implemented with broadcasting. - - [linear algebra operations](src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc. - +- [tensor algebra](src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic linear algebra + operations on tensors (plus, dot, etc.) +- [tensor algebra with broadcasting](src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) : + Basic linear algebra operations implemented with broadcasting. +- [linear algebra operations](src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : + Advanced linear algebra operations like LU decomposition, SVD, etc. ## Artifact: The Maven coordinates of this project are `space.kscience:kmath-tensors:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-tensors/build.gradle.kts b/kmath-tensors/build.gradle.kts index 82213f408..64b253044 100644 --- a/kmath-tensors/build.gradle.kts +++ b/kmath-tensors/build.gradle.kts @@ -2,11 +2,11 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js { browser { - testTask{ + testTask { useMocha().timeout = "0" } } @@ -29,8 +29,8 @@ kotlin.sourceSets { } } - commonTest{ - dependencies{ + commonTest { + dependencies { implementation(projects.testUtils) } } diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/AnalyticTensorAlgebra.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/AnalyticTensorAlgebra.kt index a986edfa5..c8546094e 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/AnalyticTensorAlgebra.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/AnalyticTensorAlgebra.kt @@ -90,15 +90,15 @@ public interface AnalyticTensorAlgebra> : //For information: https://pytorch.org/docs/stable/generated/torch.floor.html#torch.floor public fun floor(structureND: StructureND): Tensor - override fun sin(arg: StructureND): StructureND + override fun sin(arg: StructureND): StructureND - override fun cos(arg: StructureND): StructureND + override fun cos(arg: StructureND): StructureND override fun asin(arg: StructureND): StructureND override fun acos(arg: StructureND): StructureND - override fun exp(arg: StructureND): StructureND + override fun exp(arg: StructureND): StructureND override fun ln(arg: StructureND): StructureND diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt index cea77f4ab..0024f41ad 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/DoubleTensorAlgebra.kt @@ -127,10 +127,11 @@ public open class DoubleTensorAlgebra : * @param initializer mapping tensor indices to values. * @return tensor with the [shape] shape and data generated by the [initializer]. */ - override fun mutableStructureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): DoubleTensor = fromArray( - shape, - RowStrides(shape).asSequence().map { Float64Field.initializer(it) }.toMutableList().toDoubleArray() - ) + override fun mutableStructureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): DoubleTensor = + fromArray( + shape, + RowStrides(shape).asSequence().map { Float64Field.initializer(it) }.toMutableList().toDoubleArray() + ) override fun Tensor.getTensor(i: Int): DoubleTensor { val dt = asDoubleTensor() @@ -713,7 +714,7 @@ public open class DoubleTensorAlgebra : override fun solve(a: MutableStructure2D, b: MutableStructure2D): MutableStructure2D { val aSvd = DoubleTensorAlgebra.svd(a) - val s = BroadcastDoubleTensorAlgebra.diagonalEmbedding(aSvd.second.map {1.0 / it}) + val s = BroadcastDoubleTensorAlgebra.diagonalEmbedding(aSvd.second.map { 1.0 / it }) val aInverse = aSvd.third.dot(s).dot(aSvd.first.transposed()) return aInverse.dot(b).as2D() } diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/IntTensorAlgebra.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/IntTensorAlgebra.kt index eaeb43fdc..e75564ef5 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/IntTensorAlgebra.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/IntTensorAlgebra.kt @@ -252,7 +252,7 @@ public open class IntTensorAlgebra : TensorAlgebra { override fun StructureND.transposed(i: Int, j: Int): Tensor { val actualI = if (i >= 0) i else shape.size + i - val actualJ = if(j>=0) j else shape.size + j + val actualJ = if (j >= 0) j else shape.size + j return asIntTensor().permute( shape.transposed(actualI, actualJ) ) { originIndex -> diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/broadcastUtils.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/broadcastUtils.kt index 3596cbaf8..df43a7e60 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/broadcastUtils.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/broadcastUtils.kt @@ -116,6 +116,7 @@ internal fun broadcastOuterTensors(vararg tensors: DoubleTensor): List = vectors().asSeque internal val IntTensor.matrices: VirtualBuffer - get(){ + get() { val n = shape.size check(n >= 2) { "Expected tensor with 2 or more dimensions, got size $n" } val matrixOffset = shape[n - 1] * shape[n - 2] diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt index 2a3ed87c9..239d1dd18 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/internal/linUtils.kt @@ -547,7 +547,7 @@ internal fun MutableStructure2D.svdGolubKahanHelper( h = rv1[k] f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2.0 * h * y) g = pythag(f, 1.0) - f = ((x - z) * (x + z) + h * ((y / (f + if (f >= 0.0) abs(g) else -abs(g) )) - h)) / x + f = ((x - z) * (x + z) + h * ((y / (f + if (f >= 0.0) abs(g) else -abs(g))) - h)) / x c = 1.0 s = 1.0 diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorOps.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorOps.kt index 2c35f8196..9b31e5694 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorOps.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorOps.kt @@ -214,7 +214,7 @@ public fun DoubleTensorAlgebra.svd( public fun DoubleTensorAlgebra.svdGolubKahan( structureND: StructureND, - iterations: Int = 30, epsilon: Double = 1e-10 + iterations: Int = 30, epsilon: Double = 1e-10, ): Triple { val size = structureND.dimension val commonShape = structureND.shape.slice(0 until size - 2) @@ -235,8 +235,10 @@ public fun DoubleTensorAlgebra.svdGolubKahan( matrix.shape, matrix.source.view(0, matrixSize).copy() ) - curMatrix.as2D().svdGolubKahanHelper(uTensors[index].as2D(), sTensorVectors[index], vTensors[index].as2D(), - iterations, epsilon) + curMatrix.as2D().svdGolubKahanHelper( + uTensors[index].as2D(), sTensorVectors[index], vTensors[index].as2D(), + iterations, epsilon + ) } return Triple(uTensor, sTensor, vTensor) diff --git a/kmath-viktor/README.md b/kmath-viktor/README.md index 3b7b8152a..3d5ebd95c 100644 --- a/kmath-viktor/README.md +++ b/kmath-viktor/README.md @@ -9,6 +9,7 @@ Binding for https://github.com/JetBrains-Research/viktor The Maven coordinates of this project are `space.kscience:kmath-viktor:0.4.0-dev-3`. **Gradle Kotlin DSL:** + ```kotlin repositories { maven("https://repo.kotlin.link") diff --git a/kmath-viktor/build.gradle.kts b/kmath-viktor/build.gradle.kts index 7a135f316..d15a70e9b 100644 --- a/kmath-viktor/build.gradle.kts +++ b/kmath-viktor/build.gradle.kts @@ -10,5 +10,5 @@ dependencies { } readme { - maturity = space.kscience.gradle.Maturity.DEVELOPMENT + maturity = space.kscience.gradle.Maturity.DEPRECATED } diff --git a/test-utils/build.gradle.kts b/test-utils/build.gradle.kts index b03059eaf..663b1149b 100644 --- a/test-utils/build.gradle.kts +++ b/test-utils/build.gradle.kts @@ -2,7 +2,7 @@ plugins { id("space.kscience.gradle.mpp") } -kscience{ +kscience { jvm() js() native() diff --git a/test-utils/src/commonMain/kotlin/bufferEquality.kt b/test-utils/src/commonMain/kotlin/bufferEquality.kt index 5b2ef6e76..d4fd99506 100644 --- a/test-utils/src/commonMain/kotlin/bufferEquality.kt +++ b/test-utils/src/commonMain/kotlin/bufferEquality.kt @@ -17,4 +17,5 @@ public fun Float64Buffer.contentEquals(vararg doubles: Double): Boolean = array. public infix fun Float64Buffer.contentEquals(otherArray: DoubleArray): Boolean = array.contentEquals(otherArray) @JvmName("contentEqualsBuffer") -public infix fun Float64Buffer.contentEquals(otherBuffer: Float64Buffer): Boolean = array.contentEquals(otherBuffer.array) \ No newline at end of file +public infix fun Float64Buffer.contentEquals(otherBuffer: Float64Buffer): Boolean = + array.contentEquals(otherBuffer.array) \ No newline at end of file