koma icon indicating copy to clipboard operation
koma copied to clipboard

Vectorized mathematical functions

Open SebastianCallh opened this issue 5 years ago • 2 comments

Hello!

I need to do some efficient number crunching and was looking into Koma. However, I have need to take the element-wise exponent and logarithm of arrays, which does not seem to be possible without mapping the elements as boxed values (please correct me if I am wrong).

I think it would be a relevant improvement to catch up feature-wise to other numerical libraries such as Numpy.

SebastianCallh avatar May 08 '19 18:05 SebastianCallh

That shouldn't be the case. It has versions of the math functions that are specialized for all relevant primitive types. For example, here's the version of exp() for an array of doubles (https://github.com/kyonifer/koma/blob/master/koma-core-api/common/src/koma/arrayfuncs.kt#L188-L193):

fun exp(arr: NDArray<Double>) =
    arr.map { kotlin.math.exp(it) }

map() is implemented as an extension function, not a method, which allows the return type to be specialized based on the array type. Here's the implementation for NDArray<Double> (https://github.com/kyonifer/koma/blob/master/koma-core-api/common/src/koma/extensions/extensions_ndarray_Double.kt#L74-L84):

inline fun <reified R> NDArray<Double>.map(crossinline f: (Double) -> R)
    = NDArray.createLinear(*shape().toIntArray(), filler={ f(this.getDouble(it)) } )

As a result, as long as the array's type is known at compile time, no boxing is needed.

peastman avatar May 09 '19 03:05 peastman

Thank you for your reply.

It seems I was mistaken then, which is good! However, I cannot find the arrayfuncs file in the official documentation, and only specialized functions for Matrix<T> (not NDArray<T>). IntelliJ does not find any imports other than the ones in the linked documentation either.

I installed Koma using the instructions on the main page (however I had to add another line to the gradle.build as described in #99).

SebastianCallh avatar May 09 '19 07:05 SebastianCallh