### Gradle Dependency Configuration Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/templates/ARTIFACT-TEMPLATE.md This snippet shows how to configure your Gradle build to include the kmath project as a dependency. It specifies the necessary repositories and the implementation dependency line. ```Kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("${group}:${name}:${version}") } ``` -------------------------------- ### ListPolynomial Initialization Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/polynomials.md Demonstrates how to initialize a `ListPolynomial` in Kotlin, representing a polynomial as a list of coefficients. The coefficients correspond to powers of the variable, starting from the constant term. ```kotlin val polynomial: ListPolynomial = ListPolynomial(listOf(2, -3, 1)) ``` ```kotlin val polynomial: ListPolynomial = ListPolynomial(2, -3, 1) ``` -------------------------------- ### Render kmath Expression to LaTeX and MathML Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Provides an example of using the kmath-ast library to parse a mathematical expression string and render it into both LaTeX and MathML formats. This enables displaying complex formulas in various contexts. ```kotlin import space.kscience.kmath.ast.* import space.kscience.kmath.ast.rendering.* import space.kscience.kmath.misc.* @OptIn(UnstableKMathAPI::class) public fun main() { val mst = "exp(sqrt(x))-asin(2*x)/(2e10+x^3)/(12)+x^(2/3)".parseMath() val syntax = FeaturedMathRendererWithPostProcess.Default.render(mst) val latex = LatexSyntaxRenderer.renderWithStringBuilder(syntax) println("LaTeX:") println(latex) println() val mathML = MathMLSyntaxRenderer.renderWithStringBuilder(syntax) println("MathML:") println(mathML) } ``` ```html exp x - arcsin 2 x 2 × 10 10 + x 3 12 + x 2 / 3 ``` -------------------------------- ### KMath Maven Repository and Dependencies Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/templates/README-TEMPLATE.md Configures the Maven repository for kmath artifacts and declares core kmath dependencies. This setup is essential for integrating kmath into JVM projects. ```kotlin repositories { maven("https://repo.kotlin.link") } dependencies { api("${group}:kmath-core:$version") // api("${group}:kmath-core-jvm:$version") for jvm-specific version } ``` -------------------------------- ### Optimize Weights using Apache Commons Math Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Utilizes the `SimplexOptimizer` from Apache Commons Math to find optimal weights for the `ConvolutionalXYStatistic`. The optimizer minimizes the defined `lossFunction` starting from an initial guess. ```kotlin import org.apache.commons.math3.optim.* import org.apache.commons.math3.optim.nonlinear.scalar.* import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.* val optimizer = SimplexOptimizer(1e-1, Double.MAX_VALUE) val result = optimizer.optimize( ObjectiveFunction { point -> lossFunction(ConvolutionalXYStatistic(point)) }, NelderMeadSimplex(xValues.size), InitialGuess(DoubleArray(xValues.size){ 1.0 }), GoalType.MINIMIZE, MaxEval(100000) ) ``` -------------------------------- ### Perform Algebraic Operations on LabeledPolynomials Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/polynomials.md Demonstrates algebraic operations, including addition and equality checks, on LabeledPolynomial objects within their corresponding space. The example verifies the result of the computation. ```kotlin val computationResult = Int.algebra.labeledPolynomialSpace { LabeledPolynomial( listOf() to 3, listOf(0u, 1u) to 5, listOf(2u, 0u, 1u) to -7, ) + LabeledPolynomial( listOf(0u, 1u) to -5, listOf(0u, 0u, 0u, 4u) to 4, ) == LabeledPolynomial( listOf() to 3, listOf(0u, 1u) to 0, listOf(2u, 0u, 1u) to -7, listOf(0u, 0u, 0u, 4u) to 4, ) } println(computationResult) // true ``` -------------------------------- ### Generated JVM Bytecode Example (Java) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Presents a decompiled view of the JVM bytecode generated by the kmath-ast compiler for a mathematical expression. This class implements the `Expression` interface, showing the structure of the compiled code. ```java import java.util.*; import kotlin.jvm.functions.*; import space.kscience.kmath.asm.internal.*; import space.kscience.kmath.complex.*; import space.kscience.kmath.expressions.*; public final class CompiledExpression_45045_0 implements Expression { private final Object[] constants; public Complex invoke(Map arguments) { Complex var2 = (Complex)MapIntrinsics.getOrFail(arguments, "x"); return (Complex)((Function2)this.constants[0]).invoke(var2, (Complex)this.constants[1]); } } ``` -------------------------------- ### Add kmath Dependency Source: https://github.com/sciprogcentre/kmath/blob/dev/README.md Instructions on how to add the kmath library to your project by configuring Maven repositories and specifying the dependency. It includes the primary repository URL and an example dependency declaration. ```kotlin repositories { maven("https://repo.kotlin.link") } dependencies { api("space.kscience:kmath-core:$version") // api("space.kscience:kmath-core-jvm:$version") for jvm-specific version } ``` -------------------------------- ### Create Default Statistic and Apply Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Initializes a `ConvolutionalXYStatistic` with uniform weights and applies it to a generated `XYValues` dataset. This showcases the usage of the statistic object. ```kotlin val statistic = ConvolutionalXYStatistic(DoubleArray(xValues.size){1.0}) statistic(xy) ``` -------------------------------- ### Display Resulting Optimization Weights Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Prints the optimized weights found by the `SimplexOptimizer`. These weights are stored in the `result.point` property. ```kotlin result.point ``` -------------------------------- ### KMath Linear Algebra Operations Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/linear.md Demonstrates basic linear algebra operations in KMath using the `LinearSpace` context for real numbers. It shows vector and matrix creation, addition, scalar multiplication, and dot products. Requires import of `space.kscience.kmath.linear`. ```Kotlin import space.kscience.kmath.linear.*; LinearSpace.Companion.real { val vec = buildVector(10) { i -> i.toDouble() } val mat = buildMatrix(10, 10) { i, j -> i.toDouble() + j } // Addition vec + vec mat + mat // Multiplication by scalar vec * 2.0 mat * 2.0 // Dot product mat dot vec mat dot mat } ``` -------------------------------- ### Define Loss Function for Optimization Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Defines a loss function that calculates the negative absolute difference between the sum of statistics for parabolas and hyperbolas. This function is used to guide the optimization process. ```kotlin val lossFunction: (XYStatistic) -> Double = { statistic -> - abs(parabolas.sumOf { statistic(it) } - hyperbolas.sumOf { statistic(it) }) } ``` -------------------------------- ### Compile Expression to JVM Bytecode (Kotlin) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Demonstrates how to parse a human-readable mathematical expression string and compile it into an executable `Expression` object using the kmath-ast library. This process generates optimized JVM bytecode for runtime execution. ```kotlin import space.kscience.kmath.asm.compileToExpression import space.kscience.kmath.operations.DoubleField "x^3-x+3".parseMath().compileToExpression(DoubleField) ``` -------------------------------- ### NDStructure Wrapper for INDArray Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-nd4j/README.md Demonstrates creating an NDStructure wrapper for an INDArray using ND4J. It shows how to initialize an array and access/modify its elements. ```kotlin import org.nd4j.linalg.factory.* import scientifik.kmath.nd4j.* import scientifik.kmath.structures.* val array = Nd4j.ones(2, 2).asDoubleStructure() println(array[0, 0]) // 1.0 array[intArrayOf(0, 0)] = 24.0 println(array[0, 0]) // 24.0 ``` -------------------------------- ### Compile Kotlin Expression to WebAssembly IR Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/docs/README-TEMPLATE.md Illustrates compiling mathematical expressions into WebAssembly (Wasm) Intermediate Representation (IR) for optimized execution, currently supporting `DoubleField` and `IntRing`. ```kotlin import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.* import space.kscience.kmath.operations.* import space.kscience.kmath.wasm.* MstField { x + 2 }.compileToExpression(DoubleField) ``` ```wat (func $executable (param $0 f64) (result f64) (f64.add (local.get $0) (f64.const 2) ) ) ``` -------------------------------- ### Render Math Expressions to LaTeX and MathML in Kotlin Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/docs/README-TEMPLATE.md Demonstrates parsing a mathematical expression string and rendering it into both LaTeX and MathML formats using the kmath-ast library. It utilizes `FeaturedMathRendererWithPostProcess` and specific renderers for output. ```kotlin import space.kscience.kmath.ast.* import space.kscience.kmath.ast.rendering.* import space.kscience.kmath.misc.* @OptIn(UnstableKMathAPI::class) public fun main() { val mst = "exp(sqrt(x))-asin(2*x)/(2e10+x^3)/(12)+x^(2/3)".parseMath() val syntax = FeaturedMathRendererWithPostProcess.Default.render(mst) val latex = LatexSyntaxRenderer.renderWithStringBuilder(syntax) println("LaTeX:") println(latex) println() val mathML = MathMLSyntaxRenderer.renderWithStringBuilder(syntax) println("MathML:") println(mathML) } ``` -------------------------------- ### Complex Number Operations with ComplexField Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/algebra.md Shows how to use the `ComplexField` context for performing operations on complex numbers. It illustrates direct addition and using the context builder syntax for operations. ```kotlin import space.kscience.kmath.operations.* val c1 = Complex(1.0, 2.0) val c2 = ComplexField.i val c3 = c1 + c2 // or val c3 = ComplexField { c1 + c2 } ``` -------------------------------- ### Java Process Configuration Source: https://github.com/sciprogcentre/kmath/blob/dev/benchmarks/README.md Configuration details for the Java Virtual Machine used during benchmark execution. This specifies the Java runtime and system properties like file encoding and user locale. ```java C:\\Users\\altavir\\scoop\\apps\\gradle\\current\\.gradle\\jdks\\eclipse_adoptium-17-amd64-windows.2\\bin\\java.exe -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant ``` -------------------------------- ### Import Specific Operations in Kotlin Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/contexts.md Illustrates how to import specific operations from different contexts to avoid operator ambiguity when multiple scoped contexts define the same operation. This allows selective use of functionality. ```kotlin import context.complex.op1 import context.quaternion.op2 ``` -------------------------------- ### Compile Kotlin Expression to WebAssembly IR (WAT) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Shows how to compile kmath expressions for JavaScript environments using WebAssembly (Wasm) IR generation. This is an experimental feature supporting DoubleField and IntRing expressions. ```kotlin import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.* import space.kscience.kmath.operations.* import space.kscience.kmath.wasm.* MstField { x + 2 }.compileToExpression(DoubleField) ``` ```wat (func $executable (param $0 f64) (result f64) (f64.add (local.get $0) (f64.const 2) ) ) ``` -------------------------------- ### Add kmath-nd4j Dependency (Gradle) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-nd4j/README.md Shows how to add the kmath-nd4j artifact to your project using the Gradle Kotlin DSL. It includes repository configurations and the dependency declaration. ```gradle repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-nd4j:0.4.2") } ``` -------------------------------- ### Add kmath-ojalgo Dependency to Gradle Project Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ojalgo/README.md This snippet demonstrates how to include the kmath-ojalgo library in a Gradle project using Kotlin DSL. It specifies the necessary repositories and the implementation dependency for version 0.4.2. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-ojalgo:0.4.2") } ``` -------------------------------- ### Gradle Kotlin DSL Dependency Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-optimization/README.md Adds the kmath-optimization library to a Kotlin project using Gradle. It specifies the necessary Maven repositories and the dependency coordinates for version 0.4.2. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-optimization:0.4.2") } ``` -------------------------------- ### Generate Parabola and Hyperbola Data Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Provides functions to generate sample data points for mathematical functions. `generateParabolas` creates data for y = ax^2 + bx + c, and `generateHyperbols` creates data for y = gamma / (x - x0) + y0. ```kotlin fun generateParabolas(xValues: DoubleArray, a: Double, b: Double, c: Double): XYValues { val yValues = xValues.map { x -> a * x * x + b * x + c }.toDoubleArray() return XYValues(xValues, yValues) } fun generateHyperbols(xValues: DoubleArray, gamma: Double, x0: Double, y0: Double): XYValues { val yValues = xValues.map { x -> y0 + gamma / (x - x0) }.toDoubleArray() return XYValues(xValues, yValues) } ``` -------------------------------- ### Add kmath-ast Dependency (Gradle Kotlin DSL) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Specifies how to include the kmath-ast library in your project using Gradle's Kotlin DSL. It lists the necessary Maven repositories and the dependency declaration. ```gradle repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-ast:0.4.2") } ``` -------------------------------- ### Gradle Kotlin DSL Dependency Configuration Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-core/README.md Configures Maven repositories and adds the kmath-core library as a project dependency using the Gradle Kotlin DSL. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-core:0.4.2") } ``` -------------------------------- ### Basic Operation in Group Context Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/algebra.md Demonstrates how to perform a basic operation, such as addition, within a specified algebraic context (Group). This highlights KMath's design where operations are drawn from a context associated with the data types. ```kotlin import space.kscience.kmath.operations.* val a: T = ... val b: T = ... val group: Group = ... val c = group { a + b } ``` -------------------------------- ### Add kmath-for-real Dependency (Gradle Kotlin DSL) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-for-real/README.md This snippet shows how to add the `kmath-for-real` library as a dependency in a Gradle project using Kotlin DSL. It includes configuring Maven repositories and specifying the dependency coordinates for version 0.4.2. ```gradle repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-for-real:0.4.2") } ``` -------------------------------- ### Plotting Generated Data with Plotly Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Demonstrates how to generate hyperbolic data using `generateHyperbols` and plot it using the Plotly library. It sets up x and y data and configures a scatter plot. ```kotlin val xValues = (1.0..10.0).step(1.0).toDoubleArray() val xy = generateHyperbols(xValues, 1.0, 0.0, 0.0) Plotly.plot { scatter { this.x.doubles = xValues this.y.doubles = xy.yValues } } ``` -------------------------------- ### Add kmath-kotlingrad Dependency (Gradle Kotlin DSL) Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-kotlingrad/README.md Demonstrates how to include the kmath-kotlingrad module in your project using Gradle's Kotlin DSL. It specifies the necessary repositories and the implementation dependency. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-kotlingrad:0.4.2") } ``` -------------------------------- ### Kotlin Property Getter One-liner Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/codestyle.md Demonstrates the convention of using a concise one-liner for Kotlin properties with getters, improving readability for simple calculations. ```Kotlin val b: String get() = "fff" ``` -------------------------------- ### MathML Output for Mathematical Expressions Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/docs/README-TEMPLATE.md Presents the MathML representation of a parsed mathematical expression, suitable for rendering in web browsers or other platforms that support the MathML standard. ```html exp x - arcsin 2 x 2 × 10 10 + x 3 12 + x 2 / 3 ``` -------------------------------- ### Gradle Kotlin DSL Dependency Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-coroutines/README.md Adds the kmath-coroutines library to a Kotlin project using Gradle. Specifies Maven coordinates for dependency resolution. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-coroutines:0.4.2") } ``` -------------------------------- ### Generate Large Datasets of Parabolas and Hyperbolas Source: https://github.com/sciprogcentre/kmath/blob/dev/examples/notebooks/Naive classifier.ipynb Generates 500 samples each of parabolic and hyperbolic data using random parameters. This data is intended for statistical analysis and comparison. ```kotlin import kotlin.random.Random val random = Random(1288) val parabolas = buildList{ repeat(500){ add( generateParabolas( xValues, random.nextDouble(), random.nextDouble(), random.nextDouble() ) ) } } val hyperbolas: List = buildList{ repeat(500){ add( generateHyperbols( xValues, random.nextDouble()*10, random.nextDouble(), random.nextDouble() ) ) } } ``` -------------------------------- ### Compile Kotlin Expression to JVM Bytecode Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/docs/README-TEMPLATE.md Demonstrates compiling a mathematical expression string into a Java Expression object on the JVM. This process generates bytecode for efficient execution, supporting various numeric fields like DoubleField. ```kotlin import space.kscience.kmath.asm.compileToExpression import space.kscience.kmath.operations.DoubleField "x^3-x+3".parseMath().compileToExpression(DoubleField) ``` ```java import java.util.*; import kotlin.jvm.functions.*; import space.kscience.kmath.asm.internal.*; import space.kscience.kmath.complex.*; import space.kscience.kmath.expressions.*; public final class CompiledExpression_45045_0 implements Expression { private final Object[] constants; public Complex invoke(Map arguments) { Complex var2 = (Complex)MapIntrinsics.getOrFail(arguments, "x"); return (Complex)((Function2)this.constants[0]).invoke(var2, (Complex)this.constants[1]); } } ``` ```java import java.util.*; import space.kscience.kmath.asm.internal.*; import space.kscience.kmath.expressions.*; public final class CompiledExpression_-386104628_0 implements DoubleExpression { private final SymbolIndexer indexer; public SymbolIndexer getIndexer() { return this.indexer; } public double invoke(double[] arguments) { double var2 = arguments[0]; return Math.pow(var2, 3.0D) - var2 + 3.0D; } public final Double invoke(Map arguments) { double var2 = ((Double)MapIntrinsics.getOrFail(arguments, "x")).doubleValue(); return Math.pow(var2, 3.0D) - var2 + 3.0D; } } ``` -------------------------------- ### KMath AST to JVM Bytecode Compiler Source: https://github.com/sciprogcentre/kmath/blob/dev/README.md This snippet details the dynamic MST (Mathematical Syntax Tree) to JVM bytecode compiler within the kmath-ast module. It enables the execution of parsed expressions on the JVM. ```java package space.kscience.kmath.asm; import org.objectweb.asm.*; import space.kscience.kmath.ast.ExpressionNode; // Simplified example of generating JVM bytecode from an ExpressionNode public class JvmExpressionCompiler { public void compile(ExpressionNode node, ClassWriter cw) { // Example: Compiling a simple literal if (node instanceof Literal) { Object value = ((Literal) node).getValue(); // Generate code to push the value onto the stack // For example, if value is an Integer: // cw.visitLdc(new Integer((Integer) value)); } else if (node instanceof BinaryOperation) { // Recursively compile left and right operands // Then generate bytecode for the specific operation (e.g., IADD, IMUL) } // ... other node types ... } // Method to create a runnable class from an AST public byte[] createRunnableClass(ExpressionNode expression) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "GeneratedExpression", null, "java/lang/Object", null); // Create a method, e.g., 'evaluate' MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "evaluate", "()D", null, null); mv.visitCode(); // Compile the expression node into the method body compile(expression, cw); // Example: Assume the result is a double, return it mv.visitInsn(Opcodes.DRETURN); mv.visitMaxs(1, 1); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } } ``` -------------------------------- ### Compile Kotlin Expression to JavaScript Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-ast/README.md Demonstrates compiling a kmath expression defined in Kotlin to an executable JavaScript function. This allows for expression evaluation in JavaScript environments. ```kotlin import space.kscience.kmath.expressions.Symbol.Companion.x import space.kscience.kmath.expressions.* import space.kscience.kmath.operations.* import space.kscience.kmath.estree.* MstField { x + 2 }.compileToExpression(DoubleField) ``` ```javascript var executable = function (constants, arguments) { return constants[1](constants[0](arguments, "x"), 2); }; ``` -------------------------------- ### Add kmath-histograms to Gradle Project Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-histograms/README.md This snippet demonstrates how to add the kmath-histograms library to your project using Gradle with Kotlin DSL. It includes the necessary repository configurations and the dependency declaration for version 0.4.2. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-histograms:0.4.2") } ``` -------------------------------- ### kmath NDField Context Definitions Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/nd-structure.md Demonstrates the creation of different n-dimensional field contexts in kmath. These include an automatically inferred context, a specialized real number context, and a generic buffered context for objects. ```kotlin // automatically build context most suited for given type. val autoField = NDField.auto(DoubleField, dim, dim) // specialized nd-field for Double. It works as generic Double field as well. val specializedField = NDField.real(dim, dim) //A generic boxing field. It should be used for objects, not primitives. val genericField = NDField.buffered(DoubleField, dim, dim) ``` -------------------------------- ### Add kmath-multik Dependency to Gradle Kotlin DSL Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-multik/README.md Shows how to add the kmath-multik artifact to a Gradle Kotlin DSL project. It includes the necessary repository configurations and the dependency declaration. ```kotlin repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-multik:0.4.2") } ``` -------------------------------- ### ListPolynomial Arithmetic Operations Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/polynomials.md Shows how to perform arithmetic operations on `ListPolynomial` objects within a `ListPolynomialSpace` context. This allows for algebraic manipulation of polynomials. ```kotlin val computationResult = Int.algebra.listPolynomialSpace { ListPolynomial(2, -3, 1) + ListPolynomial(0, 6) == ListPolynomial(2, 3, 1) } println(computationResult) // true ``` -------------------------------- ### Creating Nested Algebraic Structures (NDElement) Source: https://github.com/sciprogcentre/kmath/blob/dev/docs/algebra.md Demonstrates the creation of a multi-dimensional element (NDElement) where each element within the structure is a complex number. This showcases how KMath allows building complex algebraic structures by providing fields for their constituent elements. ```kotlin val element = NDElement.complex(shape = intArrayOf(2, 2)) { index: IntArray -> Complex(index[0].toDouble() - index[1].toDouble(), index[0].toDouble() + index[1].toDouble()) } ``` -------------------------------- ### KMath AST Extendable Math Rendering Source: https://github.com/sciprogcentre/kmath/blob/dev/README.md This snippet pertains to the extendable MST rendering feature within the kmath-ast module. It defines a base interface for rendering mathematical expressions into various formats, such as LaTeX or MathML. ```kotlin package space.kscience.kmath.ast.rendering import space.kscience.kmath.ast.ExpressionNode /** * Interface for rendering mathematical expression trees into different formats. */ interface MathRenderer { /** * Renders a literal node. * @param node The literal node to render. * @return The rendered string. */ fun renderLiteral(node: Literal): T /** * Renders a binary operation node. * @param node The binary operation node to render. * @return The rendered string. */ fun renderBinaryOperation(node: BinaryOperation): T /** * Renders a function call node. * @param node The function call node to render. * @return The rendered string. */ fun renderFunctionCall(node: FunctionCall): T /** * Renders an unknown node type. * @param node The unknown node to render. * @return The rendered string. */ fun renderUnknown(node: ExpressionNode): T /** * Combines rendered parts into a final output. * @param parts The list of rendered parts. * @return The combined rendered output. */ fun combine(parts: List): T } // Example: A renderer for plain text output class PlainTextRenderer : MathRenderer { override fun renderLiteral(node: Literal): String = node.value.toString() override fun renderBinaryOperation(node: BinaryOperation): String { val left = render(node.left) val right = render(node.right) return "($left ${node.operator} $right)" } override fun renderFunctionCall(node: FunctionCall): String { val args = node.arguments.joinToString(", ") { render(it) } return "${node.name}($args)" } override fun renderUnknown(node: ExpressionNode): String = "" override fun combine(parts: List): String = parts.joinToString(" ") // Helper to dispatch rendering based on node type private fun render(node: ExpressionNode): String = when (node) { is Literal -> renderLiteral(node) is BinaryOperation -> renderBinaryOperation(node) is FunctionCall -> renderFunctionCall(node) else -> renderUnknown(node) } } ``` -------------------------------- ### Add kmath-viktor Dependency Source: https://github.com/sciprogcentre/kmath/blob/dev/kmath-viktor/README.md This snippet shows how to add the kmath-viktor module as a dependency in a Gradle Kotlin DSL project. It includes repository configurations and the dependency declaration. ```gradle-kotlin-dsl repositories { maven("https://repo.kotlin.link") mavenCentral() } dependencies { implementation("space.kscience:kmath-viktor:0.4.2") } ```