All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonTest.space.kscience.kmath.structures.NumberNDFieldTest.kt Maven / Gradle / Ivy

package space.kscience.kmath.structures

import space.kscience.kmath.nd.*
import space.kscience.kmath.operations.Norm
import space.kscience.kmath.operations.invoke
import kotlin.math.abs
import kotlin.math.pow
import kotlin.test.Test
import kotlin.test.assertEquals

@Suppress("UNUSED_VARIABLE")
class NumberNDFieldTest {
    val algebra = NDAlgebra.real(3,3)
    val array1 = algebra.produce { (i, j) -> (i + j).toDouble() }
    val array2 = algebra.produce { (i, j) -> (i - j).toDouble() }

    @Test
    fun testSum() {
        algebra {
            val sum = array1 + array2
            assertEquals(4.0, sum[2, 2])
        }
    }

    @Test
    fun testProduct() {
        algebra {
            val product = array1 * array2
            assertEquals(0.0, product[2, 2])
        }
    }

    @Test
    fun testGeneration() {

        val array = Structure2D.real(3, 3) { i, j -> (i * 10 + j).toDouble() }

        for (i in 0..2) {
            for (j in 0..2) {
                val expected = (i * 10 + j).toDouble()
                assertEquals(expected, array[i, j], "Error at index [$i, $j]")
            }
        }
    }

    @Test
    fun testExternalFunction() {
        algebra {
            val function: (Double) -> Double = { x -> x.pow(2) + 2 * x + 1 }
            val result = function(array1) + 1.0
            assertEquals(10.0, result[1, 1])
        }
    }

    @Test
    fun testLibraryFunction() {
        algebra {
            val abs: (Double) -> Double = ::abs
            val result = abs(array2)
            assertEquals(2.0, result[0, 2])
        }
    }

    @Test
    fun combineTest() {
        val division = array1.combine(array2, Double::div)
    }

    object L2Norm : Norm, Double> {
        override fun norm(arg: NDStructure): Double =
            kotlin.math.sqrt(arg.elements().sumByDouble { it.second.toDouble() })
    }

    @Test
    fun testInternalContext() {
        algebra {
            (NDAlgebra.real(*array1.shape)) { with(L2Norm) { 1 + norm(array1) + exp(array2) } }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy