kyonifer/koma

Add toXMatrix() / toXArray to each of the supported backends.

Opened this issue · 2 comments

toXMatrix(): XMatrix would be implemented in each of the backends where XMatrix is the matrix type that corresponds to the matrix type in the backend instead of getBaseMatrix(): Any in the api. I can't think of any situations where getBaseMatrix() is useful without a type check. toXMatrix() could also convert to the corresponding type if X wasn't the backing type of the koma matrix it is being called on. I guess there could also be both getBaseMatrix() and toXMatrix().

Here's what it could look like with ND4J (I know there is no nd4j backend at the moment but that's what I'm playing with so that's what I wrote the function for):

fun Matrix<Double>.toNd4jArray(): INDArray {
    getBaseMatrix().let { if(it is INDArray) return it }

    return Nd4j.create(toDoubleArray())
        .reshape(*shape().map { it.toLong() }.toLongArray())
}

In the case of this specific example Nd4j does not differentiate between a matrix and a ndarray so there would only need to be a function for ndarray but know all ndarrays in koma use custom implementation and not a backing ndarray at the moment so I just put this extension on koma Matrix.

Edit: And there might have to be some stuff done with generics instead of just having it for Double depending on the backend.

Yep that makes sense, definitely easier to use for a user who knows what type they want.