Compare commits
No commits in common. "48b334a2b607c884e18edd764f2a61bcd9bdcd14" and "82196250f651d0ba82eb89a1ac3b008b2af184a1" have entirely different histories.
48b334a2b6
...
82196250f6
12
CHANGELOG.md
12
CHANGELOG.md
@ -77,8 +77,7 @@
|
|||||||
- Major refactor of tensors (only minor API changes)
|
- Major refactor of tensors (only minor API changes)
|
||||||
- Kotlin 1.8.20
|
- Kotlin 1.8.20
|
||||||
- `LazyStructure` `deffered` -> `async` to comply with coroutines code style
|
- `LazyStructure` `deffered` -> `async` to comply with coroutines code style
|
||||||
- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added
|
- Default `dot` operation in tensor algebra no longer support broadcasting. Instead `matmul` operation is added to `DoubleTensorAlgebra`.
|
||||||
to `DoubleTensorAlgebra`.
|
|
||||||
- Multik went MPP
|
- Multik went MPP
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
@ -237,11 +236,9 @@
|
|||||||
- MST to JVM bytecode translator (https://github.com/mipt-npm/kmath/pull/94)
|
- MST to JVM bytecode translator (https://github.com/mipt-npm/kmath/pull/94)
|
||||||
- FloatBuffer (specialized MutableBuffer over FloatArray)
|
- FloatBuffer (specialized MutableBuffer over FloatArray)
|
||||||
- FlaggedBuffer to associate primitive numbers buffer with flags (to mark values infinite or missing, etc.)
|
- FlaggedBuffer to associate primitive numbers buffer with flags (to mark values infinite or missing, etc.)
|
||||||
- Specialized builder functions for all primitive buffers
|
- Specialized builder functions for all primitive buffers like `IntBuffer(25) { it + 1 }` (https://github.com/mipt-npm/kmath/pull/125)
|
||||||
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
|
- Interface `NumericAlgebra` where `number` operation is available to convert numbers to algebraic elements
|
||||||
- Inverse trigonometric functions support in
|
- Inverse trigonometric functions support in ExtendedField (`asin`, `acos`, `atan`) (https://github.com/mipt-npm/kmath/pull/114)
|
||||||
ExtendedField (`asin`, `acos`, `atan`) (https://github.com/mipt-npm/kmath/pull/114)
|
|
||||||
- New space extensions: `average` and `averageWith`
|
- New space extensions: `average` and `averageWith`
|
||||||
- Local coding conventions
|
- Local coding conventions
|
||||||
- Geometric Domains API in `kmath-core`
|
- Geometric Domains API in `kmath-core`
|
||||||
@ -254,8 +251,7 @@
|
|||||||
- `readAsMemory` now has `throws IOException` in JVM signature.
|
- `readAsMemory` now has `throws IOException` in JVM signature.
|
||||||
- Several functions taking functional types were made `inline`.
|
- Several functions taking functional types were made `inline`.
|
||||||
- Several functions taking functional types now have `callsInPlace` contracts.
|
- Several functions taking functional types now have `callsInPlace` contracts.
|
||||||
- BigInteger and BigDecimal algebra: JBigDecimalField has companion object with default math context; minor
|
- BigInteger and BigDecimal algebra: JBigDecimalField has companion object with default math context; minor optimizations
|
||||||
optimizations
|
|
||||||
- `power(T, Int)` extension function has preconditions and supports `Field<T>`
|
- `power(T, Int)` extension function has preconditions and supports `Field<T>`
|
||||||
- Memory objects have more preconditions (overflow checking)
|
- Memory objects have more preconditions (overflow checking)
|
||||||
- `tg` function is renamed to `tan` (https://github.com/mipt-npm/kmath/pull/114)
|
- `tg` function is renamed to `tan` (https://github.com/mipt-npm/kmath/pull/114)
|
||||||
|
127
README.md
127
README.md
@ -25,8 +25,7 @@ experience could be achieved with [kmath-for-real](/kmath-for-real) extension mo
|
|||||||
|
|
||||||
# Goal
|
# Goal
|
||||||
|
|
||||||
* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and
|
* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and Wasm).
|
||||||
Wasm).
|
|
||||||
* Provide basic multiplatform implementations for those abstractions (without significant performance optimization).
|
* Provide basic multiplatform implementations for those abstractions (without significant performance optimization).
|
||||||
* Provide bindings and wrappers with those abstractions for popular optimized platform libraries.
|
* Provide bindings and wrappers with those abstractions for popular optimized platform libraries.
|
||||||
|
|
||||||
@ -56,181 +55,150 @@ module definitions below. The module stability could have the following levels:
|
|||||||
|
|
||||||
## Modules
|
## Modules
|
||||||
|
|
||||||
### [attributes-kt](attributes-kt)
|
|
||||||
|
|
||||||
|
### [attributes-kt](attributes-kt)
|
||||||
> An API and basic implementation for arranging objects in a continuous memory block.
|
> An API and basic implementation for arranging objects in a continuous memory block.
|
||||||
>
|
>
|
||||||
> **Maturity**: DEVELOPMENT
|
> **Maturity**: DEVELOPMENT
|
||||||
|
|
||||||
### [benchmarks](benchmarks)
|
### [benchmarks](benchmarks)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [examples](examples)
|
### [examples](examples)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [kmath-ast](kmath-ast)
|
### [kmath-ast](kmath-ast)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [expression-language](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/parser.kt) : Expression language and
|
> - [expression-language](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/parser.kt) : Expression language and its parser
|
||||||
its parser
|
> - [mst-jvm-codegen](kmath-ast/src/jvmMain/kotlin/space/kscience/kmath/asm/asm.kt) : Dynamic MST to JVM bytecode compiler
|
||||||
> - [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
|
> - [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](kmath-ast/src/commonMain/kotlin/space/kscience/kmath/ast/rendering/MathRenderer.kt) : Extendable MST rendering
|
||||||
rendering
|
|
||||||
|
|
||||||
### [kmath-commons](kmath-commons)
|
### [kmath-commons](kmath-commons)
|
||||||
|
|
||||||
> Commons math binding for kmath
|
> Commons math binding for kmath
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [kmath-complex](kmath-complex)
|
### [kmath-complex](kmath-complex)
|
||||||
|
|
||||||
> Complex numbers and quaternions.
|
> Complex numbers and quaternions.
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [complex](kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt) : Complex numbers operations
|
> - [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
|
> - [quaternion](kmath-complex/src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their composition
|
||||||
composition
|
|
||||||
|
|
||||||
### [kmath-core](kmath-core)
|
### [kmath-core](kmath-core)
|
||||||
|
|
||||||
> Core classes, algebra definitions, basic linear algebra
|
> Core classes, algebra definitions, basic linear algebra
|
||||||
>
|
>
|
||||||
> **Maturity**: DEVELOPMENT
|
> **Maturity**: DEVELOPMENT
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [algebras](kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like
|
> - [algebras](kmath-core/src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces and fields.
|
||||||
rings, spaces and fields.
|
> - [nd](kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and operations on them.
|
||||||
> - [nd](kmath-core/src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures
|
> - [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.
|
||||||
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
|
> - [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
|
> - [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
|
||||||
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
|
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.
|
performance calculations to code generation.
|
||||||
> - [domains](kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
|
> - [domains](kmath-core/src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
|
||||||
> - [autodiff](kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic
|
> - [autodiff](kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic differentiation
|
||||||
differentiation
|
|
||||||
|
|
||||||
### [kmath-coroutines](kmath-coroutines)
|
### [kmath-coroutines](kmath-coroutines)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [kmath-dimensions](kmath-dimensions)
|
### [kmath-dimensions](kmath-dimensions)
|
||||||
|
|
||||||
> A proof of concept module for adding type-safe dimensions to structures
|
> A proof of concept module for adding type-safe dimensions to structures
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-ejml](kmath-ejml)
|
### [kmath-ejml](kmath-ejml)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [ejml-vector](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlVector.kt) : Point implementations.
|
> - [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-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
|
> - [ejml-linear-space](kmath-ejml/src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace implementations.
|
||||||
implementations.
|
|
||||||
|
|
||||||
### [kmath-for-real](kmath-for-real)
|
### [kmath-for-real](kmath-for-real)
|
||||||
|
|
||||||
> Extension module that should be used to achieve numpy-like behavior.
|
> Extension module that should be used to achieve numpy-like behavior.
|
||||||
> All operations are specialized to work with `Double` numbers without declaring algebraic contexts.
|
All operations are specialized to work with `Double` numbers without declaring algebraic contexts.
|
||||||
> One can still use generic algebras though.
|
One can still use generic algebras though.
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [DoubleVector](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like
|
> - [DoubleVector](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for Buffers/Points
|
||||||
operations for Buffers/Points
|
> - [DoubleMatrix](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like operations for 2d real structures
|
||||||
> - [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
|
> - [grids](kmath-for-real/src/commonMain/kotlin/space/kscience/kmath/structures/grids.kt) : Uniform grid generators
|
||||||
|
|
||||||
### [kmath-functions](kmath-functions)
|
|
||||||
|
|
||||||
|
### [kmath-functions](kmath-functions)
|
||||||
> Functions, integration and interpolation
|
> Functions, integration and interpolation
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [piecewise](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise
|
> - [piecewise](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions.
|
||||||
functions.
|
> - [polynomials](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial functions.
|
||||||
> - [polynomials](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial
|
> - [linear interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : Linear XY interpolator.
|
||||||
functions.
|
> - [spline interpolation](kmath-functions/src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline XY interpolator.
|
||||||
> - [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
|
> - [integration](kmath-functions/#) : Univariate and multivariate quadratures
|
||||||
|
|
||||||
### [kmath-geometry](kmath-geometry)
|
|
||||||
|
|
||||||
|
### [kmath-geometry](kmath-geometry)
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-histograms](kmath-histograms)
|
### [kmath-histograms](kmath-histograms)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-jafama](kmath-jafama)
|
### [kmath-jafama](kmath-jafama)
|
||||||
|
|
||||||
> Jafama integration module
|
> Jafama integration module
|
||||||
>
|
>
|
||||||
> **Maturity**: DEPRECATED
|
> **Maturity**: DEPRECATED
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [jafama-double](kmath-jafama/src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations
|
> - [jafama-double](kmath-jafama/src/main/kotlin/space/kscience/kmath/jafama/) : Double ExtendedField implementations based on Jafama
|
||||||
based on Jafama
|
|
||||||
|
|
||||||
### [kmath-jupyter](kmath-jupyter)
|
### [kmath-jupyter](kmath-jupyter)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-kotlingrad](kmath-kotlingrad)
|
### [kmath-kotlingrad](kmath-kotlingrad)
|
||||||
|
|
||||||
> Kotlin∇ integration module
|
> Kotlin∇ integration module
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [differentiable-mst-expression](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) :
|
> - [differentiable-mst-expression](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based DifferentiableExpression.
|
||||||
MST based DifferentiableExpression.
|
> - [scalars-adapters](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s SFun and MST
|
||||||
> - [scalars-adapters](kmath-kotlingrad/src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) :
|
|
||||||
Conversions between Kotlin∇'s SFun and MST
|
|
||||||
|
|
||||||
### [kmath-memory](kmath-memory)
|
### [kmath-memory](kmath-memory)
|
||||||
|
|
||||||
> An API and basic implementation for arranging objects in a continuous memory block.
|
> An API and basic implementation for arranging objects in a continuous memory block.
|
||||||
>
|
>
|
||||||
> **Maturity**: DEVELOPMENT
|
> **Maturity**: DEVELOPMENT
|
||||||
|
|
||||||
### [kmath-multik](kmath-multik)
|
### [kmath-multik](kmath-multik)
|
||||||
|
|
||||||
> JetBrains Multik connector
|
> JetBrains Multik connector
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-nd4j](kmath-nd4j)
|
### [kmath-nd4j](kmath-nd4j)
|
||||||
|
|
||||||
> ND4J NDStructure implementation and according NDAlgebra classes
|
> ND4J NDStructure implementation and according NDAlgebra classes
|
||||||
>
|
>
|
||||||
> **Maturity**: DEPRECATED
|
> **Maturity**: DEPRECATED
|
||||||
@ -240,52 +208,45 @@ module definitions below. The module stability could have the following levels:
|
|||||||
> - [nd4jarrayrings](kmath-nd4j/#) : Rings over Nd4jArrayStructure of Int and Long
|
> - [nd4jarrayrings](kmath-nd4j/#) : Rings over Nd4jArrayStructure of Int and Long
|
||||||
> - [nd4jarrayfields](kmath-nd4j/#) : Fields over Nd4jArrayStructure of Float and Double
|
> - [nd4jarrayfields](kmath-nd4j/#) : Fields over Nd4jArrayStructure of Float and Double
|
||||||
|
|
||||||
### [kmath-optimization](kmath-optimization)
|
|
||||||
|
|
||||||
|
### [kmath-optimization](kmath-optimization)
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [kmath-stat](kmath-stat)
|
### [kmath-stat](kmath-stat)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
### [kmath-symja](kmath-symja)
|
### [kmath-symja](kmath-symja)
|
||||||
|
|
||||||
> Symja integration module
|
> Symja integration module
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-tensorflow](kmath-tensorflow)
|
### [kmath-tensorflow](kmath-tensorflow)
|
||||||
|
|
||||||
> Google tensorflow connector
|
> Google tensorflow connector
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
|
|
||||||
### [kmath-tensors](kmath-tensors)
|
### [kmath-tensors](kmath-tensors)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: PROTOTYPE
|
> **Maturity**: PROTOTYPE
|
||||||
>
|
>
|
||||||
> **Features:**
|
> **Features:**
|
||||||
> - [tensor algebra](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic
|
> - [tensor algebra](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/TensorAlgebra.kt) : Basic linear algebra operations on tensors (plus, dot, etc.)
|
||||||
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.
|
||||||
> - [tensor algebra with broadcasting](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/BroadcastDoubleTensorAlgebra.kt) :
|
> - [linear algebra operations](kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/api/LinearOpsTensorAlgebra.kt) : Advanced linear algebra operations like LU decomposition, SVD, etc.
|
||||||
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)
|
### [kmath-viktor](kmath-viktor)
|
||||||
|
|
||||||
> Binding for https://github.com/JetBrains-Research/viktor
|
> Binding for https://github.com/JetBrains-Research/viktor
|
||||||
>
|
>
|
||||||
> **Maturity**: DEVELOPMENT
|
> **Maturity**: DEVELOPMENT
|
||||||
|
|
||||||
### [test-utils](test-utils)
|
### [test-utils](test-utils)
|
||||||
|
|
||||||
>
|
>
|
||||||
> **Maturity**: EXPERIMENTAL
|
> **Maturity**: EXPERIMENTAL
|
||||||
|
|
||||||
|
|
||||||
## Multi-platform support
|
## Multi-platform support
|
||||||
|
|
||||||
KMath is developed as a multi-platform library, which means that most of the interfaces are declared in the
|
KMath is developed as a multi-platform library, which means that most of the interfaces are declared in the
|
||||||
@ -296,19 +257,16 @@ feedback are also welcome.
|
|||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to
|
Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to achieve both
|
||||||
achieve both
|
|
||||||
performance and flexibility.
|
performance and flexibility.
|
||||||
|
|
||||||
We expect to focus on creating a convenient universal API first and then work on increasing performance for specific
|
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
|
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
|
native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be better than SciPy.
|
||||||
better than SciPy.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or
|
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.
|
||||||
Oracle GraalVM for execution to get better performance.
|
|
||||||
|
|
||||||
### Repositories
|
### Repositories
|
||||||
|
|
||||||
@ -331,7 +289,4 @@ dependencies {
|
|||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
The project requires a lot of additional work. The most important thing we need is feedback about what features are
|
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
|
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.
|
||||||
marked
|
|
||||||
with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
|
||||||
label.
|
|
@ -3,7 +3,7 @@ plugins {
|
|||||||
`maven-publish`
|
`maven-publish`
|
||||||
}
|
}
|
||||||
|
|
||||||
version = rootProject.extra.get("attributesVersion").toString()
|
version = "0.1.0"
|
||||||
|
|
||||||
kscience {
|
kscience {
|
||||||
jvm()
|
jvm()
|
||||||
|
@ -30,28 +30,20 @@ public interface Attributes {
|
|||||||
override fun hashCode(): Int
|
override fun hashCode(): Int
|
||||||
|
|
||||||
public companion object {
|
public companion object {
|
||||||
public val EMPTY: Attributes = object : Attributes {
|
public val EMPTY: Attributes = AttributesImpl(emptyMap())
|
||||||
override val content: Map<out Attribute<*>, Any?> get() = emptyMap()
|
|
||||||
|
|
||||||
override fun toString(): String = "Attributes.EMPTY"
|
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean = (other as? Attributes)?.isEmpty() ?: false
|
|
||||||
|
|
||||||
override fun hashCode(): Int = Unit.hashCode()
|
|
||||||
}
|
|
||||||
|
|
||||||
public fun equals(a1: Attributes, a2: Attributes): Boolean =
|
public fun equals(a1: Attributes, a2: Attributes): Boolean =
|
||||||
a1.keys == a2.keys && a1.keys.all { a1[it] == a2[it] }
|
a1.keys == a2.keys && a1.keys.all { a1[it] == a2[it] }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class MapAttributes(override val content: Map<out Attribute<*>, Any?>) : Attributes {
|
internal class AttributesImpl(override val content: Map<out Attribute<*>, Any?>) : Attributes {
|
||||||
override fun toString(): String = "Attributes(value=${content.entries})"
|
override fun toString(): String = "Attributes(value=${content.entries})"
|
||||||
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
|
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
|
||||||
override fun hashCode(): Int = content.hashCode()
|
override fun hashCode(): Int = content.hashCode()
|
||||||
}
|
}
|
||||||
|
|
||||||
public fun Attributes.isEmpty(): Boolean = keys.isEmpty()
|
public fun Attributes.isEmpty(): Boolean = content.isEmpty()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get attribute value or default
|
* Get attribute value or default
|
||||||
@ -83,7 +75,7 @@ public inline fun <reified A : FlagAttribute> Attributes.hasFlag(): Boolean =
|
|||||||
public fun <T, A : Attribute<T>> Attributes.withAttribute(
|
public fun <T, A : Attribute<T>> Attributes.withAttribute(
|
||||||
attribute: A,
|
attribute: A,
|
||||||
attrValue: T,
|
attrValue: T,
|
||||||
): Attributes = MapAttributes(content + (attribute to attrValue))
|
): Attributes = AttributesImpl(content + (attribute to attrValue))
|
||||||
|
|
||||||
public fun <A : Attribute<Unit>> Attributes.withAttribute(attribute: A): Attributes =
|
public fun <A : Attribute<Unit>> Attributes.withAttribute(attribute: A): Attributes =
|
||||||
withAttribute(attribute, Unit)
|
withAttribute(attribute, Unit)
|
||||||
@ -91,15 +83,15 @@ public fun <A : Attribute<Unit>> Attributes.withAttribute(attribute: A): Attribu
|
|||||||
/**
|
/**
|
||||||
* Create a new [Attributes] by modifying the current one
|
* Create a new [Attributes] by modifying the current one
|
||||||
*/
|
*/
|
||||||
public fun <O> Attributes.modified(block: AttributesBuilder<O>.() -> Unit): Attributes = Attributes<O> {
|
public fun <T> Attributes.modify(block: AttributesBuilder<T>.() -> Unit): Attributes = Attributes<T> {
|
||||||
putAll(this@modified)
|
from(this@modify)
|
||||||
block()
|
block()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create new [Attributes] by removing [attribute] key
|
* Create new [Attributes] by removing [attribute] key
|
||||||
*/
|
*/
|
||||||
public fun Attributes.withoutAttribute(attribute: Attribute<*>): Attributes = MapAttributes(content.minus(attribute))
|
public fun Attributes.withoutAttribute(attribute: Attribute<*>): Attributes = AttributesImpl(content.minus(attribute))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add an element to a [SetAttribute]
|
* Add an element to a [SetAttribute]
|
||||||
@ -109,7 +101,7 @@ public fun <T, A : SetAttribute<T>> Attributes.withAttributeElement(
|
|||||||
attrValue: T,
|
attrValue: T,
|
||||||
): Attributes {
|
): Attributes {
|
||||||
val currentSet: Set<T> = get(attribute) ?: emptySet()
|
val currentSet: Set<T> = get(attribute) ?: emptySet()
|
||||||
return MapAttributes(
|
return AttributesImpl(
|
||||||
content + (attribute to (currentSet + attrValue))
|
content + (attribute to (currentSet + attrValue))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -122,7 +114,7 @@ public fun <T, A : SetAttribute<T>> Attributes.withoutAttributeElement(
|
|||||||
attrValue: T,
|
attrValue: T,
|
||||||
): Attributes {
|
): Attributes {
|
||||||
val currentSet: Set<T> = get(attribute) ?: emptySet()
|
val currentSet: Set<T> = get(attribute) ?: emptySet()
|
||||||
return MapAttributes(content + (attribute to (currentSet - attrValue)))
|
return AttributesImpl(content + (attribute to (currentSet - attrValue)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -131,13 +123,13 @@ public fun <T, A : SetAttribute<T>> Attributes.withoutAttributeElement(
|
|||||||
public fun <T, A : Attribute<T>> Attributes(
|
public fun <T, A : Attribute<T>> Attributes(
|
||||||
attribute: A,
|
attribute: A,
|
||||||
attrValue: T,
|
attrValue: T,
|
||||||
): Attributes = MapAttributes(mapOf(attribute to attrValue))
|
): Attributes = AttributesImpl(mapOf(attribute to attrValue))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create Attributes with a single [Unit] valued attribute
|
* Create Attributes with a single [Unit] valued attribute
|
||||||
*/
|
*/
|
||||||
public fun <A : Attribute<Unit>> Attributes(
|
public fun <A : Attribute<Unit>> Attributes(
|
||||||
attribute: A,
|
attribute: A,
|
||||||
): Attributes = MapAttributes(mapOf(attribute to Unit))
|
): Attributes = AttributesImpl(mapOf(attribute to Unit))
|
||||||
|
|
||||||
public operator fun Attributes.plus(other: Attributes): Attributes = MapAttributes(content + other.content)
|
public operator fun Attributes.plus(other: Attributes): Attributes = AttributesImpl(content + other.content)
|
@ -6,18 +6,19 @@
|
|||||||
package space.kscience.attributes
|
package space.kscience.attributes
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for [Attributes].
|
* A safe builder for [Attributes]
|
||||||
* The builder is not thread safe
|
|
||||||
*
|
*
|
||||||
* @param O type marker of an owner object, for which these attributes are made
|
* @param O type marker of an owner object, for which these attributes are made
|
||||||
*/
|
*/
|
||||||
public class AttributesBuilder<out O> internal constructor() : Attributes {
|
public class AttributesBuilder<out O> internal constructor(
|
||||||
|
private val map: MutableMap<Attribute<*>, Any?>,
|
||||||
|
) : Attributes {
|
||||||
|
|
||||||
private val map = mutableMapOf<Attribute<*>, Any?>()
|
public constructor() : this(mutableMapOf())
|
||||||
|
|
||||||
override fun toString(): String = "Attributes(value=${map.entries})"
|
override fun toString(): String = "Attributes(value=${content.entries})"
|
||||||
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
|
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
|
||||||
override fun hashCode(): Int = map.hashCode()
|
override fun hashCode(): Int = content.hashCode()
|
||||||
|
|
||||||
override val content: Map<out Attribute<*>, Any?> get() = map
|
override val content: Map<out Attribute<*>, Any?> get() = map
|
||||||
|
|
||||||
@ -33,18 +34,13 @@ public class AttributesBuilder<out O> internal constructor() : Attributes {
|
|||||||
set(this, value)
|
set(this, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
public infix fun <V> Attribute<V>.put(value: V?) {
|
public fun from(attributes: Attributes) {
|
||||||
set(this, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Put all attributes for given [attributes]
|
|
||||||
*/
|
|
||||||
public fun putAll(attributes: Attributes) {
|
|
||||||
map.putAll(attributes.content)
|
map.putAll(attributes.content)
|
||||||
}
|
}
|
||||||
|
|
||||||
public infix fun <V> SetAttribute<V>.add(attrValue: V) {
|
public fun <V> SetAttribute<V>.add(
|
||||||
|
attrValue: V,
|
||||||
|
) {
|
||||||
val currentSet: Set<V> = get(this) ?: emptySet()
|
val currentSet: Set<V> = get(this) ?: emptySet()
|
||||||
map[this] = currentSet + attrValue
|
map[this] = currentSet + attrValue
|
||||||
}
|
}
|
||||||
@ -52,17 +48,15 @@ public class AttributesBuilder<out O> internal constructor() : Attributes {
|
|||||||
/**
|
/**
|
||||||
* Remove an element from [SetAttribute]
|
* Remove an element from [SetAttribute]
|
||||||
*/
|
*/
|
||||||
public infix fun <V> SetAttribute<V>.remove(attrValue: V) {
|
public fun <V> SetAttribute<V>.remove(
|
||||||
|
attrValue: V,
|
||||||
|
) {
|
||||||
val currentSet: Set<V> = get(this) ?: emptySet()
|
val currentSet: Set<V> = get(this) ?: emptySet()
|
||||||
map[this] = currentSet - attrValue
|
map[this] = currentSet - attrValue
|
||||||
}
|
}
|
||||||
|
|
||||||
public fun build(): Attributes = MapAttributes(map)
|
public fun build(): Attributes = AttributesImpl(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public inline fun <O> Attributes(builder: AttributesBuilder<O>.() -> Unit): Attributes =
|
||||||
* Create [Attributes] with a given [builder]
|
|
||||||
* @param O the type for which attributes are built. The type is used only during compilation phase for static extension dispatch
|
|
||||||
*/
|
|
||||||
public fun <O> Attributes(builder: AttributesBuilder<O>.() -> Unit): Attributes =
|
|
||||||
AttributesBuilder<O>().apply(builder).build()
|
AttributesBuilder<O>().apply(builder).build()
|
@ -21,14 +21,11 @@ public abstract class PolymorphicAttribute<T>(public val type: SafeType<T>) : At
|
|||||||
/**
|
/**
|
||||||
* Get a polymorphic attribute using attribute factory
|
* Get a polymorphic attribute using attribute factory
|
||||||
*/
|
*/
|
||||||
@UnstableAttributesAPI
|
public operator fun <T> Attributes.get(attributeKeyBuilder: () -> PolymorphicAttribute<T>): T? = get(attributeKeyBuilder())
|
||||||
public operator fun <T> Attributes.get(attributeKeyBuilder: () -> PolymorphicAttribute<T>): T? =
|
|
||||||
get(attributeKeyBuilder())
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set a polymorphic attribute using its factory
|
* Set a polymorphic attribute using its factory
|
||||||
*/
|
*/
|
||||||
@UnstableAttributesAPI
|
|
||||||
public operator fun <O, T> AttributesBuilder<O>.set(attributeKeyBuilder: () -> PolymorphicAttribute<T>, value: T) {
|
public operator fun <O, T> AttributesBuilder<O>.set(attributeKeyBuilder: () -> PolymorphicAttribute<T>, value: T) {
|
||||||
set(attributeKeyBuilder(), value)
|
set(attributeKeyBuilder(), value)
|
||||||
}
|
}
|
||||||
|
@ -94,7 +94,6 @@ class ExpressionsInterpretersBenchmark {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private val mst = node.toExpression(Float64Field)
|
private val mst = node.toExpression(Float64Field)
|
||||||
|
|
||||||
@OptIn(UnstableKMathAPI::class)
|
@OptIn(UnstableKMathAPI::class)
|
||||||
private val wasm = node.wasmCompileToExpression(Float64Field)
|
private val wasm = node.wasmCompileToExpression(Float64Field)
|
||||||
private val estree = node.estreeCompileToExpression(Float64Field)
|
private val estree = node.estreeCompileToExpression(Float64Field)
|
||||||
|
@ -13,6 +13,8 @@ import space.kscience.kmath.jafama.JafamaDoubleField
|
|||||||
import space.kscience.kmath.jafama.StrictJafamaDoubleField
|
import space.kscience.kmath.jafama.StrictJafamaDoubleField
|
||||||
import space.kscience.kmath.operations.Float64Field
|
import space.kscience.kmath.operations.Float64Field
|
||||||
import space.kscience.kmath.operations.invoke
|
import space.kscience.kmath.operations.invoke
|
||||||
|
import kotlin.contracts.InvocationKind
|
||||||
|
import kotlin.contracts.contract
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
|
|
||||||
@State(Scope.Benchmark)
|
@State(Scope.Benchmark)
|
||||||
@ -34,6 +36,7 @@ internal class JafamaBenchmark {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private inline fun invokeBenchmarks(blackhole: Blackhole, expr: (Double) -> Double) {
|
private inline fun invokeBenchmarks(blackhole: Blackhole, expr: (Double) -> Double) {
|
||||||
|
contract { callsInPlace(expr, InvocationKind.AT_LEAST_ONCE) }
|
||||||
val rng = Random(0)
|
val rng = Random(0)
|
||||||
repeat(1000000) { blackhole.consume(expr(rng.nextDouble())) }
|
repeat(1000000) { blackhole.consume(expr(rng.nextDouble())) }
|
||||||
}
|
}
|
||||||
|
@ -6,8 +6,6 @@ plugins {
|
|||||||
id("org.jetbrains.kotlinx.kover") version "0.7.6"
|
id("org.jetbrains.kotlinx.kover") version "0.7.6"
|
||||||
}
|
}
|
||||||
|
|
||||||
val attributesVersion by extra("0.1.0")
|
|
||||||
|
|
||||||
allprojects {
|
allprojects {
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -63,8 +63,7 @@ fun Project.addBenchmarkProperties() {
|
|||||||
if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) {
|
if (resDirectory == null || !(resDirectory.resolve("jvm.json")).exists()) {
|
||||||
"> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**."
|
"> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**."
|
||||||
} else {
|
} else {
|
||||||
val reports: List<JmhReport> =
|
val reports: List<JmhReport> = jsonMapper.readValue<List<JmhReport>>(resDirectory.resolve("jvm.json"))
|
||||||
jsonMapper.readValue<List<JmhReport>>(resDirectory.resolve("jvm.json"))
|
|
||||||
|
|
||||||
buildString {
|
buildString {
|
||||||
appendLine("<details>")
|
appendLine("<details>")
|
||||||
@ -77,20 +76,16 @@ fun Project.addBenchmarkProperties() {
|
|||||||
appendLine("* Run on ${first.vmName} (build ${first.vmVersion}) with Java process:")
|
appendLine("* Run on ${first.vmName} (build ${first.vmVersion}) with Java process:")
|
||||||
appendLine()
|
appendLine()
|
||||||
appendLine("```")
|
appendLine("```")
|
||||||
appendLine(
|
appendLine("${first.jvm} ${
|
||||||
"${first.jvm} ${
|
|
||||||
first.jvmArgs.joinToString(" ")
|
first.jvmArgs.joinToString(" ")
|
||||||
}"
|
}")
|
||||||
)
|
|
||||||
appendLine("```")
|
appendLine("```")
|
||||||
|
|
||||||
appendLine(
|
appendLine("* JMH ${first.jmhVersion} was used in `${first.mode}` mode with ${first.warmupIterations} warmup ${
|
||||||
"* JMH ${first.jmhVersion} was used in `${first.mode}` mode with ${first.warmupIterations} warmup ${
|
|
||||||
noun(first.warmupIterations, "iteration", "iterations")
|
noun(first.warmupIterations, "iteration", "iterations")
|
||||||
} by ${first.warmupTime} and ${first.measurementIterations} measurement ${
|
} by ${first.warmupTime} and ${first.measurementIterations} measurement ${
|
||||||
noun(first.measurementIterations, "iteration", "iterations")
|
noun(first.measurementIterations, "iteration", "iterations")
|
||||||
} by ${first.measurementTime}."
|
} by ${first.measurementTime}.")
|
||||||
)
|
|
||||||
|
|
||||||
appendLine()
|
appendLine()
|
||||||
appendLine("| Benchmark | Score |")
|
appendLine("| Benchmark | Score |")
|
||||||
|
@ -1,27 +1,20 @@
|
|||||||
# Coding Conventions
|
# Coding Conventions
|
||||||
|
|
||||||
Generally, KMath code follows
|
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.
|
||||||
general [Kotlin coding conventions](https://kotlinlang.org/docs/reference/coding-conventions.html), but with a number of
|
|
||||||
small changes and clarifications.
|
|
||||||
|
|
||||||
## Utility Class Naming
|
## 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
|
Filename should coincide with a name of one of the classes contained in the file or start with small letter and describe its contents.
|
||||||
its contents.
|
|
||||||
|
|
||||||
The code convention [here](https://kotlinlang.org/docs/reference/coding-conventions.html#source-file-names) says that
|
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.
|
||||||
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.
|
This convention could be changed in future in a non-breaking way.
|
||||||
|
|
||||||
## Private Variable Naming
|
## Private Variable Naming
|
||||||
|
|
||||||
Private variables' names may start with underscore `_` for of the private mutable variable is shadowed by the public
|
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.
|
||||||
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
|
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.
|
||||||
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.
|
This convention could be changed in future in a non-breaking way.
|
||||||
|
|
||||||
@ -31,5 +24,4 @@ Use one-liners when they occupy single code window line both for functions and p
|
|||||||
`val b: String get() = "fff"`. The same should be performed with multiline expressions when they could be
|
`val b: String get() = "fff"`. The same should be performed with multiline expressions when they could be
|
||||||
cleanly separated.
|
cleanly separated.
|
||||||
|
|
||||||
There is no universal consensus whenever use `fun a() = ...` or `fun a() { return ... }`. Yet from reader outlook
|
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.
|
||||||
one-lines seem to better show that the property or function is easily calculated.
|
|
||||||
|
@ -1,19 +1,16 @@
|
|||||||
# Expressions
|
# Expressions
|
||||||
|
|
||||||
Expressions is a feature, which allows constructing lazily or immediately calculated parametric mathematical
|
Expressions is a feature, which allows constructing lazily or immediately calculated parametric mathematical expressions.
|
||||||
expressions.
|
|
||||||
|
|
||||||
The potential use-cases for it (so far) are following:
|
The potential use-cases for it (so far) are following:
|
||||||
|
|
||||||
* lazy evaluation (in general simple lambda is better, but there are some border cases);
|
* lazy evaluation (in general simple lambda is better, but there are some border cases);
|
||||||
* automatic differentiation in single-dimension and in multiple dimensions;
|
* automatic differentiation in single-dimension and in multiple dimensions;
|
||||||
* generation of mathematical syntax trees with subsequent code generation for other languages;
|
* 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
|
* symbolic computations, especially differentiation (and some other actions with `kmath-symja` integration with Symja's `IExpr`—integration, simplification, and more);
|
||||||
Symja's `IExpr`—integration, simplification, and more);
|
|
||||||
* visualization with `kmath-jupyter`.
|
* visualization with `kmath-jupyter`.
|
||||||
|
|
||||||
The workhorse of this API is `Expression` interface, which exposes
|
The workhorse of this API is `Expression` interface, which exposes single `operator fun invoke(arguments: Map<Symbol, T>): T`
|
||||||
single `operator fun invoke(arguments: Map<Symbol, T>): T`
|
|
||||||
method. `ExpressionAlgebra` is used to generate expressions and introduce variables.
|
method. `ExpressionAlgebra` is used to generate expressions and introduce variables.
|
||||||
|
|
||||||
Currently there are two implementations:
|
Currently there are two implementations:
|
||||||
|
@ -1,12 +1,8 @@
|
|||||||
## Basic linear algebra layout
|
## Basic linear algebra layout
|
||||||
|
|
||||||
KMath support for linear algebra organized in a context-oriented way, which means that operations are in most cases
|
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.
|
||||||
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
|
The main context for linear algebra over matrices and vectors is `LinearSpace`, which defines addition and dot products of matrices and vectors:
|
||||||
of matrices and vectors:
|
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
import space.kscience.kmath.linear.*
|
import space.kscience.kmath.linear.*
|
||||||
@ -32,5 +28,4 @@ LinearSpace.Companion.real {
|
|||||||
## Backends overview
|
## Backends overview
|
||||||
|
|
||||||
### EJML
|
### EJML
|
||||||
|
|
||||||
### Commons Math
|
### Commons Math
|
||||||
|
@ -8,7 +8,6 @@ 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.
|
structures. In `kmath` performance depends on which particular context was used for operation.
|
||||||
|
|
||||||
Let us consider following contexts:
|
Let us consider following contexts:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
// automatically build context most suited for given type.
|
// automatically build context most suited for given type.
|
||||||
val autoField = NDField.auto(DoubleField, dim, dim)
|
val autoField = NDField.auto(DoubleField, dim, dim)
|
||||||
@ -17,7 +16,6 @@ Let us consider following contexts:
|
|||||||
//A generic boxing field. It should be used for objects, not primitives.
|
//A generic boxing field. It should be used for objects, not primitives.
|
||||||
val genericField = NDField.buffered(DoubleField, dim, dim)
|
val genericField = NDField.buffered(DoubleField, dim, dim)
|
||||||
```
|
```
|
||||||
|
|
||||||
Now let us perform several tests and see, which implementation is best suited for each case:
|
Now let us perform several tests and see, which implementation is best suited for each case:
|
||||||
|
|
||||||
## Test case
|
## Test case
|
||||||
@ -26,9 +24,7 @@ To test performance we will take 2d-structures with `dim = 1000` and add a struc
|
|||||||
to it `n = 1000` times.
|
to it `n = 1000` times.
|
||||||
|
|
||||||
## Specialized
|
## Specialized
|
||||||
|
|
||||||
The code to run this looks like:
|
The code to run this looks like:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
specializedField.run {
|
specializedField.run {
|
||||||
var res: NDBuffer<Double> = one
|
var res: NDBuffer<Double> = one
|
||||||
@ -37,16 +33,13 @@ 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
|
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
|
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
|
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.
|
from the beginning. Everyone does so anyway, so it is the recommended approach.
|
||||||
|
|
||||||
## Automatic
|
## Automatic
|
||||||
|
|
||||||
Let's do the same with automatic field inference:
|
Let's do the same with automatic field inference:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
autoField.run {
|
autoField.run {
|
||||||
var res = one
|
var res = one
|
||||||
@ -55,16 +48,13 @@ 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
|
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.
|
returns the same `RealNDField` in this case. Of course, it is usually better to use specialized method to be sure.
|
||||||
|
|
||||||
## Lazy
|
## Lazy
|
||||||
|
|
||||||
Lazy field does not produce a structure when asked, instead it generates an empty structure and fills it on-demand
|
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.
|
using coroutines to parallelize computations.
|
||||||
When one calls
|
When one calls
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
lazyField.run {
|
lazyField.run {
|
||||||
var res = one
|
var res = one
|
||||||
@ -73,14 +63,12 @@ When one calls
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The result will be calculated almost immediately but the result will be empty. To get the full result
|
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
|
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
|
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.
|
save a lot of time.
|
||||||
|
|
||||||
This field still could be used with reasonable performance if call code is changed:
|
This field still could be used with reasonable performance if call code is changed:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
lazyField.run {
|
lazyField.run {
|
||||||
val res = one.map {
|
val res = one.map {
|
||||||
@ -94,13 +82,10 @@ This field still could be used with reasonable performance if call code is chang
|
|||||||
res.elements().forEach { it.second }
|
res.elements().forEach { it.second }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
In this case it completes in about `4x-5x` time due to boxing.
|
In this case it completes in about `4x-5x` time due to boxing.
|
||||||
|
|
||||||
## Boxing
|
## Boxing
|
||||||
|
|
||||||
The boxing field produced by
|
The boxing field produced by
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
genericField.run {
|
genericField.run {
|
||||||
var res: NDBuffer<Double> = one
|
var res: NDBuffer<Double> = one
|
||||||
@ -109,22 +94,18 @@ The boxing field produced by
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
is the slowest one, because it requires boxing and unboxing the `double` on each operation. It takes about
|
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
|
`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.
|
never be used for primitives.
|
||||||
|
|
||||||
## Element operation
|
## Element operation
|
||||||
|
|
||||||
Let us also check the speed for direct operations on elements:
|
Let us also check the speed for direct operations on elements:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
var res = genericField.one
|
var res = genericField.one
|
||||||
repeat(n) {
|
repeat(n) {
|
||||||
res += 1.0
|
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.
|
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
|
It happens, because in this particular case it does not use actual `NDField` but instead calculated directly
|
||||||
via extension function.
|
via extension function.
|
||||||
@ -133,7 +114,6 @@ via extension function.
|
|||||||
|
|
||||||
Usually it is bad idea to compare the direct numerical operation performance in different languages, but it hard to
|
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:
|
work completely without frame of reference. In this case, simple numpy code:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@ -141,9 +121,7 @@ res = np.ones((1000,1000))
|
|||||||
for i in range(1000):
|
for i in range(1000):
|
||||||
res = res + 1.0
|
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,
|
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
|
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
|
available in `kmath` with `MutableNDStructure` but there is no field for it (one can still work with mapping
|
||||||
|
@ -1,54 +1,27 @@
|
|||||||
# Polynomials and Rational Functions
|
# Polynomials and Rational Functions
|
||||||
|
|
||||||
KMath provides a way to work with uni- and multivariate polynomials and rational functions. It includes full support of
|
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.
|
||||||
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
|
## Concrete realizations
|
||||||
|
|
||||||
There are 3 approaches to represent polynomials:
|
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)$.
|
||||||
|
|
||||||
1. For univariate polynomials one can represent and store polynomial as a list of coefficients for each power of the
|
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.
|
||||||
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:
|
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<C>`).
|
||||||
|
|
||||||
1. `ListPolynomial`, `ListPolynomialSpace`, `ListRationalFunction` and `ListRationalFunctionSpace` implement the first
|
They also have variation `ScalableListPolynomialSpace` that replaces former polynomials and implements `ScaleOperations`.
|
||||||
scenario. `ListPolynomial` stores polynomial $a_0 + \dots + a_n x^n $ as a coefficients
|
2. `NumberedPolynomial`, `NumberedPolynomialSpace`, `NumberedRationalFunction` and `NumberedRationalFunctionSpace` implement second scenario. `NumberedPolynomial` stores polynomials as structures of type `Map<List<UInt>, C>`. Signatures are stored as `List<UInt>`. To prevent ambiguity signatures should not end with zeros.
|
||||||
list `listOf(a_0, ..., a_n)` (of type `List<C>`).
|
3. `LabeledPolynomial`, `LabeledPolynomialSpace`, `LabeledRationalFunction` and `LabeledRationalFunctionSpace` implement third scenario using common `Symbol` as variable type. `LabeledPolynomial` stores polynomials as structures of type `Map<Map<Symbol, UInt>, C>`. Signatures are stored as `Map<Symbol, UInt>`. To prevent ambiguity each signature should not map any variable to zero.
|
||||||
|
|
||||||
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<List<UInt>, C>`.
|
|
||||||
Signatures are stored as `List<UInt>`. 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<Map<Symbol, UInt>, C>`. Signatures are stored as `Map<Symbol, UInt>`. To prevent ambiguity each signature
|
|
||||||
should not map any variable to zero.
|
|
||||||
|
|
||||||
### Example: `ListPolynomial`
|
### 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
|
```kotlin
|
||||||
val polynomial: ListPolynomial<Int> = ListPolynomial(listOf(2, -3, 1))
|
val polynomial: ListPolynomial<Int> = ListPolynomial(listOf(2, -3, 1))
|
||||||
// or
|
// or
|
||||||
@ -56,7 +29,6 @@ val polynomial: ListPolynomial<Int> = ListPolynomial(2, -3, 1)
|
|||||||
```
|
```
|
||||||
|
|
||||||
All algebraic operations can be used in corresponding space:
|
All algebraic operations can be used in corresponding space:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
val computationResult = Int.algebra.listPolynomialSpace {
|
val computationResult = Int.algebra.listPolynomialSpace {
|
||||||
ListPolynomial(2, -3, 1) + ListPolynomial(0, 6) == ListPolynomial(2, 3, 1)
|
ListPolynomial(2, -3, 1) + ListPolynomial(0, 6) == ListPolynomial(2, 3, 1)
|
||||||
@ -70,7 +42,6 @@ For more see [examples](../examples/src/main/kotlin/space/kscience/kmath/functio
|
|||||||
### Example: `NumberedPolynomial`
|
### 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
|
```kotlin
|
||||||
val polynomial: NumberedPolynomial<Int> = NumberedPolynomial(
|
val polynomial: NumberedPolynomial<Int> = NumberedPolynomial(
|
||||||
mapOf(
|
mapOf(
|
||||||
@ -88,7 +59,6 @@ val polynomial: NumberedPolynomial<Int> = NumberedPolynomial(
|
|||||||
```
|
```
|
||||||
|
|
||||||
All algebraic operations can be used in corresponding space:
|
All algebraic operations can be used in corresponding space:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
val computationResult = Int.algebra.numberedPolynomialSpace {
|
val computationResult = Int.algebra.numberedPolynomialSpace {
|
||||||
NumberedPolynomial(
|
NumberedPolynomial(
|
||||||
@ -114,7 +84,6 @@ For more see [examples](../examples/src/main/kotlin/space/kscience/kmath/functio
|
|||||||
### Example: `LabeledPolynomial`
|
### 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
|
```kotlin
|
||||||
val polynomial: LabeledPolynomial<Int> = LabeledPolynomial(
|
val polynomial: LabeledPolynomial<Int> = LabeledPolynomial(
|
||||||
mapOf(
|
mapOf(
|
||||||
@ -132,7 +101,6 @@ val polynomial: LabeledPolynomial<Int> = LabeledPolynomial(
|
|||||||
```
|
```
|
||||||
|
|
||||||
All algebraic operations can be used in corresponding space:
|
All algebraic operations can be used in corresponding space:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
val computationResult = Int.algebra.labeledPolynomialSpace {
|
val computationResult = Int.algebra.labeledPolynomialSpace {
|
||||||
LabeledPolynomial(
|
LabeledPolynomial(
|
||||||
@ -182,42 +150,23 @@ classDiagram
|
|||||||
PolynomialSpaceOfFractions <|-- MultivariatePolynomialSpaceOfFractions
|
PolynomialSpaceOfFractions <|-- MultivariatePolynomialSpaceOfFractions
|
||||||
```
|
```
|
||||||
|
|
||||||
There are implemented `Polynomial` and `RationalFunction` interfaces as abstractions of polynomials and rational
|
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:
|
||||||
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.
|
- `Polynomial` does not provide any logic. It is marker interface.
|
||||||
- `RationalFunction` provides numerator and denominator of rational function and destructuring declaration for them.
|
- `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
|
- `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.
|
||||||
polynomials (of type `P`) like addition, subtraction, multiplication, and some others and common properties like
|
- `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.
|
||||||
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
|
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.
|
||||||
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:
|
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<C>`).
|
||||||
- `PolynomialSpaceOverRing` allows to replace implementation of interactions of integers and constants with
|
|
||||||
implementations from provided ring over constants (of type `A: Ring<C>`).
|
|
||||||
- `RationalFunctionSpaceOverRing` — the same but for `RationalFunctionSpace`.
|
- `RationalFunctionSpaceOverRing` — the same but for `RationalFunctionSpace`.
|
||||||
- `RationalFunctionSpaceOverPolynomialSpace` — the same but "the inheritance" includes interactions with
|
- `RationalFunctionSpaceOverPolynomialSpace` — the same but "the inheritance" includes interactions with polynomials from provided `PolynomialSpace`.
|
||||||
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.
|
||||||
- `PolynomialSpaceOfFractions` is actually abstract subclass of `RationalFunctionSpace` that implements all fractions
|
- `MultivariateRationalFunctionSpaceOverMultivariatePolynomialSpace` and `MultivariatePolynomialSpaceOfFractions` — the same stories of operators inheritance and fractions boilerplates respectively but in multivariate case.
|
||||||
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
|
## Utilities
|
||||||
|
|
||||||
For all kinds of polynomials there are provided (implementation details depend on kind of polynomials) such common
|
For all kinds of polynomials there are provided (implementation details depend on kind of polynomials) such common utilities as:
|
||||||
utilities as:
|
|
||||||
|
|
||||||
1. differentiation and anti-differentiation,
|
1. differentiation and anti-differentiation,
|
||||||
2. substitution, invocation and functional representation.
|
2. substitution, invocation and functional representation.
|
1
docs/templates/ARTIFACT-TEMPLATE.md
vendored
1
docs/templates/ARTIFACT-TEMPLATE.md
vendored
@ -3,7 +3,6 @@
|
|||||||
The Maven coordinates of this project are `${group}:${name}:${version}`.
|
The Maven coordinates of this project are `${group}:${name}:${version}`.
|
||||||
|
|
||||||
**Gradle:**
|
**Gradle:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
17
docs/templates/README-TEMPLATE.md
vendored
17
docs/templates/README-TEMPLATE.md
vendored
@ -25,8 +25,7 @@ experience could be achieved with [kmath-for-real](/kmath-for-real) extension mo
|
|||||||
|
|
||||||
# Goal
|
# Goal
|
||||||
|
|
||||||
* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and
|
* Provide a flexible and powerful API to work with mathematics abstractions in Kotlin-multiplatform (JVM, JS, Native and Wasm).
|
||||||
Wasm).
|
|
||||||
* Provide basic multiplatform implementations for those abstractions (without significant performance optimization).
|
* Provide basic multiplatform implementations for those abstractions (without significant performance optimization).
|
||||||
* Provide bindings and wrappers with those abstractions for popular optimized platform libraries.
|
* Provide bindings and wrappers with those abstractions for popular optimized platform libraries.
|
||||||
|
|
||||||
@ -68,19 +67,16 @@ feedback are also welcome.
|
|||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to
|
Calculation of performance is one of the major goals of KMath in the future, but in some cases it is impossible to achieve both
|
||||||
achieve both
|
|
||||||
performance and flexibility.
|
performance and flexibility.
|
||||||
|
|
||||||
We expect to focus on creating a convenient universal API first and then work on increasing performance for specific
|
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
|
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
|
native/SciPy (mostly due to boxing operations on primitive numbers). The best performance of optimized parts could be better than SciPy.
|
||||||
better than SciPy.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
KMath currently relies on JDK 11 for compilation and execution of Kotlin-JVM part. We recommend using GraalVM-CE or
|
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.
|
||||||
Oracle GraalVM for execution to get better performance.
|
|
||||||
|
|
||||||
### Repositories
|
### Repositories
|
||||||
|
|
||||||
@ -103,7 +99,4 @@ dependencies {
|
|||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
The project requires a lot of additional work. The most important thing we need is feedback about what features are
|
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
|
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.
|
||||||
marked
|
|
||||||
with [good first issue](hhttps://github.com/SciProgCentre/kmath/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
|
||||||
label.
|
|
@ -67,8 +67,8 @@ kotlin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType<KotlinJvmCompile> {
|
tasks.withType<KotlinJvmCompile> {
|
||||||
compilerOptions {
|
kotlinOptions {
|
||||||
freeCompilerArgs.addAll("-Xjvm-default=all", "-Xopt-in=kotlin.RequiresOptIn", "-Xlambdas=indy")
|
freeCompilerArgs = freeCompilerArgs + "-Xjvm-default=all" + "-Xopt-in=kotlin.RequiresOptIn" + "-Xlambdas=indy"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,6 @@
|
|||||||
package space.kscience.kmath.expressions
|
package space.kscience.kmath.expressions
|
||||||
|
|
||||||
import space.kscience.kmath.UnstableKMathAPI
|
import space.kscience.kmath.UnstableKMathAPI
|
||||||
|
|
||||||
// Only kmath-core is needed.
|
// Only kmath-core is needed.
|
||||||
|
|
||||||
// Let's declare some variables
|
// Let's declare some variables
|
||||||
|
@ -8,6 +8,7 @@ package space.kscience.kmath.operations
|
|||||||
import space.kscience.kmath.commons.linear.CMLinearSpace
|
import space.kscience.kmath.commons.linear.CMLinearSpace
|
||||||
import space.kscience.kmath.linear.matrix
|
import space.kscience.kmath.linear.matrix
|
||||||
import space.kscience.kmath.nd.Float64BufferND
|
import space.kscience.kmath.nd.Float64BufferND
|
||||||
|
import space.kscience.kmath.nd.ShapeND
|
||||||
import space.kscience.kmath.nd.Structure2D
|
import space.kscience.kmath.nd.Structure2D
|
||||||
import space.kscience.kmath.nd.mutableStructureND
|
import space.kscience.kmath.nd.mutableStructureND
|
||||||
import space.kscience.kmath.nd.ndAlgebra
|
import space.kscience.kmath.nd.ndAlgebra
|
||||||
|
@ -53,10 +53,7 @@ class StreamDoubleFieldND(override val shape: ShapeND) : FieldND<Double, Float64
|
|||||||
return BufferND(strides, array.asBuffer())
|
return BufferND(strides, array.asBuffer())
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun mutableStructureND(
|
override fun mutableStructureND(shape: ShapeND, initializer: DoubleField.(IntArray) -> Double): MutableBufferND<Double> {
|
||||||
shape: ShapeND,
|
|
||||||
initializer: DoubleField.(IntArray) -> Double,
|
|
||||||
): MutableBufferND<Double> {
|
|
||||||
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
|
val array = IntStream.range(0, strides.linearSize).parallel().mapToDouble { offset ->
|
||||||
val index = strides.index(offset)
|
val index = strides.index(offset)
|
||||||
DoubleField.initializer(index)
|
DoubleField.initializer(index)
|
||||||
|
@ -12,7 +12,7 @@ import space.kscience.kmath.operations.withSize
|
|||||||
|
|
||||||
inline fun <reified R : Any> MutableBuffer.Companion.same(
|
inline fun <reified R : Any> MutableBuffer.Companion.same(
|
||||||
n: Int,
|
n: Int,
|
||||||
value: R,
|
value: R
|
||||||
): MutableBuffer<R> = MutableBuffer(n) { value }
|
): MutableBuffer<R> = MutableBuffer(n) { value }
|
||||||
|
|
||||||
|
|
||||||
|
@ -51,8 +51,7 @@ 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-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 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(
|
val inputData = LMInput(::funcDifficultForLm,
|
||||||
::funcDifficultForLm,
|
|
||||||
p_init.as2D(),
|
p_init.as2D(),
|
||||||
t,
|
t,
|
||||||
y_dat,
|
y_dat,
|
||||||
@ -65,8 +64,7 @@ fun main() {
|
|||||||
doubleArrayOf(opts[6], opts[7], opts[8]),
|
doubleArrayOf(opts[6], opts[7], opts[8]),
|
||||||
opts[9].toInt(),
|
opts[9].toInt(),
|
||||||
10,
|
10,
|
||||||
1
|
1)
|
||||||
)
|
|
||||||
|
|
||||||
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
||||||
|
|
||||||
|
@ -18,8 +18,7 @@ import kotlin.math.roundToInt
|
|||||||
|
|
||||||
fun main() {
|
fun main() {
|
||||||
val startedData = getStartDataForFuncEasy()
|
val startedData = getStartDataForFuncEasy()
|
||||||
val inputData = LMInput(
|
val inputData = LMInput(::funcEasyForLm,
|
||||||
::funcEasyForLm,
|
|
||||||
DoubleTensorAlgebra.ones(ShapeND(intArrayOf(4, 1))).as2D(),
|
DoubleTensorAlgebra.ones(ShapeND(intArrayOf(4, 1))).as2D(),
|
||||||
startedData.t,
|
startedData.t,
|
||||||
startedData.y_dat,
|
startedData.y_dat,
|
||||||
@ -32,8 +31,7 @@ fun main() {
|
|||||||
doubleArrayOf(startedData.opts[6], startedData.opts[7], startedData.opts[8]),
|
doubleArrayOf(startedData.opts[6], startedData.opts[7], startedData.opts[8]),
|
||||||
startedData.opts[9].toInt(),
|
startedData.opts[9].toInt(),
|
||||||
10,
|
10,
|
||||||
startedData.example_number
|
startedData.example_number)
|
||||||
)
|
|
||||||
|
|
||||||
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
||||||
|
|
||||||
|
@ -15,7 +15,6 @@ import space.kscience.kmath.tensors.core.DoubleTensorAlgebra
|
|||||||
import space.kscience.kmath.tensors.core.LMInput
|
import space.kscience.kmath.tensors.core.LMInput
|
||||||
import space.kscience.kmath.tensors.core.levenbergMarquardt
|
import space.kscience.kmath.tensors.core.levenbergMarquardt
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
fun main() {
|
fun main() {
|
||||||
val NData = 100
|
val NData = 100
|
||||||
var t_example = DoubleTensorAlgebra.ones(ShapeND(intArrayOf(NData, 1))).as2D()
|
var t_example = DoubleTensorAlgebra.ones(ShapeND(intArrayOf(NData, 1))).as2D()
|
||||||
@ -50,8 +49,7 @@ fun main() {
|
|||||||
p_min = p_min.div(1.0 / 50.0)
|
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 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(
|
val inputData = LMInput(::funcMiddleForLm,
|
||||||
::funcMiddleForLm,
|
|
||||||
p_init.as2D(),
|
p_init.as2D(),
|
||||||
t,
|
t,
|
||||||
y_dat,
|
y_dat,
|
||||||
@ -64,8 +62,7 @@ fun main() {
|
|||||||
doubleArrayOf(opts[6], opts[7], opts[8]),
|
doubleArrayOf(opts[6], opts[7], opts[8]),
|
||||||
opts[9].toInt(),
|
opts[9].toInt(),
|
||||||
10,
|
10,
|
||||||
1
|
1)
|
||||||
)
|
|
||||||
|
|
||||||
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
||||||
|
|
||||||
|
@ -6,23 +6,18 @@
|
|||||||
package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm
|
package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm
|
||||||
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.*
|
||||||
import kotlinx.coroutines.flow.flow
|
import space.kscience.kmath.nd.*
|
||||||
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.LevenbergMarquardt.StartDataLm
|
||||||
import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra.zeros
|
import space.kscience.kmath.tensors.core.BroadcastDoubleTensorAlgebra.zeros
|
||||||
import space.kscience.kmath.tensors.core.DoubleTensorAlgebra
|
import space.kscience.kmath.tensors.core.DoubleTensorAlgebra
|
||||||
import space.kscience.kmath.tensors.core.LMInput
|
import space.kscience.kmath.tensors.core.LMInput
|
||||||
import space.kscience.kmath.tensors.core.levenbergMarquardt
|
import space.kscience.kmath.tensors.core.levenbergMarquardt
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
|
import kotlin.reflect.KFunction3
|
||||||
|
|
||||||
fun streamLm(
|
fun streamLm(lm_func: (MutableStructure2D<Double>, MutableStructure2D<Double>, Int) -> (MutableStructure2D<Double>),
|
||||||
lm_func: (MutableStructure2D<Double>, MutableStructure2D<Double>, Int) -> (MutableStructure2D<Double>),
|
startData: StartDataLm, launchFrequencyInMs: Long, numberOfLaunches: Int): Flow<MutableStructure2D<Double>> = flow{
|
||||||
startData: StartDataLm, launchFrequencyInMs: Long, numberOfLaunches: Int,
|
|
||||||
): Flow<MutableStructure2D<Double>> = flow {
|
|
||||||
|
|
||||||
var example_number = startData.example_number
|
var example_number = startData.example_number
|
||||||
var p_init = startData.p_init
|
var p_init = startData.p_init
|
||||||
@ -37,8 +32,7 @@ fun streamLm(
|
|||||||
var steps = numberOfLaunches
|
var steps = numberOfLaunches
|
||||||
val isEndless = (steps <= 0)
|
val isEndless = (steps <= 0)
|
||||||
|
|
||||||
val inputData = LMInput(
|
val inputData = LMInput(lm_func,
|
||||||
lm_func,
|
|
||||||
p_init,
|
p_init,
|
||||||
t,
|
t,
|
||||||
y_dat,
|
y_dat,
|
||||||
@ -51,8 +45,7 @@ fun streamLm(
|
|||||||
doubleArrayOf(opts[6], opts[7], opts[8]),
|
doubleArrayOf(opts[6], opts[7], opts[8]),
|
||||||
opts[9].toInt(),
|
opts[9].toInt(),
|
||||||
10,
|
10,
|
||||||
example_number
|
example_number)
|
||||||
)
|
|
||||||
|
|
||||||
while (isEndless || steps > 0) {
|
while (isEndless || steps > 0) {
|
||||||
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
val result = DoubleTensorAlgebra.levenbergMarquardt(inputData)
|
||||||
|
@ -5,9 +5,8 @@
|
|||||||
|
|
||||||
package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm
|
package space.kscience.kmath.tensors.LevenbergMarquardt.StreamingLm
|
||||||
|
|
||||||
import space.kscience.kmath.nd.component1
|
import space.kscience.kmath.nd.*
|
||||||
import space.kscience.kmath.tensors.LevenbergMarquardt.funcDifficultForLm
|
import space.kscience.kmath.tensors.LevenbergMarquardt.*
|
||||||
import space.kscience.kmath.tensors.LevenbergMarquardt.getStartDataForFuncDifficult
|
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
suspend fun main(){
|
suspend fun main(){
|
||||||
|
@ -29,14 +29,10 @@ public data class StartDataLm(
|
|||||||
var p_min: MutableStructure2D<Double>,
|
var p_min: MutableStructure2D<Double>,
|
||||||
var p_max: MutableStructure2D<Double>,
|
var p_max: MutableStructure2D<Double>,
|
||||||
var consts: MutableStructure2D<Double>,
|
var consts: MutableStructure2D<Double>,
|
||||||
var opts: DoubleArray,
|
var opts: DoubleArray
|
||||||
)
|
)
|
||||||
|
|
||||||
fun funcEasyForLm(
|
fun funcEasyForLm(t: MutableStructure2D<Double>, p: MutableStructure2D<Double>, exampleNumber: Int): MutableStructure2D<Double> {
|
||||||
t: MutableStructure2D<Double>,
|
|
||||||
p: MutableStructure2D<Double>,
|
|
||||||
exampleNumber: Int,
|
|
||||||
): MutableStructure2D<Double> {
|
|
||||||
val m = t.shape.component1()
|
val m = t.shape.component1()
|
||||||
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1)))
|
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf(m, 1)))
|
||||||
|
|
||||||
@ -44,13 +40,15 @@ fun funcEasyForLm(
|
|||||||
y_hat = DoubleTensorAlgebra.exp((t.times(-1.0 / p[1, 0]))).times(p[0, 0]) + t.times(p[2, 0]).times(
|
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])))
|
DoubleTensorAlgebra.exp((t.times(-1.0 / p[3, 0])))
|
||||||
)
|
)
|
||||||
} else if (exampleNumber == 2) {
|
}
|
||||||
|
else if (exampleNumber == 2) {
|
||||||
val mt = t.max()
|
val mt = t.max()
|
||||||
y_hat = (t.times(1.0 / mt)).times(p[0, 0]) +
|
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(2).times(p[1, 0]) +
|
||||||
(t.times(1.0 / mt)).pow(3).times(p[2, 0]) +
|
(t.times(1.0 / mt)).pow(3).times(p[2, 0]) +
|
||||||
(t.times(1.0 / mt)).pow(4).times(p[3, 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])))
|
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])
|
.times(p[0, 0]) + DoubleTensorAlgebra.sin((t.times(1.0 / p[3, 0]))).times(p[2, 0])
|
||||||
}
|
}
|
||||||
@ -58,11 +56,7 @@ fun funcEasyForLm(
|
|||||||
return y_hat.as2D()
|
return y_hat.as2D()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun funcMiddleForLm(
|
fun funcMiddleForLm(t: MutableStructure2D<Double>, p: MutableStructure2D<Double>, exampleNumber: Int): MutableStructure2D<Double> {
|
||||||
t: MutableStructure2D<Double>,
|
|
||||||
p: MutableStructure2D<Double>,
|
|
||||||
exampleNumber: Int,
|
|
||||||
): MutableStructure2D<Double> {
|
|
||||||
val m = t.shape.component1()
|
val m = t.shape.component1()
|
||||||
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1)))
|
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1)))
|
||||||
|
|
||||||
@ -78,11 +72,7 @@ fun funcMiddleForLm(
|
|||||||
return y_hat.as2D()
|
return y_hat.as2D()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun funcDifficultForLm(
|
fun funcDifficultForLm(t: MutableStructure2D<Double>, p: MutableStructure2D<Double>, exampleNumber: Int): MutableStructure2D<Double> {
|
||||||
t: MutableStructure2D<Double>,
|
|
||||||
p: MutableStructure2D<Double>,
|
|
||||||
exampleNumber: Int,
|
|
||||||
): MutableStructure2D<Double> {
|
|
||||||
val m = t.shape.component1()
|
val m = t.shape.component1()
|
||||||
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1)))
|
var y_hat = DoubleTensorAlgebra.zeros(ShapeND(intArrayOf (m, 1)))
|
||||||
|
|
||||||
|
@ -5,10 +5,13 @@
|
|||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
kotlin.mpp.stability.nowarn=true
|
kotlin.mpp.stability.nowarn=true
|
||||||
kotlin.native.ignoreDisabledTargets=true
|
kotlin.native.ignoreDisabledTargets=true
|
||||||
|
|
||||||
org.gradle.configureondemand=true
|
org.gradle.configureondemand=true
|
||||||
org.gradle.jvmargs=-Xmx4096m
|
org.gradle.jvmargs=-Xmx4096m
|
||||||
|
|
||||||
org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
org.gradle.workers.max=4
|
org.gradle.workers.max=4
|
||||||
|
|
||||||
toolsVersion=0.15.2-kotlin-1.9.22
|
toolsVersion=0.15.2-kotlin-1.9.22
|
||||||
#kotlin.experimental.tryK2=true
|
#kotlin.experimental.tryK2=true
|
||||||
#kscience.wasm.disabled=true
|
#kscience.wasm.disabled=true
|
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@ -1,5 +1,5 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
|
@ -7,12 +7,12 @@ Extensions to MST API: transformations, dynamic compilation and visualization.
|
|||||||
- [mst-js-codegen](src/jsMain/kotlin/space/kscience/kmath/estree/estree.kt) : Dynamic MST to JS compiler
|
- [mst-js-codegen](src/jsMain/kotlin/space/kscience/kmath/estree/estree.kt) : Dynamic MST to JS compiler
|
||||||
- [rendering](src/commonMain/kotlin/space/kscience/kmath/ast/rendering/MathRenderer.kt) : Extendable MST rendering
|
- [rendering](src/commonMain/kotlin/space/kscience/kmath/ast/rendering/MathRenderer.kt) : Extendable MST rendering
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-ast:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-ast:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
@ -26,27 +26,21 @@ dependencies {
|
|||||||
|
|
||||||
## Parsing expressions
|
## Parsing expressions
|
||||||
|
|
||||||
In this module there is a parser from human-readable strings like `"x^3-x+3"` (in the more
|
In this module there is a parser from human-readable strings like `"x^3-x+3"` (in the more specific [grammar](reference/ArithmeticsEvaluator.g4)) to MST instances.
|
||||||
specific [grammar](reference/ArithmeticsEvaluator.g4)) to MST instances.
|
|
||||||
|
|
||||||
Supported literals:
|
Supported literals:
|
||||||
|
|
||||||
1. Constants and variables (consist of latin letters, digits and underscores, can't start with digit): `x`, `_Abc2`.
|
1. Constants and variables (consist of latin letters, digits and underscores, can't start with digit): `x`, `_Abc2`.
|
||||||
2. Numbers: `123`, `1.02`, `1e10`, `1e-10`, `1.0e+3`—all parsed either as `kotlin.Long` or `kotlin.Double`.
|
2. Numbers: `123`, `1.02`, `1e10`, `1e-10`, `1.0e+3`—all parsed either as `kotlin.Long` or `kotlin.Double`.
|
||||||
|
|
||||||
Supported binary operators (from the highest precedence to the lowest one):
|
Supported binary operators (from the highest precedence to the lowest one):
|
||||||
|
|
||||||
1. `^`
|
1. `^`
|
||||||
2. `*`, `/`
|
2. `*`, `/`
|
||||||
3. `+`, `-`
|
3. `+`, `-`
|
||||||
|
|
||||||
Supported unary operator:
|
Supported unary operator:
|
||||||
|
|
||||||
1. `-`, e. g. `-x`
|
1. `-`, e. g. `-x`
|
||||||
|
|
||||||
Arbitrary unary and binary functions are also supported: names consist of latin letters, digits and underscores, can't
|
Arbitrary unary and binary functions are also supported: names consist of latin letters, digits and underscores, can't start with digit. Examples:
|
||||||
start with digit. Examples:
|
|
||||||
|
|
||||||
1. `sin(x)`
|
1. `sin(x)`
|
||||||
2. `add(x, y)`
|
2. `add(x, y)`
|
||||||
|
|
||||||
@ -111,15 +105,12 @@ public final class CompiledExpression_-386104628_0 implements DoubleExpression {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Setting JVM system property `space.kscience.kmath.ast.dump.generated.classes` to `1` makes the translator dump class
|
Setting JVM system property `space.kscience.kmath.ast.dump.generated.classes` to `1` makes the translator dump class files to program's working directory, so they can be reviewed manually.
|
||||||
files to program's working directory, so they can be reviewed manually.
|
|
||||||
|
|
||||||
#### Limitations
|
#### Limitations
|
||||||
|
|
||||||
- The same classes may be generated and loaded twice, so it is recommended to cache compiled expressions to avoid class
|
- The same classes may be generated and loaded twice, so it is recommended to cache compiled expressions to avoid class loading overhead.
|
||||||
loading overhead.
|
- This API is not supported by non-dynamic JVM implementations like TeaVM or GraalVM Native Image because they may not support class loaders.
|
||||||
- This API is not supported by non-dynamic JVM implementations like TeaVM or GraalVM Native Image because they may not
|
|
||||||
support class loaders.
|
|
||||||
|
|
||||||
### On JS
|
### On JS
|
||||||
|
|
||||||
@ -197,8 +188,7 @@ public fun main() {
|
|||||||
|
|
||||||
Result LaTeX:
|
Result LaTeX:
|
||||||
|
|
||||||
$$\operatorname{exp}\\,\left(\sqrt{x}\right)-\frac{\frac{\operatorname{arcsin}\\,\left(2\\,x\right)
|
$$\operatorname{exp}\\,\left(\sqrt{x}\right)-\frac{\frac{\operatorname{arcsin}\\,\left(2\\,x\right)}{2\times10^{10}+x^{3}}}{12}+x^{2/3}$$
|
||||||
}{2\times10^{10}+x^{3}}}{12}+x^{2/3}$$
|
|
||||||
|
|
||||||
Result MathML (can be used with MathJax or other renderers):
|
Result MathML (can be used with MathJax or other renderers):
|
||||||
|
|
||||||
|
@ -8,27 +8,21 @@ ${artifact}
|
|||||||
|
|
||||||
## Parsing expressions
|
## Parsing expressions
|
||||||
|
|
||||||
In this module there is a parser from human-readable strings like `"x^3-x+3"` (in the more
|
In this module there is a parser from human-readable strings like `"x^3-x+3"` (in the more specific [grammar](reference/ArithmeticsEvaluator.g4)) to MST instances.
|
||||||
specific [grammar](reference/ArithmeticsEvaluator.g4)) to MST instances.
|
|
||||||
|
|
||||||
Supported literals:
|
Supported literals:
|
||||||
|
|
||||||
1. Constants and variables (consist of latin letters, digits and underscores, can't start with digit): `x`, `_Abc2`.
|
1. Constants and variables (consist of latin letters, digits and underscores, can't start with digit): `x`, `_Abc2`.
|
||||||
2. Numbers: `123`, `1.02`, `1e10`, `1e-10`, `1.0e+3`—all parsed either as `kotlin.Long` or `kotlin.Double`.
|
2. Numbers: `123`, `1.02`, `1e10`, `1e-10`, `1.0e+3`—all parsed either as `kotlin.Long` or `kotlin.Double`.
|
||||||
|
|
||||||
Supported binary operators (from the highest precedence to the lowest one):
|
Supported binary operators (from the highest precedence to the lowest one):
|
||||||
|
|
||||||
1. `^`
|
1. `^`
|
||||||
2. `*`, `/`
|
2. `*`, `/`
|
||||||
3. `+`, `-`
|
3. `+`, `-`
|
||||||
|
|
||||||
Supported unary operator:
|
Supported unary operator:
|
||||||
|
|
||||||
1. `-`, e. g. `-x`
|
1. `-`, e. g. `-x`
|
||||||
|
|
||||||
Arbitrary unary and binary functions are also supported: names consist of latin letters, digits and underscores, can't
|
Arbitrary unary and binary functions are also supported: names consist of latin letters, digits and underscores, can't start with digit. Examples:
|
||||||
start with digit. Examples:
|
|
||||||
|
|
||||||
1. `sin(x)`
|
1. `sin(x)`
|
||||||
2. `add(x, y)`
|
2. `add(x, y)`
|
||||||
|
|
||||||
@ -93,15 +87,12 @@ public final class CompiledExpression_-386104628_0 implements DoubleExpression {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Setting JVM system property `space.kscience.kmath.ast.dump.generated.classes` to `1` makes the translator dump class
|
Setting JVM system property `space.kscience.kmath.ast.dump.generated.classes` to `1` makes the translator dump class files to program's working directory, so they can be reviewed manually.
|
||||||
files to program's working directory, so they can be reviewed manually.
|
|
||||||
|
|
||||||
#### Limitations
|
#### Limitations
|
||||||
|
|
||||||
- The same classes may be generated and loaded twice, so it is recommended to cache compiled expressions to avoid class
|
- The same classes may be generated and loaded twice, so it is recommended to cache compiled expressions to avoid class loading overhead.
|
||||||
loading overhead.
|
- This API is not supported by non-dynamic JVM implementations like TeaVM or GraalVM Native Image because they may not support class loaders.
|
||||||
- This API is not supported by non-dynamic JVM implementations like TeaVM or GraalVM Native Image because they may not
|
|
||||||
support class loaders.
|
|
||||||
|
|
||||||
### On JS
|
### On JS
|
||||||
|
|
||||||
@ -179,8 +170,7 @@ public fun main() {
|
|||||||
|
|
||||||
Result LaTeX:
|
Result LaTeX:
|
||||||
|
|
||||||
$$\operatorname{exp}\\,\left(\sqrt{x}\right)-\frac{\frac{\operatorname{arcsin}\\,\left(2\\,x\right)
|
$$\operatorname{exp}\\,\left(\sqrt{x}\right)-\frac{\frac{\operatorname{arcsin}\\,\left(2\\,x\right)}{2\times10^{10}+x^{3}}}{12}+x^{2/3}$$
|
||||||
}{2\times10^{10}+x^{3}}}{12}+x^{2/3}$$
|
|
||||||
|
|
||||||
Result MathML (can be used with MathJax or other renderers):
|
Result MathML (can be used with MathJax or other renderers):
|
||||||
|
|
||||||
|
@ -426,13 +426,11 @@ public class InverseTrigonometricOperations(operations: Collection<String>?) : U
|
|||||||
* The default instance configured with [TrigonometricOperations.ACOS_OPERATION],
|
* The default instance configured with [TrigonometricOperations.ACOS_OPERATION],
|
||||||
* [TrigonometricOperations.ASIN_OPERATION], [TrigonometricOperations.ATAN_OPERATION].
|
* [TrigonometricOperations.ASIN_OPERATION], [TrigonometricOperations.ATAN_OPERATION].
|
||||||
*/
|
*/
|
||||||
public val Default: InverseTrigonometricOperations = InverseTrigonometricOperations(
|
public val Default: InverseTrigonometricOperations = InverseTrigonometricOperations(setOf(
|
||||||
setOf(
|
|
||||||
TrigonometricOperations.ACOS_OPERATION,
|
TrigonometricOperations.ACOS_OPERATION,
|
||||||
TrigonometricOperations.ASIN_OPERATION,
|
TrigonometricOperations.ASIN_OPERATION,
|
||||||
TrigonometricOperations.ATAN_OPERATION,
|
TrigonometricOperations.ATAN_OPERATION,
|
||||||
)
|
))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -454,12 +452,10 @@ public class InverseHyperbolicOperations(operations: Collection<String>?) : Unar
|
|||||||
* The default instance configured with [ExponentialOperations.ACOSH_OPERATION],
|
* The default instance configured with [ExponentialOperations.ACOSH_OPERATION],
|
||||||
* [ExponentialOperations.ASINH_OPERATION], and [ExponentialOperations.ATANH_OPERATION].
|
* [ExponentialOperations.ASINH_OPERATION], and [ExponentialOperations.ATANH_OPERATION].
|
||||||
*/
|
*/
|
||||||
public val Default: InverseHyperbolicOperations = InverseHyperbolicOperations(
|
public val Default: InverseHyperbolicOperations = InverseHyperbolicOperations(setOf(
|
||||||
setOf(
|
|
||||||
ExponentialOperations.ACOSH_OPERATION,
|
ExponentialOperations.ACOSH_OPERATION,
|
||||||
ExponentialOperations.ASINH_OPERATION,
|
ExponentialOperations.ASINH_OPERATION,
|
||||||
ExponentialOperations.ATANH_OPERATION,
|
ExponentialOperations.ATANH_OPERATION,
|
||||||
)
|
))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,6 @@ internal class TestFeatures {
|
|||||||
fun printNumeric() {
|
fun printNumeric() {
|
||||||
val num = object : Number() {
|
val num = object : Number() {
|
||||||
override fun toByte(): Byte = throw UnsupportedOperationException()
|
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 toDouble(): Double = throw UnsupportedOperationException()
|
||||||
override fun toFloat(): Float = throw UnsupportedOperationException()
|
override fun toFloat(): Float = throw UnsupportedOperationException()
|
||||||
|
@ -81,10 +81,8 @@ internal class TestMathML {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun radicalWithIndex() =
|
fun radicalWithIndex() =
|
||||||
testMathML(
|
testMathML(RadicalWithIndexSyntax("", SymbolSyntax("x"), SymbolSyntax("y")),
|
||||||
RadicalWithIndexSyntax("", SymbolSyntax("x"), SymbolSyntax("y")),
|
"<mroot><mrow><mi>y</mi></mrow><mrow><mi>x</mi></mrow></mroot>")
|
||||||
"<mroot><mrow><mi>y</mi></mrow><mrow><mi>x</mi></mrow></mroot>"
|
|
||||||
)
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun multiplication() {
|
fun multiplication() {
|
||||||
|
@ -1656,27 +1656,27 @@ internal open external class Module {
|
|||||||
open fun `if`(
|
open fun `if`(
|
||||||
condition: ExpressionRef,
|
condition: ExpressionRef,
|
||||||
ifTrue: ExpressionRef,
|
ifTrue: ExpressionRef,
|
||||||
ifFalse: ExpressionRef = definedExternally,
|
ifFalse: ExpressionRef = definedExternally
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun loop(label: String, body: ExpressionRef): ExpressionRef
|
open fun loop(label: String, body: ExpressionRef): ExpressionRef
|
||||||
open fun br(
|
open fun br(
|
||||||
label: String,
|
label: String,
|
||||||
condition: ExpressionRef = definedExternally,
|
condition: ExpressionRef = definedExternally,
|
||||||
value: ExpressionRef = definedExternally,
|
value: ExpressionRef = definedExternally
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun br_if(
|
open fun br_if(
|
||||||
label: String,
|
label: String,
|
||||||
condition: ExpressionRef = definedExternally,
|
condition: ExpressionRef = definedExternally,
|
||||||
value: ExpressionRef = definedExternally,
|
value: ExpressionRef = definedExternally
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun switch(
|
open fun switch(
|
||||||
labels: Array<String>,
|
labels: Array<String>,
|
||||||
defaultLabel: String,
|
defaultLabel: String,
|
||||||
condition: ExpressionRef,
|
condition: ExpressionRef,
|
||||||
value: ExpressionRef = definedExternally,
|
value: ExpressionRef = definedExternally
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun call(name: String, operands: Array<ExpressionRef>, returnType: Type): ExpressionRef
|
open fun call(name: String, operands: Array<ExpressionRef>, returnType: Type): ExpressionRef
|
||||||
@ -1685,14 +1685,14 @@ internal open external class Module {
|
|||||||
target: ExpressionRef,
|
target: ExpressionRef,
|
||||||
operands: Array<ExpressionRef>,
|
operands: Array<ExpressionRef>,
|
||||||
params: Type,
|
params: Type,
|
||||||
results: Type,
|
results: Type
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun return_call_indirect(
|
open fun return_call_indirect(
|
||||||
target: ExpressionRef,
|
target: ExpressionRef,
|
||||||
operands: Array<ExpressionRef>,
|
operands: Array<ExpressionRef>,
|
||||||
params: Type,
|
params: Type,
|
||||||
results: Type,
|
results: Type
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open var local: `T$2`
|
open var local: `T$2`
|
||||||
@ -1730,7 +1730,7 @@ internal open external class Module {
|
|||||||
condition: ExpressionRef,
|
condition: ExpressionRef,
|
||||||
ifTrue: ExpressionRef,
|
ifTrue: ExpressionRef,
|
||||||
ifFalse: ExpressionRef,
|
ifFalse: ExpressionRef,
|
||||||
type: Type = definedExternally,
|
type: Type = definedExternally
|
||||||
): ExpressionRef
|
): ExpressionRef
|
||||||
|
|
||||||
open fun drop(value: ExpressionRef): ExpressionRef
|
open fun drop(value: ExpressionRef): ExpressionRef
|
||||||
@ -1754,7 +1754,7 @@ internal open external class Module {
|
|||||||
externalModuleName: String,
|
externalModuleName: String,
|
||||||
externalBaseName: String,
|
externalBaseName: String,
|
||||||
params: Type,
|
params: Type,
|
||||||
results: Type,
|
results: Type
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun addTableImport(internalName: String, externalModuleName: String, externalBaseName: String)
|
open fun addTableImport(internalName: String, externalModuleName: String, externalBaseName: String)
|
||||||
@ -1763,7 +1763,7 @@ internal open external class Module {
|
|||||||
internalName: String,
|
internalName: String,
|
||||||
externalModuleName: String,
|
externalModuleName: String,
|
||||||
externalBaseName: String,
|
externalBaseName: String,
|
||||||
globalType: Type,
|
globalType: Type
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun addEventImport(
|
open fun addEventImport(
|
||||||
@ -1772,7 +1772,7 @@ internal open external class Module {
|
|||||||
externalBaseName: String,
|
externalBaseName: String,
|
||||||
attribute: Number,
|
attribute: Number,
|
||||||
params: Type,
|
params: Type,
|
||||||
results: Type,
|
results: Type
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun addFunctionExport(internalName: String, externalName: String): ExportRef
|
open fun addFunctionExport(internalName: String, externalName: String): ExportRef
|
||||||
@ -1786,7 +1786,7 @@ internal open external class Module {
|
|||||||
initial: Number,
|
initial: Number,
|
||||||
maximum: Number,
|
maximum: Number,
|
||||||
funcNames: Array<Number>,
|
funcNames: Array<Number>,
|
||||||
offset: ExpressionRef = definedExternally,
|
offset: ExpressionRef = definedExternally
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun getFunctionTable(): `T$26`
|
open fun getFunctionTable(): `T$26`
|
||||||
@ -1796,7 +1796,7 @@ internal open external class Module {
|
|||||||
exportName: String? = definedExternally,
|
exportName: String? = definedExternally,
|
||||||
segments: Array<MemorySegment>? = definedExternally,
|
segments: Array<MemorySegment>? = definedExternally,
|
||||||
flags: Array<Number>? = definedExternally,
|
flags: Array<Number>? = definedExternally,
|
||||||
shared: Boolean = definedExternally,
|
shared: Boolean = definedExternally
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun getNumMemorySegments(): Number
|
open fun getNumMemorySegments(): Number
|
||||||
@ -1827,7 +1827,7 @@ internal open external class Module {
|
|||||||
expr: ExpressionRef,
|
expr: ExpressionRef,
|
||||||
fileIndex: Number,
|
fileIndex: Number,
|
||||||
lineNumber: Number,
|
lineNumber: Number,
|
||||||
columnNumber: Number,
|
columnNumber: Number
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun copyExpression(expr: ExpressionRef): ExpressionRef
|
open fun copyExpression(expr: ExpressionRef): ExpressionRef
|
||||||
@ -2231,7 +2231,7 @@ internal open external class Relooper(module: Module) {
|
|||||||
from: RelooperBlockRef,
|
from: RelooperBlockRef,
|
||||||
to: RelooperBlockRef,
|
to: RelooperBlockRef,
|
||||||
indexes: Array<Number>,
|
indexes: Array<Number>,
|
||||||
code: ExpressionRef,
|
code: ExpressionRef
|
||||||
)
|
)
|
||||||
|
|
||||||
open fun renderAndDispose(entry: RelooperBlockRef, labelHelper: Number): ExpressionRef
|
open fun renderAndDispose(entry: RelooperBlockRef, labelHelper: Number): ExpressionRef
|
||||||
|
@ -30,8 +30,7 @@ internal fun Identifier(name: String) = object : Identifier {
|
|||||||
override var name = name
|
override var name = name
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun FunctionExpression(id: Identifier?, params: Array<dynamic>, body: BlockStatement) =
|
internal fun FunctionExpression(id: Identifier?, params: Array<dynamic>, body: BlockStatement) = object : FunctionExpression {
|
||||||
object : FunctionExpression {
|
|
||||||
override var params = params
|
override var params = params
|
||||||
override var type = "FunctionExpression"
|
override var type = "FunctionExpression"
|
||||||
override var id: Identifier? = id
|
override var id: Identifier? = id
|
||||||
|
@ -91,6 +91,6 @@ internal typealias Extract<T, U> = Any
|
|||||||
internal external interface PromiseLike<T> {
|
internal external interface PromiseLike<T> {
|
||||||
fun then(
|
fun then(
|
||||||
onfulfilled: ((value: T) -> Any?)? = definedExternally,
|
onfulfilled: ((value: T) -> Any?)? = definedExternally,
|
||||||
onrejected: ((reason: Any) -> Any?)? = definedExternally,
|
onrejected: ((reason: Any) -> Any?)? = definedExternally
|
||||||
): PromiseLike<dynamic /* TResult1 | TResult2 */>
|
): PromiseLike<dynamic /* TResult1 | TResult2 */>
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@
|
|||||||
|
|
||||||
package space.kscience.kmath.internal.webassembly
|
package space.kscience.kmath.internal.webassembly
|
||||||
|
|
||||||
|
import space.kscience.kmath.internal.tsstdlib.PromiseLike
|
||||||
import org.khronos.webgl.ArrayBuffer
|
import org.khronos.webgl.ArrayBuffer
|
||||||
import org.khronos.webgl.ArrayBufferView
|
import org.khronos.webgl.ArrayBufferView
|
||||||
import org.khronos.webgl.Uint8Array
|
import org.khronos.webgl.Uint8Array
|
||||||
import org.w3c.fetch.Response
|
import org.w3c.fetch.Response
|
||||||
import space.kscience.kmath.internal.tsstdlib.PromiseLike
|
|
||||||
import kotlin.js.Promise
|
import kotlin.js.Promise
|
||||||
|
|
||||||
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
|
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
|
||||||
|
@ -13,6 +13,9 @@ import space.kscience.kmath.expressions.*
|
|||||||
import java.lang.invoke.MethodHandles
|
import java.lang.invoke.MethodHandles
|
||||||
import java.lang.invoke.MethodType
|
import java.lang.invoke.MethodType
|
||||||
import java.nio.file.Paths
|
import java.nio.file.Paths
|
||||||
|
import java.util.stream.Collectors.toMap
|
||||||
|
import kotlin.contracts.InvocationKind
|
||||||
|
import kotlin.contracts.contract
|
||||||
import kotlin.io.path.writeBytes
|
import kotlin.io.path.writeBytes
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -280,6 +283,7 @@ internal class GenericAsmBuilder<T>(
|
|||||||
fun loadVariable(name: Symbol): Unit = invokeMethodVisitor.load(2 + argumentsLocals.indexOf(name), tType)
|
fun loadVariable(name: Symbol): Unit = invokeMethodVisitor.load(2 + argumentsLocals.indexOf(name), tType)
|
||||||
|
|
||||||
inline fun buildCall(function: Function<T>, parameters: GenericAsmBuilder<T>.() -> Unit) {
|
inline fun buildCall(function: Function<T>, parameters: GenericAsmBuilder<T>.() -> Unit) {
|
||||||
|
contract { callsInPlace(parameters, InvocationKind.EXACTLY_ONCE) }
|
||||||
val `interface` = function.javaClass.interfaces.first { Function::class.java in it.interfaces }
|
val `interface` = function.javaClass.interfaces.first { Function::class.java in it.interfaces }
|
||||||
|
|
||||||
val arity = `interface`.methods.find { it.name == "invoke" }?.parameterCount
|
val arity = `interface`.methods.find { it.name == "invoke" }?.parameterCount
|
||||||
|
@ -332,7 +332,7 @@ internal sealed class PrimitiveAsmBuilder<T : Number, out E : Expression<T>>(
|
|||||||
private fun visitVariables(
|
private fun visitVariables(
|
||||||
node: TypedMst<T>,
|
node: TypedMst<T>,
|
||||||
arrayMode: Boolean,
|
arrayMode: Boolean,
|
||||||
alreadyLoaded: MutableList<Symbol> = mutableListOf(),
|
alreadyLoaded: MutableList<Symbol> = mutableListOf()
|
||||||
): Unit = when (node) {
|
): Unit = when (node) {
|
||||||
is TypedMst.Variable -> if (node.symbol !in alreadyLoaded) {
|
is TypedMst.Variable -> if (node.symbol !in alreadyLoaded) {
|
||||||
alreadyLoaded += node.symbol
|
alreadyLoaded += node.symbol
|
||||||
|
@ -8,6 +8,7 @@ package space.kscience.kmath.asm.internal
|
|||||||
import org.objectweb.asm.*
|
import org.objectweb.asm.*
|
||||||
import org.objectweb.asm.commons.InstructionAdapter
|
import org.objectweb.asm.commons.InstructionAdapter
|
||||||
import space.kscience.kmath.expressions.Expression
|
import space.kscience.kmath.expressions.Expression
|
||||||
|
import space.kscience.kmath.expressions.MST
|
||||||
import kotlin.contracts.InvocationKind
|
import kotlin.contracts.InvocationKind
|
||||||
import kotlin.contracts.contract
|
import kotlin.contracts.contract
|
||||||
|
|
||||||
|
@ -9,7 +9,6 @@ Commons math binding for kmath
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-commons:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-commons:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -35,13 +35,11 @@ public class CMGaussRuleIntegrator(
|
|||||||
range.start,
|
range.start,
|
||||||
range.endInclusive
|
range.endInclusive
|
||||||
)
|
)
|
||||||
|
|
||||||
GaussRule.LEGENDREHP -> factory.legendreHighPrecision(
|
GaussRule.LEGENDREHP -> factory.legendreHighPrecision(
|
||||||
numpoints,
|
numpoints,
|
||||||
range.start,
|
range.start,
|
||||||
range.endInclusive
|
range.endInclusive
|
||||||
)
|
)
|
||||||
|
|
||||||
GaussRule.UNIFORM -> GaussIntegrator(
|
GaussRule.UNIFORM -> GaussIntegrator(
|
||||||
getUniformRule(
|
getUniformRule(
|
||||||
range.start,
|
range.start,
|
||||||
|
@ -48,11 +48,9 @@ public fun CMLinearSpace.inverse(
|
|||||||
|
|
||||||
|
|
||||||
public fun CMLinearSpace.solver(decomposition: CMDecomposition): LinearSolver<Double> = object : LinearSolver<Double> {
|
public fun CMLinearSpace.solver(decomposition: CMDecomposition): LinearSolver<Double> = object : LinearSolver<Double> {
|
||||||
override fun solve(a: Matrix<Double>, b: Matrix<Double>): Matrix<Double> =
|
override fun solve(a: Matrix<Double>, b: Matrix<Double>): Matrix<Double> = solver(a, decomposition).solve(b.toCM().origin).wrap()
|
||||||
solver(a, decomposition).solve(b.toCM().origin).wrap()
|
|
||||||
|
|
||||||
override fun solve(a: Matrix<Double>, b: Point<Double>): Point<Double> =
|
override fun solve(a: Matrix<Double>, b: Point<Double>): Point<Double> = solver(a, decomposition).solve(b.toCM().origin).toPoint()
|
||||||
solver(a, decomposition).solve(b.toCM().origin).toPoint()
|
|
||||||
|
|
||||||
override fun inverse(matrix: Matrix<Double>): Matrix<Double> = solver(matrix, decomposition).inverse.wrap()
|
override fun inverse(matrix: Matrix<Double>): Matrix<Double> = solver(matrix, decomposition).inverse.wrap()
|
||||||
}
|
}
|
||||||
|
@ -43,7 +43,7 @@ public object CMOptimizerData : SetAttribute<SymbolIndexer.() -> OptimizationDat
|
|||||||
* Specify Commons-maths optimization data.
|
* Specify Commons-maths optimization data.
|
||||||
*/
|
*/
|
||||||
public fun AttributesBuilder<FunctionOptimization<Double>>.cmOptimizationData(data: SymbolIndexer.() -> OptimizationData) {
|
public fun AttributesBuilder<FunctionOptimization<Double>>.cmOptimizationData(data: SymbolIndexer.() -> OptimizationData) {
|
||||||
CMOptimizerData add data
|
CMOptimizerData.add(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
public fun AttributesBuilder<FunctionOptimization<Double>>.simplexSteps(vararg steps: Pair<Symbol, Double>) {
|
public fun AttributesBuilder<FunctionOptimization<Double>>.simplexSteps(vararg steps: Pair<Symbol, Double>) {
|
||||||
|
@ -5,12 +5,12 @@ Complex and hypercomplex number systems in KMath.
|
|||||||
- [complex](src/commonMain/kotlin/space/kscience/kmath/complex/Complex.kt) : Complex numbers operations
|
- [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
|
- [quaternion](src/commonMain/kotlin/space/kscience/kmath/complex/Quaternion.kt) : Quaternions and their composition
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-complex:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-complex:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -19,8 +19,7 @@ import kotlin.contracts.contract
|
|||||||
*/
|
*/
|
||||||
@OptIn(UnstableKMathAPI::class)
|
@OptIn(UnstableKMathAPI::class)
|
||||||
public sealed class ComplexFieldOpsND : BufferedFieldOpsND<Complex, ComplexField>(ComplexField.bufferAlgebra),
|
public sealed class ComplexFieldOpsND : BufferedFieldOpsND<Complex, ComplexField>(ComplexField.bufferAlgebra),
|
||||||
ScaleOperations<StructureND<Complex>>, ExtendedFieldOps<StructureND<Complex>>,
|
ScaleOperations<StructureND<Complex>>, ExtendedFieldOps<StructureND<Complex>>, PowerOperations<StructureND<Complex>> {
|
||||||
PowerOperations<StructureND<Complex>> {
|
|
||||||
|
|
||||||
@OptIn(PerformancePitfall::class)
|
@OptIn(PerformancePitfall::class)
|
||||||
override fun StructureND<Complex>.toBufferND(): BufferND<Complex> = when (this) {
|
override fun StructureND<Complex>.toBufferND(): BufferND<Complex> = when (this) {
|
||||||
|
@ -2,28 +2,23 @@
|
|||||||
|
|
||||||
The core interfaces of KMath.
|
The core interfaces of KMath.
|
||||||
|
|
||||||
- [algebras](src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces
|
- [algebras](src/commonMain/kotlin/space/kscience/kmath/operations/Algebra.kt) : Algebraic structures like rings, spaces and fields.
|
||||||
and fields.
|
- [nd](src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and operations on them.
|
||||||
- [nd](src/commonMain/kotlin/space/kscience/kmath/structures/StructureND.kt) : Many-dimensional structures and
|
- [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.
|
||||||
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
|
- [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
|
- [expressions](src/commonMain/kotlin/space/kscience/kmath/expressions) : By writing a single mathematical expression once, users will be able to apply different types of
|
||||||
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
|
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.
|
performance calculations to code generation.
|
||||||
- [domains](src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
|
- [domains](src/commonMain/kotlin/space/kscience/kmath/domains) : Domains
|
||||||
- [autodiff](src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic differentiation
|
- [autodiff](src/commonMain/kotlin/space/kscience/kmath/expressions/SimpleAutoDiff.kt) : Automatic differentiation
|
||||||
- [linear.parallel](#) : Parallel implementation for `LinearAlgebra`
|
- [linear.parallel](#) : Parallel implementation for `LinearAlgebra`
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-core:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-core:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -27,7 +27,7 @@ public interface XYErrorColumnarData<T, out X : T, out Y : T> : XYColumnarData<T
|
|||||||
|
|
||||||
public companion object {
|
public companion object {
|
||||||
public fun <T, X : T, Y : T> of(
|
public fun <T, X : T, Y : T> of(
|
||||||
x: Buffer<X>, y: Buffer<Y>, yErr: Buffer<Y>,
|
x: Buffer<X>, y: Buffer<Y>, yErr: Buffer<Y>
|
||||||
): XYErrorColumnarData<T, X, Y> {
|
): XYErrorColumnarData<T, X, Y> {
|
||||||
require(x.size == y.size) { "Buffer size mismatch. x buffer size is ${x.size}, y buffer size is ${y.size}" }
|
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}" }
|
require(y.size == yErr.size) { "Buffer size mismatch. y buffer size is ${x.size}, yErr buffer size is ${y.size}" }
|
||||||
|
@ -58,7 +58,6 @@ public fun <T> MST.interpret(algebra: Algebra<T>, arguments: Map<Symbol, T>): T
|
|||||||
this.operation,
|
this.operation,
|
||||||
algebra.number(this.value.value),
|
algebra.number(this.value.value),
|
||||||
)
|
)
|
||||||
|
|
||||||
else -> algebra.unaryOperationFunction(this.operation)(this.value.interpret(algebra, arguments))
|
else -> algebra.unaryOperationFunction(this.operation)(this.value.interpret(algebra, arguments))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -224,7 +224,11 @@ public inline fun <T : Any, F : Field<T>> SimpleAutoDiffField<T, F>.const(block:
|
|||||||
public fun <T : Any, F : Field<T>> F.simpleAutoDiff(
|
public fun <T : Any, F : Field<T>> F.simpleAutoDiff(
|
||||||
bindings: Map<Symbol, T>,
|
bindings: Map<Symbol, T>,
|
||||||
body: SimpleAutoDiffField<T, F>.() -> AutoDiffValue<T>,
|
body: SimpleAutoDiffField<T, F>.() -> AutoDiffValue<T>,
|
||||||
): DerivationResult<T> = SimpleAutoDiffField(this, bindings).differentiate(body)
|
): DerivationResult<T> {
|
||||||
|
contract { callsInPlace(body, InvocationKind.EXACTLY_ONCE) }
|
||||||
|
|
||||||
|
return SimpleAutoDiffField(this, bindings).differentiate(body)
|
||||||
|
}
|
||||||
|
|
||||||
public fun <T : Any, F : Field<T>> F.simpleAutoDiff(
|
public fun <T : Any, F : Field<T>> F.simpleAutoDiff(
|
||||||
vararg bindings: Pair<Symbol, T>,
|
vararg bindings: Pair<Symbol, T>,
|
||||||
|
@ -182,7 +182,7 @@ public interface LinearSpace<T, out A : Ring<T>> : MatrixScope<T> {
|
|||||||
* better use [StructureND.getOrComputeAttribute].
|
* better use [StructureND.getOrComputeAttribute].
|
||||||
*/
|
*/
|
||||||
@UnstableKMathAPI
|
@UnstableKMathAPI
|
||||||
public fun <V : Any, A : StructureAttribute<V>> Matrix<T>.withComputedAttribute(
|
public fun <V : Any, A : StructureAttribute<V>> Matrix<T>.compute(
|
||||||
attribute: A,
|
attribute: A,
|
||||||
): Matrix<T>? {
|
): Matrix<T>? {
|
||||||
return if (attributes[attribute] != null) {
|
return if (attributes[attribute] != null) {
|
||||||
|
@ -18,11 +18,12 @@ public sealed class Int16RingOpsND : BufferedRingOpsND<Short, Int16Ring>(Int16Ri
|
|||||||
|
|
||||||
@OptIn(UnstableKMathAPI::class)
|
@OptIn(UnstableKMathAPI::class)
|
||||||
public class Int16RingND(
|
public class Int16RingND(
|
||||||
override val shape: ShapeND,
|
override val shape: ShapeND
|
||||||
) : Int16RingOpsND(), RingND<Short, Int16Ring>, NumbersAddOps<StructureND<Short>> {
|
) : Int16RingOpsND(), RingND<Short, Int16Ring>, NumbersAddOps<StructureND<Short>> {
|
||||||
|
|
||||||
override fun number(value: Number): BufferND<Short> {
|
override fun number(value: Number): BufferND<Short> {
|
||||||
val short = value.toShort() // minimize conversions
|
val short
|
||||||
|
= value.toShort() // minimize conversions
|
||||||
return structureND(shape) { short }
|
return structureND(shape) { short }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@ public sealed class IntRingOpsND : BufferedRingOpsND<Int, Int32Ring>(Int32Ring.b
|
|||||||
|
|
||||||
@OptIn(UnstableKMathAPI::class)
|
@OptIn(UnstableKMathAPI::class)
|
||||||
public class IntRingND(
|
public class IntRingND(
|
||||||
override val shape: ShapeND,
|
override val shape: ShapeND
|
||||||
) : IntRingOpsND(), RingND<Int, Int32Ring>, NumbersAddOps<StructureND<Int>> {
|
) : IntRingOpsND(), RingND<Int, Int32Ring>, NumbersAddOps<StructureND<Int>> {
|
||||||
|
|
||||||
override fun number(value: Number): BufferND<Int> {
|
override fun number(value: Number): BufferND<Int> {
|
||||||
|
@ -14,13 +14,13 @@ import kotlin.jvm.JvmName
|
|||||||
public fun <T, A : Algebra<T>> AlgebraND<T, A>.structureND(
|
public fun <T, A : Algebra<T>> AlgebraND<T, A>.structureND(
|
||||||
shapeFirst: Int,
|
shapeFirst: Int,
|
||||||
vararg shapeRest: Int,
|
vararg shapeRest: Int,
|
||||||
initializer: A.(IntArray) -> T,
|
initializer: A.(IntArray) -> T
|
||||||
): StructureND<T> = structureND(ShapeND(shapeFirst, *shapeRest), initializer)
|
): StructureND<T> = structureND(ShapeND(shapeFirst, *shapeRest), initializer)
|
||||||
|
|
||||||
public fun <T, A : Algebra<T>> AlgebraND<T, A>.mutableStructureND(
|
public fun <T, A : Algebra<T>> AlgebraND<T, A>.mutableStructureND(
|
||||||
shapeFirst: Int,
|
shapeFirst: Int,
|
||||||
vararg shapeRest: Int,
|
vararg shapeRest: Int,
|
||||||
initializer: A.(IntArray) -> T,
|
initializer: A.(IntArray) -> T
|
||||||
): MutableStructureND<T> = mutableStructureND(ShapeND(shapeFirst, *shapeRest), initializer)
|
): MutableStructureND<T> = mutableStructureND(ShapeND(shapeFirst, *shapeRest), initializer)
|
||||||
|
|
||||||
public fun <T, A : Group<T>> AlgebraND<T, A>.zero(shape: ShapeND): StructureND<T> = structureND(shape) { zero }
|
public fun <T, A : Group<T>> AlgebraND<T, A>.zero(shape: ShapeND): StructureND<T> = structureND(shape) { zero }
|
||||||
|
@ -454,12 +454,10 @@ public fun String.parseBigInteger(): BigInt? {
|
|||||||
sign = +1
|
sign = +1
|
||||||
1
|
1
|
||||||
}
|
}
|
||||||
|
|
||||||
'-' -> {
|
'-' -> {
|
||||||
sign = -1
|
sign = -1
|
||||||
1
|
1
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
sign = +1
|
sign = +1
|
||||||
0
|
0
|
||||||
|
@ -99,8 +99,7 @@ public fun <T> Iterable<T>.sumWith(group: Group<T>): T = group.sum(this)
|
|||||||
* @param group tha algebra that provides addition
|
* @param group tha algebra that provides addition
|
||||||
* @param extractor the (inline) lambda function to extract value
|
* @param extractor the (inline) lambda function to extract value
|
||||||
*/
|
*/
|
||||||
public inline fun <T, R> Iterable<T>.sumWithGroupOf(group: Group<R>, extractor: (T) -> R): R =
|
public inline fun <T, R> Iterable<T>.sumWithGroupOf(group: Group<R>, extractor: (T) -> R): R = this.fold(group.zero) { left: R, right: T ->
|
||||||
this.fold(group.zero) { left: R, right: T ->
|
|
||||||
group.add(left, extractor(right))
|
group.add(left, extractor(right))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -55,7 +55,7 @@ public fun FlaggedBuffer<*>.isMissing(index: Int): Boolean = hasFlag(index, Valu
|
|||||||
*/
|
*/
|
||||||
public class FlaggedDoubleBuffer(
|
public class FlaggedDoubleBuffer(
|
||||||
public val values: DoubleArray,
|
public val values: DoubleArray,
|
||||||
public val flags: ByteArray,
|
public val flags: ByteArray
|
||||||
) : FlaggedBuffer<Double?>, Buffer<Double?> {
|
) : FlaggedBuffer<Double?>, Buffer<Double?> {
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
@ -37,8 +37,7 @@ public typealias FloatBuffer = Float32Buffer
|
|||||||
* The function [init] is called for each array element sequentially starting from the first one.
|
* 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.
|
* It should return the value for a buffer element given its index.
|
||||||
*/
|
*/
|
||||||
public inline fun Float32Buffer(size: Int, init: (Int) -> Float): Float32Buffer =
|
public inline fun Float32Buffer(size: Int, init: (Int) -> Float): Float32Buffer = Float32Buffer(FloatArray(size) { init(it) })
|
||||||
Float32Buffer(FloatArray(size) { init(it) })
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a new [Float32Buffer] of given elements.
|
* Returns a new [Float32Buffer] of given elements.
|
||||||
|
@ -74,8 +74,7 @@ public fun <T> Buffer<T>.copy(bufferFactory: BufferFactory<T>): Buffer<T> = if (
|
|||||||
/**
|
/**
|
||||||
* Returns a mutable shallow copy of the buffer.
|
* Returns a mutable shallow copy of the buffer.
|
||||||
*/
|
*/
|
||||||
public fun <T> Buffer<T>.mutableCopy(bufferFactory: MutableBufferFactory<T>): MutableBuffer<T> =
|
public fun <T> Buffer<T>.mutableCopy(bufferFactory: MutableBufferFactory<T>): MutableBuffer<T> =if(this is ArrayBuffer){
|
||||||
if (this is ArrayBuffer) {
|
|
||||||
ArrayBuffer(array.copyOf())
|
ArrayBuffer(array.copyOf())
|
||||||
}else{
|
}else{
|
||||||
bufferFactory(size,::get)
|
bufferFactory(size,::get)
|
||||||
|
@ -67,11 +67,7 @@ class PermSortTest {
|
|||||||
assertContentEquals(expected, permutations.map { platforms[it] }, "PermSort using custom ascending comparator")
|
assertContentEquals(expected, permutations.map { platforms[it] }, "PermSort using custom ascending comparator")
|
||||||
|
|
||||||
permutations = platforms.indicesSortedWith(compareByDescending { it.name.length })
|
permutations = platforms.indicesSortedWith(compareByDescending { it.name.length })
|
||||||
assertContentEquals(
|
assertContentEquals(expected.reversed(), permutations.map { platforms[it] }, "PermSort using custom descending comparator")
|
||||||
expected.reversed(),
|
|
||||||
permutations.map { platforms[it] },
|
|
||||||
"PermSort using custom descending comparator"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun testPermutation(bufferSize: Int) {
|
private fun testPermutation(bufferSize: Int) {
|
||||||
|
@ -8,5 +8,4 @@ package space.kscience.kmath.operations
|
|||||||
/**
|
/**
|
||||||
* Check if number is an integer
|
* Check if number is an integer
|
||||||
*/
|
*/
|
||||||
public actual fun Number.isInteger(): Boolean =
|
public actual fun Number.isInteger(): Boolean = (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0)
|
||||||
(this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0)
|
|
@ -33,8 +33,7 @@ public fun <T> MutableBuffer.Companion.parallel(
|
|||||||
typeOf<Double>() -> IntStream.range(0, size).parallel().mapToDouble { initializer(it) as Float64 }.toArray()
|
typeOf<Double>() -> IntStream.range(0, size).parallel().mapToDouble { initializer(it) as Float64 }.toArray()
|
||||||
.asBuffer() as MutableBuffer<T>
|
.asBuffer() as MutableBuffer<T>
|
||||||
//TODO add unsigned types
|
//TODO add unsigned types
|
||||||
else -> IntStream.range(0, size).parallel().mapToObj { initializer(it) }.collect(Collectors.toList<T>())
|
else -> IntStream.range(0, size).parallel().mapToObj { initializer(it) }.collect(Collectors.toList<T>()).asMutableBuffer()
|
||||||
.asMutableBuffer()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ParallelBufferFactory<T>(override val type: SafeType<T>) : MutableBufferFactory<T> {
|
public class ParallelBufferFactory<T>(override val type: SafeType<T>) : MutableBufferFactory<T> {
|
||||||
|
@ -8,5 +8,4 @@ package space.kscience.kmath.operations
|
|||||||
/**
|
/**
|
||||||
* Check if number is an integer
|
* Check if number is an integer
|
||||||
*/
|
*/
|
||||||
public actual fun Number.isInteger(): Boolean =
|
public actual fun Number.isInteger(): Boolean = (this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0)
|
||||||
(this is Int) || (this is Long) || (this is Short) || (this.toDouble() % 1 == 0.0)
|
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-coroutines
|
# Module kmath-coroutines
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-coroutines:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-coroutines:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -25,7 +25,6 @@ public class LazyStructureND<out T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
public suspend fun await(index: IntArray): T = async(index).await()
|
public suspend fun await(index: IntArray): T = async(index).await()
|
||||||
|
|
||||||
@PerformancePitfall
|
@PerformancePitfall
|
||||||
override operator fun get(index: IntArray): T = runBlocking { async(index).await() }
|
override operator fun get(index: IntArray): T = runBlocking { async(index).await() }
|
||||||
|
|
||||||
@ -49,13 +48,13 @@ public suspend fun <T> StructureND<T>.await(index: IntArray): T =
|
|||||||
* PENDING would benefit from KEEP-176
|
* PENDING would benefit from KEEP-176
|
||||||
*/
|
*/
|
||||||
@OptIn(PerformancePitfall::class)
|
@OptIn(PerformancePitfall::class)
|
||||||
public inline fun <T, R> StructureND<T>.mapAsyncIndexed(
|
public inline fun <T, reified R> StructureND<T>.mapAsyncIndexed(
|
||||||
scope: CoroutineScope,
|
scope: CoroutineScope,
|
||||||
crossinline function: suspend (T, index: IntArray) -> R,
|
crossinline function: suspend (T, index: IntArray) -> R,
|
||||||
): LazyStructureND<R> = LazyStructureND(scope, shape) { index -> function(get(index), index) }
|
): LazyStructureND<R> = LazyStructureND(scope, shape) { index -> function(get(index), index) }
|
||||||
|
|
||||||
@OptIn(PerformancePitfall::class)
|
@OptIn(PerformancePitfall::class)
|
||||||
public inline fun <T, R> StructureND<T>.mapAsync(
|
public inline fun <T, reified R> StructureND<T>.mapAsync(
|
||||||
scope: CoroutineScope,
|
scope: CoroutineScope,
|
||||||
crossinline function: suspend (T) -> R,
|
crossinline function: suspend (T) -> R,
|
||||||
): LazyStructureND<R> = LazyStructureND(scope, shape) { index -> function(get(index)) }
|
): LazyStructureND<R> = LazyStructureND(scope, shape) { index -> function(get(index)) }
|
||||||
|
@ -9,7 +9,6 @@ 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`.
|
The Maven coordinates of this project are `space.kscience:kmath-dimensions:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -6,12 +6,12 @@ EJML based linear algebra implementation.
|
|||||||
- [ejml-matrix](src/main/kotlin/space/kscience/kmath/ejml/EjmlMatrix.kt) : Matrix implementation.
|
- [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-linear-space](src/main/kotlin/space/kscience/kmath/ejml/EjmlLinearSpace.kt) : LinearSpace implementations.
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-ejml:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-ejml:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -682,9 +682,7 @@ public object EjmlLinearSpaceDSCC : EjmlLinearSpace<Double, Float64Field, DMatri
|
|||||||
Determinant -> CommonOps_DSCC.det(origin)
|
Determinant -> CommonOps_DSCC.det(origin)
|
||||||
|
|
||||||
QR -> object : QRDecomposition<Double> {
|
QR -> object : QRDecomposition<Double> {
|
||||||
val ejmlQr by lazy {
|
val ejmlQr by lazy { DecompositionFactory_DSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } }
|
||||||
DecompositionFactory_DSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) }
|
|
||||||
}
|
|
||||||
override val q: Matrix<Double> get() = ejmlQr.getQ(null, false).wrapMatrix()
|
override val q: Matrix<Double> get() = ejmlQr.getQ(null, false).wrapMatrix()
|
||||||
override val r: Matrix<Double> get() = ejmlQr.getR(null, false).wrapMatrix()
|
override val r: Matrix<Double> get() = ejmlQr.getR(null, false).wrapMatrix()
|
||||||
}
|
}
|
||||||
@ -905,9 +903,7 @@ public object EjmlLinearSpaceFSCC : EjmlLinearSpace<Float, Float32Field, FMatrix
|
|||||||
Determinant -> CommonOps_FSCC.det(origin)
|
Determinant -> CommonOps_FSCC.det(origin)
|
||||||
|
|
||||||
QR -> object : QRDecomposition<Float32> {
|
QR -> object : QRDecomposition<Float32> {
|
||||||
val ejmlQr by lazy {
|
val ejmlQr by lazy { DecompositionFactory_FSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) } }
|
||||||
DecompositionFactory_FSCC.qr(FillReducing.NONE).apply { decompose(origin.copy()) }
|
|
||||||
}
|
|
||||||
override val q: Matrix<Float32> get() = ejmlQr.getQ(null, false).wrapMatrix()
|
override val q: Matrix<Float32> get() = ejmlQr.getQ(null, false).wrapMatrix()
|
||||||
override val r: Matrix<Float32> get() = ejmlQr.getR(null, false).wrapMatrix()
|
override val r: Matrix<Float32> get() = ejmlQr.getR(null, false).wrapMatrix()
|
||||||
}
|
}
|
||||||
|
@ -2,18 +2,16 @@
|
|||||||
|
|
||||||
Specialization of KMath APIs for Double numbers.
|
Specialization of KMath APIs for Double numbers.
|
||||||
|
|
||||||
- [DoubleVector](src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for
|
- [DoubleVector](src/commonMain/kotlin/space/kscience/kmath/real/DoubleVector.kt) : Numpy-like operations for Buffers/Points
|
||||||
Buffers/Points
|
- [DoubleMatrix](src/commonMain/kotlin/space/kscience/kmath/real/DoubleMatrix.kt) : Numpy-like operations for 2d real structures
|
||||||
- [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
|
- [grids](src/commonMain/kotlin/space/kscience/kmath/structures/grids.kt) : Uniform grid generators
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-for-real:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-for-real:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -4,18 +4,16 @@ Functions and interpolations.
|
|||||||
|
|
||||||
- [piecewise](src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions.
|
- [piecewise](src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt) : Piecewise functions.
|
||||||
- [polynomials](src/commonMain/kotlin/space/kscience/kmath/functions/Polynomial.kt) : Polynomial 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
|
- [linear interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/LinearInterpolator.kt) : Linear XY interpolator.
|
||||||
interpolator.
|
- [spline interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline XY interpolator.
|
||||||
- [spline interpolation](src/commonMain/kotlin/space/kscience/kmath/interpolation/SplineInterpolator.kt) : Cubic spline
|
|
||||||
XY interpolator.
|
|
||||||
- [integration](#) : Univariate and multivariate quadratures
|
- [integration](#) : Univariate and multivariate quadratures
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-functions:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-functions:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -26,7 +26,7 @@ public fun <T, A : Any> MultivariateIntegrand<T>.withAttribute(
|
|||||||
|
|
||||||
public fun <T> MultivariateIntegrand<T>.withAttributes(
|
public fun <T> MultivariateIntegrand<T>.withAttributes(
|
||||||
block: AttributesBuilder<MultivariateIntegrand<T>>.() -> Unit,
|
block: AttributesBuilder<MultivariateIntegrand<T>>.() -> Unit,
|
||||||
): MultivariateIntegrand<T> = withAttributes(attributes.modified(block))
|
): MultivariateIntegrand<T> = withAttributes(attributes.modify(block))
|
||||||
|
|
||||||
public inline fun <reified T : Any> MultivariateIntegrand(
|
public inline fun <reified T : Any> MultivariateIntegrand(
|
||||||
attributeBuilder: AttributesBuilder<MultivariateIntegrand<T>>.() -> Unit,
|
attributeBuilder: AttributesBuilder<MultivariateIntegrand<T>>.() -> Unit,
|
||||||
|
@ -27,7 +27,7 @@ public fun <T, A : Any> UnivariateIntegrand<T>.withAttribute(
|
|||||||
|
|
||||||
public fun <T> UnivariateIntegrand<T>.withAttributes(
|
public fun <T> UnivariateIntegrand<T>.withAttributes(
|
||||||
block: AttributesBuilder<UnivariateIntegrand<T>>.() -> Unit,
|
block: AttributesBuilder<UnivariateIntegrand<T>>.() -> Unit,
|
||||||
): UnivariateIntegrand<T> = withAttributes(attributes.modified(block))
|
): UnivariateIntegrand<T> = withAttributes(attributes.modify(block))
|
||||||
|
|
||||||
public inline fun <reified T : Any> UnivariateIntegrand(
|
public inline fun <reified T : Any> UnivariateIntegrand(
|
||||||
attributeBuilder: AttributesBuilder<UnivariateIntegrand<T>>.() -> Unit,
|
attributeBuilder: AttributesBuilder<UnivariateIntegrand<T>>.() -> Unit,
|
||||||
|
@ -8,8 +8,7 @@
|
|||||||
package space.kscience.kmath.functions
|
package space.kscience.kmath.functions
|
||||||
|
|
||||||
import space.kscience.kmath.functions.testUtils.*
|
import space.kscience.kmath.functions.testUtils.*
|
||||||
import kotlin.test.Test
|
import kotlin.test.*
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
|
|
||||||
class PolynomialTest {
|
class PolynomialTest {
|
||||||
@ -53,7 +52,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_Constant_minus() {
|
fun test_Polynomial_Constant_minus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -94,7 +92,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_Constant_times() {
|
fun test_Polynomial_Constant_times() {
|
||||||
IntModuloRing(35).polynomialSpace {
|
IntModuloRing(35).polynomialSpace {
|
||||||
@ -110,7 +107,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Constant_Polynomial_plus() {
|
fun test_Constant_Polynomial_plus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -151,7 +147,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Constant_Polynomial_minus() {
|
fun test_Constant_Polynomial_minus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -192,7 +187,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Constant_Polynomial_times() {
|
fun test_Constant_Polynomial_times() {
|
||||||
IntModuloRing(35).polynomialSpace {
|
IntModuloRing(35).polynomialSpace {
|
||||||
@ -208,7 +202,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_unaryMinus() {
|
fun test_Polynomial_unaryMinus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -224,7 +217,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_Polynomial_plus() {
|
fun test_Polynomial_Polynomial_plus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -258,7 +250,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_Polynomial_minus() {
|
fun test_Polynomial_Polynomial_minus() {
|
||||||
RationalField.polynomialSpace {
|
RationalField.polynomialSpace {
|
||||||
@ -292,7 +283,6 @@ class PolynomialTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_Polynomial_times() {
|
fun test_Polynomial_Polynomial_times() {
|
||||||
IntModuloRing(35).polynomialSpace {
|
IntModuloRing(35).polynomialSpace {
|
||||||
|
@ -53,7 +53,6 @@ class PolynomialUtilTest {
|
|||||||
"test 5"
|
"test 5"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_value_Constant() {
|
fun test_Polynomial_value_Constant() {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
@ -86,7 +85,6 @@ class PolynomialUtilTest {
|
|||||||
"test 5"
|
"test 5"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_differentiate() {
|
fun test_Polynomial_differentiate() {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
@ -96,27 +94,20 @@ class PolynomialUtilTest {
|
|||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(-8, 3), Rational(8, 9), Rational(15, 7), Rational(-20, 9)),
|
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(
|
Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 2"
|
"test 2"
|
||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(0), Rational(8, 9), Rational(15, 7), Rational(-20, 9)),
|
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(
|
Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).differentiate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 3"
|
"test 3"
|
||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(-8, 3), Rational(8, 9), Rational(15, 7), Rational(0)),
|
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(
|
Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).differentiate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 4"
|
"test 4"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_Polynomial_integrate() {
|
fun test_Polynomial_integrate() {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
@ -126,23 +117,17 @@ class PolynomialUtilTest {
|
|||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(0), Rational(1, 5), Rational(-4, 3), Rational(4, 27), Rational(5, 28), Rational(-1, 9)),
|
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(
|
Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 2"
|
"test 2"
|
||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(0), Rational(0), Rational(0), Rational(4, 27), Rational(5, 28), Rational(-1, 9)),
|
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(
|
Polynomial(Rational(0), Rational(0), Rational(4, 9), Rational(5, 7), Rational(-5, 9)).integrate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 3"
|
"test 3"
|
||||||
)
|
)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Polynomial(Rational(0), Rational(1, 5), Rational(-4, 3), Rational(4, 27), Rational(5, 28), Rational(0)),
|
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(
|
Polynomial(Rational(1, 5), Rational(-8, 3), Rational(4, 9), Rational(5, 7), Rational(0)).integrate(RationalField),
|
||||||
RationalField
|
|
||||||
),
|
|
||||||
"test 4"
|
"test 4"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -37,7 +37,6 @@ class IntModulo {
|
|||||||
modulus,
|
modulus,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun plus(other: IntModulo): IntModulo {
|
operator fun plus(other: IntModulo): IntModulo {
|
||||||
require(modulus == other.modulus) { "can not add two residue different modulo" }
|
require(modulus == other.modulus) { "can not add two residue different modulo" }
|
||||||
return IntModulo(
|
return IntModulo(
|
||||||
@ -46,14 +45,12 @@ class IntModulo {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun plus(other: Int): IntModulo =
|
operator fun plus(other: Int): IntModulo =
|
||||||
IntModulo(
|
IntModulo(
|
||||||
(residue + other) % modulus,
|
(residue + other) % modulus,
|
||||||
modulus,
|
modulus,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun minus(other: IntModulo): IntModulo {
|
operator fun minus(other: IntModulo): IntModulo {
|
||||||
require(modulus == other.modulus) { "can not subtract two residue different modulo" }
|
require(modulus == other.modulus) { "can not subtract two residue different modulo" }
|
||||||
return IntModulo(
|
return IntModulo(
|
||||||
@ -62,14 +59,12 @@ class IntModulo {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun minus(other: Int): IntModulo =
|
operator fun minus(other: Int): IntModulo =
|
||||||
IntModulo(
|
IntModulo(
|
||||||
(residue - other) % modulus,
|
(residue - other) % modulus,
|
||||||
modulus,
|
modulus,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun times(other: IntModulo): IntModulo {
|
operator fun times(other: IntModulo): IntModulo {
|
||||||
require(modulus == other.modulus) { "can not multiply two residue different modulo" }
|
require(modulus == other.modulus) { "can not multiply two residue different modulo" }
|
||||||
return IntModulo(
|
return IntModulo(
|
||||||
@ -78,14 +73,12 @@ class IntModulo {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun times(other: Int): IntModulo =
|
operator fun times(other: Int): IntModulo =
|
||||||
IntModulo(
|
IntModulo(
|
||||||
(residue * other) % modulus,
|
(residue * other) % modulus,
|
||||||
modulus,
|
modulus,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun div(other: IntModulo): IntModulo {
|
operator fun div(other: IntModulo): IntModulo {
|
||||||
require(modulus == other.modulus) { "can not divide two residue different modulo" }
|
require(modulus == other.modulus) { "can not divide two residue different modulo" }
|
||||||
val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other.residue, modulus)
|
val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other.residue, modulus)
|
||||||
@ -96,7 +89,6 @@ class IntModulo {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun div(other: Int): IntModulo {
|
operator fun div(other: Int): IntModulo {
|
||||||
val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other, modulus)
|
val (reciprocalCandidate, gcdOfOtherResidueAndModulus) = bezoutIdentityWithGCD(other, modulus)
|
||||||
require(gcdOfOtherResidueAndModulus == 1) { "can not divide to residue that has non-trivial GCD with modulo" }
|
require(gcdOfOtherResidueAndModulus == 1) { "can not divide to residue that has non-trivial GCD with modulo" }
|
||||||
@ -106,7 +98,6 @@ class IntModulo {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean =
|
override fun equals(other: Any?): Boolean =
|
||||||
when (other) {
|
when (other) {
|
||||||
is IntModulo -> residue == other.residue && modulus == other.modulus
|
is IntModulo -> residue == other.residue && modulus == other.modulus
|
||||||
|
@ -11,7 +11,6 @@ import space.kscience.kmath.functions.PolynomialSpace
|
|||||||
|
|
||||||
fun PolynomialSpace<IntModulo, IntModuloRing>.Polynomial(vararg coefs: Int): Polynomial<IntModulo> =
|
fun PolynomialSpace<IntModulo, IntModuloRing>.Polynomial(vararg coefs: Int): Polynomial<IntModulo> =
|
||||||
Polynomial(coefs.map { IntModulo(it, ring.modulus) })
|
Polynomial(coefs.map { IntModulo(it, ring.modulus) })
|
||||||
|
|
||||||
fun IntModuloRing.Polynomial(vararg coefs: Int): Polynomial<IntModulo> =
|
fun IntModuloRing.Polynomial(vararg coefs: Int): Polynomial<IntModulo> =
|
||||||
Polynomial(coefs.map { IntModulo(it, modulus) })
|
Polynomial(coefs.map { IntModulo(it, modulus) })
|
||||||
|
|
||||||
|
@ -57,21 +57,18 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun plus(other: Int): Rational =
|
operator fun plus(other: Int): Rational =
|
||||||
Rational(
|
Rational(
|
||||||
numerator + denominator * other.toLong(),
|
numerator + denominator * other.toLong(),
|
||||||
denominator,
|
denominator,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun plus(other: Long): Rational =
|
operator fun plus(other: Long): Rational =
|
||||||
Rational(
|
Rational(
|
||||||
numerator + denominator * other,
|
numerator + denominator * other,
|
||||||
denominator,
|
denominator,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun minus(other: Rational): Rational {
|
operator fun minus(other: Rational): Rational {
|
||||||
val denominatorsGcd = gcd(denominator, other.denominator)
|
val denominatorsGcd = gcd(denominator, other.denominator)
|
||||||
val dividedThisDenominator = denominator / denominatorsGcd
|
val dividedThisDenominator = denominator / denominatorsGcd
|
||||||
@ -84,21 +81,18 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun minus(other: Int): Rational =
|
operator fun minus(other: Int): Rational =
|
||||||
Rational(
|
Rational(
|
||||||
numerator - denominator * other.toLong(),
|
numerator - denominator * other.toLong(),
|
||||||
denominator,
|
denominator,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun minus(other: Long): Rational =
|
operator fun minus(other: Long): Rational =
|
||||||
Rational(
|
Rational(
|
||||||
numerator - denominator * other,
|
numerator - denominator * other,
|
||||||
denominator,
|
denominator,
|
||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
|
|
||||||
operator fun times(other: Rational): Rational {
|
operator fun times(other: Rational): Rational {
|
||||||
val thisDenominatorAndOtherNumeratorGcd = gcd(denominator, other.numerator)
|
val thisDenominatorAndOtherNumeratorGcd = gcd(denominator, other.numerator)
|
||||||
val otherDenominatorAndThisNumeratorGcd = gcd(other.denominator, numerator)
|
val otherDenominatorAndThisNumeratorGcd = gcd(other.denominator, numerator)
|
||||||
@ -108,7 +102,6 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun times(other: Int): Rational {
|
operator fun times(other: Int): Rational {
|
||||||
val other = other.toLong()
|
val other = other.toLong()
|
||||||
val denominatorAndOtherGcd = gcd(denominator, other)
|
val denominatorAndOtherGcd = gcd(denominator, other)
|
||||||
@ -118,7 +111,6 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun times(other: Long): Rational {
|
operator fun times(other: Long): Rational {
|
||||||
val denominatorAndOtherGcd = gcd(denominator, other)
|
val denominatorAndOtherGcd = gcd(denominator, other)
|
||||||
return Rational(
|
return Rational(
|
||||||
@ -127,7 +119,6 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun div(other: Rational): Rational {
|
operator fun div(other: Rational): Rational {
|
||||||
val denominatorsGcd = gcd(denominator, other.denominator)
|
val denominatorsGcd = gcd(denominator, other.denominator)
|
||||||
val numeratorsGcd = gcd(numerator, other.numerator)
|
val numeratorsGcd = gcd(numerator, other.numerator)
|
||||||
@ -136,7 +127,6 @@ class Rational {
|
|||||||
(denominator / denominatorsGcd) * (other.numerator / numeratorsGcd)
|
(denominator / denominatorsGcd) * (other.numerator / numeratorsGcd)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun div(other: Int): Rational {
|
operator fun div(other: Int): Rational {
|
||||||
val other = other.toLong()
|
val other = other.toLong()
|
||||||
val numeratorAndOtherGcd = gcd(numerator, other)
|
val numeratorAndOtherGcd = gcd(numerator, other)
|
||||||
@ -146,7 +136,6 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun div(other: Long): Rational {
|
operator fun div(other: Long): Rational {
|
||||||
val numeratorAndOtherGcd = gcd(numerator, other)
|
val numeratorAndOtherGcd = gcd(numerator, other)
|
||||||
return Rational(
|
return Rational(
|
||||||
@ -155,7 +144,6 @@ class Rational {
|
|||||||
toCheckInput = false
|
toCheckInput = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean =
|
override fun equals(other: Any?): Boolean =
|
||||||
when (other) {
|
when (other) {
|
||||||
is Rational -> numerator == other.numerator && denominator == other.denominator
|
is Rational -> numerator == other.numerator && denominator == other.denominator
|
||||||
|
@ -14,41 +14,13 @@ internal tailrec fun gcd(a: Long, b: Long): Long = if (a == 0L) abs(b) else gcd(
|
|||||||
|
|
||||||
internal fun bezoutIdentityWithGCD(a: Int, b: Int): BezoutIdentityWithGCD<Int> =
|
internal fun bezoutIdentityWithGCD(a: Int, b: Int): BezoutIdentityWithGCD<Int> =
|
||||||
when {
|
when {
|
||||||
a < 0 && b < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, -b, 1, 0, 0, 1)) {
|
a < 0 && b < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, -b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(-first, -second, gcd) }
|
||||||
BezoutIdentityWithGCD(
|
a < 0 -> with(bezoutIdentityWithGCDInternalLogic(-a, b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(-first, second, gcd) }
|
||||||
-first,
|
b < 0 -> with(bezoutIdentityWithGCDInternalLogic(a, -b, 1, 0, 0, 1)) { BezoutIdentityWithGCD(first, -second, gcd) }
|
||||||
-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)
|
else -> bezoutIdentityWithGCDInternalLogic(a, b, 1, 0, 0, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal tailrec fun bezoutIdentityWithGCDInternalLogic(
|
internal tailrec fun bezoutIdentityWithGCDInternalLogic(a: Int, b: Int, m1: Int, m2: Int, m3: Int, m4: Int): BezoutIdentityWithGCD<Int> =
|
||||||
a: Int,
|
|
||||||
b: Int,
|
|
||||||
m1: Int,
|
|
||||||
m2: Int,
|
|
||||||
m3: Int,
|
|
||||||
m4: Int,
|
|
||||||
): BezoutIdentityWithGCD<Int> =
|
|
||||||
if (b == 0) BezoutIdentityWithGCD(m1, m3, a)
|
if (b == 0) BezoutIdentityWithGCD(m1, m3, a)
|
||||||
else {
|
else {
|
||||||
val quotient = a / b
|
val quotient = a / b
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-geometry
|
# Module kmath-geometry
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-geometry:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-geometry:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -27,6 +27,7 @@ public typealias Float64Vector2D = Vector2D<Float64>
|
|||||||
public typealias DoubleVector2D = Float64Vector2D
|
public typealias DoubleVector2D = Float64Vector2D
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 2D Euclidean space
|
* 2D Euclidean space
|
||||||
*/
|
*/
|
||||||
|
@ -18,7 +18,7 @@ fun ClosedRange<Double>.generateList(step: Double): List<Double> = generateSeque
|
|||||||
fun grid(
|
fun grid(
|
||||||
xRange: ClosedRange<Double>,
|
xRange: ClosedRange<Double>,
|
||||||
yRange: ClosedRange<Double>,
|
yRange: ClosedRange<Double>,
|
||||||
step: Double,
|
step: Double
|
||||||
): List<Pair<Double, Double>> {
|
): List<Pair<Double, Double>> {
|
||||||
val xs = xRange.generateList(step)
|
val xs = xRange.generateList(step)
|
||||||
val ys = yRange.generateList(step)
|
val ys = yRange.generateList(step)
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-histograms
|
# Module kmath-histograms
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-histograms:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-histograms:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -4,12 +4,12 @@ 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:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-jafama:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-jafama:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
@ -39,7 +39,6 @@ fun main() {
|
|||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that
|
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.
|
||||||
on Hotspot Jafama is a bit faster.
|
|
||||||
|
|
||||||
> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**.
|
> **Can't find appropriate benchmark data. Try generating readme files after running benchmarks**.
|
||||||
|
@ -24,7 +24,6 @@ fun main() {
|
|||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
According to KMath benchmarks on GraalVM, Jafama functions are slower than JDK math; however, there are indications that
|
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.
|
||||||
on Hotspot Jafama is a bit faster.
|
|
||||||
|
|
||||||
${benchmarkJafamaDouble}
|
${benchmarkJafamaDouble}
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-jupyter
|
# Module kmath-jupyter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-jupyter:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-jupyter:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -2,17 +2,15 @@
|
|||||||
|
|
||||||
[Kotlin∇](https://github.com/breandan/kotlingrad) integration module.
|
[Kotlin∇](https://github.com/breandan/kotlingrad) integration module.
|
||||||
|
|
||||||
- [differentiable-mst-expression](src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based
|
- [differentiable-mst-expression](src/main/kotlin/space/kscience/kmath/kotlingrad/KotlingradExpression.kt) : MST based DifferentiableExpression.
|
||||||
DifferentiableExpression.
|
- [scalars-adapters](src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s SFun and MST
|
||||||
- [scalars-adapters](src/main/kotlin/space/kscience/kmath/kotlingrad/scalarsAdapters.kt) : Conversions between Kotlin∇'s
|
|
||||||
SFun and MST
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-kotlingrad:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-kotlingrad:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-memory
|
# Module kmath-memory
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-memory:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-memory:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -9,7 +9,6 @@ JetBrains Multik connector
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-multik:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-multik:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -16,17 +16,15 @@ import space.kscience.kmath.operations.Float64Field
|
|||||||
import space.kscience.kmath.operations.TrigonometricOperations
|
import space.kscience.kmath.operations.TrigonometricOperations
|
||||||
|
|
||||||
public class MultikDoubleAlgebra(
|
public class MultikDoubleAlgebra(
|
||||||
multikEngine: Engine,
|
multikEngine: Engine
|
||||||
) : MultikDivisionTensorAlgebra<Double, Float64Field>(multikEngine),
|
) : MultikDivisionTensorAlgebra<Double, Float64Field>(multikEngine),
|
||||||
TrigonometricOperations<StructureND<Double>>, ExponentialOperations<StructureND<Double>> {
|
TrigonometricOperations<StructureND<Double>>, ExponentialOperations<StructureND<Double>> {
|
||||||
override val elementAlgebra: Float64Field get() = Float64Field
|
override val elementAlgebra: Float64Field get() = Float64Field
|
||||||
override val dataType: DataType get() = DataType.DoubleDataType
|
override val dataType: DataType get() = DataType.DoubleDataType
|
||||||
|
|
||||||
override fun sin(arg: StructureND<Double>): MultikTensor<Double> =
|
override fun sin(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.sin(arg.asMultik().array).wrap()
|
||||||
multikMath.mathEx.sin(arg.asMultik().array).wrap()
|
|
||||||
|
|
||||||
override fun cos(arg: StructureND<Double>): MultikTensor<Double> =
|
override fun cos(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.cos(arg.asMultik().array).wrap()
|
||||||
multikMath.mathEx.cos(arg.asMultik().array).wrap()
|
|
||||||
|
|
||||||
override fun tan(arg: StructureND<Double>): MultikTensor<Double> = sin(arg) / cos(arg)
|
override fun tan(arg: StructureND<Double>): MultikTensor<Double> = sin(arg) / cos(arg)
|
||||||
|
|
||||||
@ -39,8 +37,7 @@ public class MultikDoubleAlgebra(
|
|||||||
@PerformancePitfall
|
@PerformancePitfall
|
||||||
override fun atan(arg: StructureND<Double>): MultikTensor<Double> = arg.map { atan(it) }
|
override fun atan(arg: StructureND<Double>): MultikTensor<Double> = arg.map { atan(it) }
|
||||||
|
|
||||||
override fun exp(arg: StructureND<Double>): MultikTensor<Double> =
|
override fun exp(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.exp(arg.asMultik().array).wrap()
|
||||||
multikMath.mathEx.exp(arg.asMultik().array).wrap()
|
|
||||||
|
|
||||||
override fun ln(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.log(arg.asMultik().array).wrap()
|
override fun ln(arg: StructureND<Double>): MultikTensor<Double> = multikMath.mathEx.log(arg.asMultik().array).wrap()
|
||||||
|
|
||||||
|
@ -12,7 +12,7 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType
|
|||||||
import space.kscience.kmath.operations.Float32Field
|
import space.kscience.kmath.operations.Float32Field
|
||||||
|
|
||||||
public class MultikFloatAlgebra(
|
public class MultikFloatAlgebra(
|
||||||
multikEngine: Engine,
|
multikEngine: Engine
|
||||||
) : MultikDivisionTensorAlgebra<Float, Float32Field>(multikEngine) {
|
) : MultikDivisionTensorAlgebra<Float, Float32Field>(multikEngine) {
|
||||||
override val elementAlgebra: Float32Field get() = Float32Field
|
override val elementAlgebra: Float32Field get() = Float32Field
|
||||||
override val dataType: DataType get() = DataType.FloatDataType
|
override val dataType: DataType get() = DataType.FloatDataType
|
||||||
|
@ -12,7 +12,7 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType
|
|||||||
import space.kscience.kmath.operations.Int32Ring
|
import space.kscience.kmath.operations.Int32Ring
|
||||||
|
|
||||||
public class MultikIntAlgebra(
|
public class MultikIntAlgebra(
|
||||||
multikEngine: Engine,
|
multikEngine: Engine
|
||||||
) : MultikTensorAlgebra<Int, Int32Ring>(multikEngine) {
|
) : MultikTensorAlgebra<Int, Int32Ring>(multikEngine) {
|
||||||
override val elementAlgebra: Int32Ring get() = Int32Ring
|
override val elementAlgebra: Int32Ring get() = Int32Ring
|
||||||
override val dataType: DataType get() = DataType.IntDataType
|
override val dataType: DataType get() = DataType.IntDataType
|
||||||
|
@ -12,7 +12,7 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType
|
|||||||
import space.kscience.kmath.operations.Int64Ring
|
import space.kscience.kmath.operations.Int64Ring
|
||||||
|
|
||||||
public class MultikLongAlgebra(
|
public class MultikLongAlgebra(
|
||||||
multikEngine: Engine,
|
multikEngine: Engine
|
||||||
) : MultikTensorAlgebra<Long, Int64Ring>(multikEngine) {
|
) : MultikTensorAlgebra<Long, Int64Ring>(multikEngine) {
|
||||||
override val elementAlgebra: Int64Ring get() = Int64Ring
|
override val elementAlgebra: Int64Ring get() = Int64Ring
|
||||||
override val dataType: DataType get() = DataType.LongDataType
|
override val dataType: DataType get() = DataType.LongDataType
|
||||||
|
@ -12,7 +12,7 @@ import org.jetbrains.kotlinx.multik.ndarray.data.DataType
|
|||||||
import space.kscience.kmath.operations.Int16Ring
|
import space.kscience.kmath.operations.Int16Ring
|
||||||
|
|
||||||
public class MultikShortAlgebra(
|
public class MultikShortAlgebra(
|
||||||
multikEngine: Engine,
|
multikEngine: Engine
|
||||||
) : MultikTensorAlgebra<Short, Int16Ring>(multikEngine) {
|
) : MultikTensorAlgebra<Short, Int16Ring>(multikEngine) {
|
||||||
override val elementAlgebra: Int16Ring get() = Int16Ring
|
override val elementAlgebra: Int16Ring get() = Int16Ring
|
||||||
override val dataType: DataType get() = DataType.ShortDataType
|
override val dataType: DataType get() = DataType.ShortDataType
|
||||||
|
@ -251,12 +251,7 @@ public abstract class MultikTensorAlgebra<T, A : Ring<T>>(
|
|||||||
TODO("Not implemented for broadcasting")
|
TODO("Not implemented for broadcasting")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun diagonalEmbedding(
|
override fun diagonalEmbedding(diagonalEntries: StructureND<T>, offset: Int, dim1: Int, dim2: Int): MultikTensor<T> {
|
||||||
diagonalEntries: StructureND<T>,
|
|
||||||
offset: Int,
|
|
||||||
dim1: Int,
|
|
||||||
dim2: Int,
|
|
||||||
): MultikTensor<T> {
|
|
||||||
|
|
||||||
TODO("Diagonal embedding not implemented")
|
TODO("Diagonal embedding not implemented")
|
||||||
}
|
}
|
||||||
|
@ -6,12 +6,12 @@ ND4J based implementations of KMath abstractions.
|
|||||||
- [nd4jarrayrings](#) : Rings over Nd4jArrayStructure of Int and Long
|
- [nd4jarrayrings](#) : Rings over Nd4jArrayStructure of Int and Long
|
||||||
- [nd4jarrayfields](#) : Fields over Nd4jArrayStructure of Float and Double
|
- [nd4jarrayfields](#) : Fields over Nd4jArrayStructure of Float and Double
|
||||||
|
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
|
|
||||||
The Maven coordinates of this project are `space.kscience:kmath-nd4j:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-nd4j:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
@ -225,8 +225,7 @@ public open class DoubleNd4jArrayFieldOps : Nd4jArrayExtendedFieldOps<Double, Fl
|
|||||||
|
|
||||||
public val Float64Field.nd4j: DoubleNd4jArrayFieldOps get() = DoubleNd4jArrayFieldOps
|
public val Float64Field.nd4j: DoubleNd4jArrayFieldOps get() = DoubleNd4jArrayFieldOps
|
||||||
|
|
||||||
public class DoubleNd4jArrayField(override val shape: ShapeND) : DoubleNd4jArrayFieldOps(),
|
public class DoubleNd4jArrayField(override val shape: ShapeND) : DoubleNd4jArrayFieldOps(), FieldND<Double, Float64Field>
|
||||||
FieldND<Double, Float64Field>
|
|
||||||
|
|
||||||
public fun Float64Field.nd4j(shapeFirst: Int, vararg shapeRest: Int): DoubleNd4jArrayField =
|
public fun Float64Field.nd4j(shapeFirst: Int, vararg shapeRest: Int): DoubleNd4jArrayField =
|
||||||
DoubleNd4jArrayField(ShapeND(shapeFirst, * shapeRest))
|
DoubleNd4jArrayField(ShapeND(shapeFirst, * shapeRest))
|
||||||
|
@ -144,9 +144,7 @@ public sealed interface Nd4jTensorAlgebra<T : Number, A : Field<T>> : AnalyticTe
|
|||||||
override fun atanh(arg: StructureND<T>): Nd4jArrayStructure<T> = Transforms.atanh(arg.ndArray).wrap()
|
override fun atanh(arg: StructureND<T>): Nd4jArrayStructure<T> = Transforms.atanh(arg.ndArray).wrap()
|
||||||
override fun power(arg: StructureND<T>, pow: Number): StructureND<T> = Transforms.pow(arg.ndArray, pow).wrap()
|
override fun power(arg: StructureND<T>, pow: Number): StructureND<T> = Transforms.pow(arg.ndArray, pow).wrap()
|
||||||
override fun ceil(arg: StructureND<T>): Nd4jArrayStructure<T> = Transforms.ceil(arg.ndArray).wrap()
|
override fun ceil(arg: StructureND<T>): Nd4jArrayStructure<T> = Transforms.ceil(arg.ndArray).wrap()
|
||||||
override fun floor(structureND: StructureND<T>): Nd4jArrayStructure<T> =
|
override fun floor(structureND: StructureND<T>): Nd4jArrayStructure<T> = Transforms.floor(structureND.ndArray).wrap()
|
||||||
Transforms.floor(structureND.ndArray).wrap()
|
|
||||||
|
|
||||||
override fun std(structureND: StructureND<T>, dim: Int, keepDim: Boolean): Tensor<T> =
|
override fun std(structureND: StructureND<T>, dim: Int, keepDim: Boolean): Tensor<T> =
|
||||||
structureND.ndArray.std(true, keepDim, dim).wrap()
|
structureND.ndArray.std(true, keepDim, dim).wrap()
|
||||||
|
|
||||||
@ -180,10 +178,7 @@ public object DoubleNd4jTensorAlgebra : Nd4jTensorAlgebra<Double, Float64Field>
|
|||||||
override fun INDArray.wrap(): Nd4jArrayStructure<Double> = asDoubleStructure()
|
override fun INDArray.wrap(): Nd4jArrayStructure<Double> = asDoubleStructure()
|
||||||
|
|
||||||
@OptIn(UnsafeKMathAPI::class)
|
@OptIn(UnsafeKMathAPI::class)
|
||||||
override fun mutableStructureND(
|
override fun mutableStructureND(shape: ShapeND, initializer: Float64Field.(IntArray) -> Double): Nd4jArrayStructure<Double> {
|
||||||
shape: ShapeND,
|
|
||||||
initializer: Float64Field.(IntArray) -> Double,
|
|
||||||
): Nd4jArrayStructure<Double> {
|
|
||||||
val array: INDArray = Nd4j.zeros(*shape.asArray())
|
val array: INDArray = Nd4j.zeros(*shape.asArray())
|
||||||
val indices = ColumnStrides(shape)
|
val indices = ColumnStrides(shape)
|
||||||
indices.asSequence().forEach { index ->
|
indices.asSequence().forEach { index ->
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# Module kmath-optimization
|
# Module kmath-optimization
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
## Artifact:
|
## Artifact:
|
||||||
@ -7,7 +9,6 @@
|
|||||||
The Maven coordinates of this project are `space.kscience:kmath-optimization:0.4.0-dev-3`.
|
The Maven coordinates of this project are `space.kscience:kmath-optimization:0.4.0-dev-3`.
|
||||||
|
|
||||||
**Gradle Kotlin DSL:**
|
**Gradle Kotlin DSL:**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
maven("https://repo.kotlin.link")
|
maven("https://repo.kotlin.link")
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user