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

commonMain.space.kscience.kmath.expressions.SymbolIndexer.kt Maven / Gradle / Ivy

package space.kscience.kmath.expressions

import space.kscience.kmath.linear.Point
import space.kscience.kmath.nd.Structure2D
import space.kscience.kmath.structures.BufferFactory

/**
 * An environment to easy transform indexed variables to symbols and back.
 * TODO requires multi-receivers to be beautiful
 */
public interface SymbolIndexer {
    public val symbols: List
    public fun indexOf(symbol: Symbol): Int = symbols.indexOf(symbol)

    public operator fun  List.get(symbol: Symbol): T {
        require(size == symbols.size) { "The input list size for indexer should be ${symbols.size} but $size found" }
        return get([email protected](symbol))
    }

    public operator fun  Array.get(symbol: Symbol): T {
        require(size == symbols.size) { "The input array size for indexer should be ${symbols.size} but $size found" }
        return get([email protected](symbol))
    }

    public operator fun DoubleArray.get(symbol: Symbol): Double {
        require(size == symbols.size) { "The input array size for indexer should be ${symbols.size} but $size found" }
        return get([email protected](symbol))
    }

    public operator fun  Point.get(symbol: Symbol): T {
        require(size == symbols.size) { "The input buffer size for indexer should be ${symbols.size} but $size found" }
        return get([email protected](symbol))
    }

    public fun DoubleArray.toMap(): Map {
        require(size == symbols.size) { "The input array size for indexer should be ${symbols.size} but $size found" }
        return symbols.indices.associate { symbols[it] to get(it) }
    }

    public operator fun  Structure2D.get(rowSymbol: Symbol, columnSymbol: Symbol): T =
        get(indexOf(rowSymbol), indexOf(columnSymbol))


    public fun  Map.toList(): List = symbols.map { getValue(it) }

    public fun  Map.toPoint(bufferFactory: BufferFactory): Point =
        bufferFactory(symbols.size) { getValue(symbols[it]) }

    public fun Map.toDoubleArray(): DoubleArray = DoubleArray(symbols.size) { getValue(symbols[it]) }
}

public inline class SimpleSymbolIndexer(override val symbols: List) : SymbolIndexer

/**
 * Execute the block with symbol indexer based on given symbol order
 */
public inline fun  withSymbols(vararg symbols: Symbol, block: SymbolIndexer.() -> R): R =
    with(SimpleSymbolIndexer(symbols.toList()), block)

public inline fun  withSymbols(symbols: Collection, block: SymbolIndexer.() -> R): R =
    with(SimpleSymbolIndexer(symbols.toList()), block)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy