Skip to content

Commit

Permalink
A simpler 'Array<*>.toF64Array'
Browse files Browse the repository at this point in the history
  • Loading branch information
superbobry committed Nov 1, 2016
1 parent 4013b7d commit 6689fc3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 19 deletions.
2 changes: 1 addition & 1 deletion CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Version 0.4.0
- Allowed slicing a `StridedVector` with custom `step`.
- Replaced `Strided` prefix with `F64`.
- Removed specialcased 'Vector', `Matrix2` and `Matrix3` classes in
faviour of a more generic `F64Array`.
favour of a more generic `F64Array`.
- Added a special attribute `V` for slicing the array.
- Removed `stochastic` and `indexedStochastic`.
- Added `axis` to `F64Array.append`, `F64Array.slice` and `F64Array.reorder`.
Expand Down
28 changes: 10 additions & 18 deletions src/main/kotlin/org/jetbrains/bio/viktor/F64Array.kt
Original file line number Diff line number Diff line change
Expand Up @@ -757,26 +757,18 @@ fun DoubleArray.asF64Array(offset: Int = 0, size: Int = this.size): F64Array {
/** Copies the elements of this nested array into [F64Array] of the same shape. */
fun Array<*>.toF64Array(): F64Array {
val shape = guessShape()
val a = F64Array(shape.product())

var ptr = 0
val q = ArrayDeque<Any>()
q.add(this)

do {
val tip = q.removeFirst()
when (tip) {
is DoubleArray -> {
tip.asF64Array().copyTo(a.slice(ptr, ptr + tip.size))
ptr += tip.size
}
is Array<*> -> q.addAll(tip)
return flatten(this).asF64Array().reshape(*shape)
}

/** Flattens a nested [DoubleArray]. */
private fun flatten(a: Array<*>): DoubleArray {
return Arrays.stream(a).flatMapToDouble {
when (it) {
is DoubleArray -> Arrays.stream(it)
is Array<*> -> Arrays.stream(flatten(a))
else -> unsupported()
}

} while (q.isNotEmpty())

return a.reshape(*shape)
}.toArray()
}

/** No validation, therefore "check". */
Expand Down

0 comments on commit 6689fc3

Please sign in to comment.