I guess this is going a bit overboard with overloa...
# kotlindl
p
I guess this is going a bit overboard with overloading operator functions 🙂 , but wanted to see if it is possible to imitate Numpy array access with NDArray, and actually not very hard at all.
Copy code
@file:Suppress("ConstantConditionIf")
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.indexing.NDArrayIndex

/**
 * Add stride syntax to int ranges: 0..100..2
 *
 * @param step
 * @return
 */
operator fun IntRange.rangeTo(step: Int) : IntProgression {
    return IntProgression.fromClosedRange(first, last, step)
}

/**
 * Simplify NDArray access: a[0..4, 16..32..2, END-10..END-5]
 *
 * @param indexes
 * @return
 */
operator fun INDArray.get(vararg indexes: IntProgression) : INDArray {
    var dimension = 0
    val intervals = indexes.map {
        val first = if (it.first < 0) size(dimension).toInt() + it.first + 1 else it.first
        val last = if (it.last < 0) size(dimension).toInt() + it.last + 1 else it.last
        dimension++
        NDArrayIndex.interval(first, it.step, last, false)!!
    }.toTypedArray()
    return get(*intervals)
}

// Small trick so the compiler doesn't infer empty ranges
val END = if (true) -1 else 1
PS I don't really use this, so might contain some bugs.
a
I think it is a wrong chat for that. Look into #mathematics. MultiK library does exactly numpy-like overloading and KMath has basic bindings for ND4J, we recently discussed just that.
р
your get function returns a copy or not? If that's numpy behaviour.
we implemented non copying slicing in kmath
more work is needed before we release that
but should happen in the coming couple of months
varargs caused us trouble on multiplatform actually so we decided to get a behaviour like
array[i][j][k]
etc. to subset each dimension
but that's also familiar to
numpy
users
p
Will keep an eye out for kmath, sounds interesting. BTW, in my sample snippet, the get shouldn't create a copy (at least according to some ND4J doc I read).
👍 1