diff --git a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorCasts.kt b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorCasts.kt index 814a1bb9b..921bcf97e 100644 --- a/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorCasts.kt +++ b/kmath-tensors/src/commonMain/kotlin/space/kscience/kmath/tensors/core/tensorCasts.kt @@ -35,3 +35,35 @@ public fun IntTensor.toIntArray(): IntArray { mutableBuffer[bufferStart + i] } } + +/** + * Casts [Array] to [DoubleTensor] + */ +public fun Array.toDoubleTensor(): DoubleTensor { + val n = size + check(n > 0) { "An empty array cannot be casted to tensor" } + val m = first().size + check(m > 0) { "Inner arrays must have at least 1 argument" } + check(all { size == m }) { "Inner arrays must be the same size" } + + val shape = intArrayOf(n, m) + val buffer = this.flatMap { arr -> arr.map { it } }.toDoubleArray() + + return DoubleTensor(shape, buffer, 0) +} + +/** + * Casts [Array] to [IntTensor] + */ +public fun Array.toIntTensor(): IntTensor { + val n = size + check(n > 0) { "An empty array cannot be casted to tensor" } + val m = first().size + check(m > 0) { "Inner arrays must have at least 1 argument" } + check(all { size == m }) { "Inner arrays must be the same size" } + + val shape = intArrayOf(n, m) + val buffer = this.flatMap { arr -> arr.map { it } }.toIntArray() + + return IntTensor(shape, buffer, 0) +}