SciProgCentre / kmath

Kotlin mathematics extensions library
650 stars 55 forks source link

Add PiecewiseBicubicSplineInterpolatingFunction #509

Open hondogo opened 1 year ago

hondogo commented 1 year ago

Please add function (for multiplatform) like org.apache.commons.math3.analysis.interpolation.PiecewiseBicubicSplineInterpolatingFunction.

Purpose: To be able to interpolate points for surface given by points matrix there is a need for such function.

Link to Slack thread with initial request intent

SPC-code commented 1 year ago

It would be best if you could clarify what use case do you have. What input and output data formats and what additional parameters do you have. It it is quite easy to replicate CM behavior. But maybe we could do better.

hondogo commented 1 year ago

Here is a peace of code that uses interpolation function (Apache Commons Math implementation):

import org.apache.commons.math3.analysis.interpolation.PiecewiseBicubicSplineInterpolatingFunction
import org.apache.commons.math3.exception.OutOfRangeException

class InterpolatingSurface(
    xPoints: DoubleArray,
    yPoints: DoubleArray,
    zPoints: Array<DoubleArray>
) : Surface {

    init {
        require(zPoints.size == xPoints.size)
        require(zPoints.all { it.size == yPoints.size })
    }

    private val interpolator = PiecewiseBicubicSplineInterpolatingFunction(
        /* x = */ xPoints,
        /* y = */ yPoints,
        /* f = */ zPoints
    )

    override fun z(x: Double, y: Double): Double {
        return try {
            interpolator.value(x, y)
        } catch (_: OutOfRangeException) {
            Double.NaN
        }
    }
}