kyonifer / koma

A scientific computing library for Kotlin. https://kyonifer.github.io/koma
Other
270 stars 23 forks source link

Vectorized mathematical functions #101

Open SebastianCallh opened 5 years ago

SebastianCallh commented 5 years ago

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.

peastman commented 5 years ago

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.

SebastianCallh commented 5 years ago

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).