# bend-ndarray N-dimensional arrays for Bend 2, in the manner of NumPy: dtypes, shapes, broadcasting, element-wise arithmetic, comparisons, reductions along any axis, reshape, transpose, slicing and joining. NumPy's broadcasting rule is proved for every pair of shapes; the values are checked against NumPy itself. ```python import bend-ndarray@/ndarray.bend as NP import bend-ndarray@/shape.bend as S # the error type, S.NdErr ``` ```python def main() -> IO(Unit): do IO: IO.print(NP.show(NP.reshape(NP.arange(NP.i32(), 6n), [2n, 3n]))) # [[0 1 2] # [3 4 5]] IO.print(NP.show(NP.and_then(NP.reshape(NP.arange(NP.i32(), 6n), [2n, 3n]), a => NP.add(a, NP.arange(NP.i32(), 3n))))) # [[0 2 4] # [3 5 7]] IO.print(NP.show(NP.add(NP.arange(NP.i32(), 3n), NP.arange(NP.f32(), 3n)))) # error: dtypes int32 and float32 differ (convert one with astype) ``` ## How it behaves - **Arrays are values.** Every operation takes its arrays and answers a new one; there are no views. `NP.clone(a)` gives two. (A Bend array has one owner, so a NumPy-style view would be an alias.) - **Errors are values.** An operation that can fail answers `Result<&1, &1, S.NdErr, NP.ND>`: `Done{array}` or `Fail{why}`; `NP.why(e)` puts it in words, naming the shapes, axis or dtypes. `NP.and_then(r, f)` chains. - **One dtype per operation.** `float32` (`NP.f32()`), `int32`, `uint32`, `uint8` and `bool`. Mixing two is an error; `NP.astype(a, dt)` converts (float to integer rounds toward zero, to `uint8` wraps, to `bool` is "not zero"). - **Integers wrap around**, as in NumPy: `uint8` 200 + 100 is 44. - **Broadcasting is NumPy's**: shapes aligned at their last dimension, a missing dimension counts as 1, and two dimensions agree when equal or when one is 1. - **Division:** `divide` is true division, for `float32`; `floor_divide` and `remainder` follow Python's `//` and `%` for every numeric dtype (an integer divided by 0 gives 0, as NumPy does). `power` is `float32` only. - **Reductions** pair their elements in a balanced tree (pairwise summation), so float sums match NumPy's to rounding, not bit for bit. An empty axis gives the identity (`sum` 0, `prod` 1, `all` true, `any` false); `min` and `max` of one are an error. `mean` is `float32` only. - **Slices** take a start, a stop and a step of 1 or more, clamped like Python's `a[start:stop:step]`. ## Operations | Kind | Functions | | - | - | | make | `zeros(dt, shape)`, `ones`, `full(dt, shape, cell)`, `arange(dt, n)`, `linspace(start, stop, num)`, `eye(dt, n)`, `from_list(dt, shape, cells)`, `from_f32s(shape, floats)` | | read | `to_list(a)` (cells, row-major), `to_f32s(a)`, `get(a, index)`, `shape(a)`, `dtype(a)`, `to_string(a)`, `show(result)` | | element-wise | `add`, `subtract`, `multiply`, `divide`, `floor_divide`, `remainder`, `minimum`, `maximum`, `power`; `equal`, `not_equal`, `less`, `less_equal`, `greater`, `greater_equal` (to `bool`); `logical_and`, `logical_or`, `logical_xor`, `logical_not`; `negative`, `absolute`; `astype` | | shape | `reshape(a, shape)`, `transpose(a, perm)`, `t(a)` (NumPy's `a.T`), `expand_dims(a, axis)`, `squeeze(a, axis)`, `broadcast_to(a, shape)`, `slice(a, axis, start, stop, step)`, `concatenate(axis, a, b)`, `stack(axis, a, b)` | | reduce | `sum`, `prod`, `min`, `max`, `mean`, `all`, `any` along an axis (`keep` keeps it as length 1); `sum_all` and the others over every element | Cells are `U32`: a `float32` cell holds the float's bits (`from_f32s` and `to_f32s` convert), an `int32` cell its two's complement, `bool` 0 or 1. Shapes, axes and indexes are `Nat`s. ## How it works An array is its dtype, its shape and one Bend `Array`, a binary tree whose levels follow the dimensions: a dimension of n elements takes the least d levels with 2^d >= n, the first dimension's at the top. So a sub-array is a subtree, and the operations are recursions over the tree that Bend runs in parallel: broadcasting copies a subtree where an operand has a 1; a reduction combines the subtrees at one level, pairwise; transpose moves a dimension's levels below another's; slicing and joining rebuild one level. The cost is padding: each dimension is rounded up to a power of two (a 1000 x 1000 array uses 1024 x 1024 cells), and reshaping between shapes that are not all powers of two goes through the row-major list of elements. Speed, on an Intel i9-13900K (32 threads), against NumPy on the same machine (`test/bench.bend`, `test/bench.py`): a chain of ten operations on a 1024 x 1024 array (build, broadcast add, sums along each axis, transpose, reshape, slice, astype, a float32 multiply and a full sum) takes 160-190 ms, against about 6 ms for NumPy. Element-wise operations take 2-40 ms and reductions along an axis 4-9 ms per million elements. ## How it was checked - **The laws** (`LAWS.bend`, `PROOF.bend`; `./bend-check PROOF.bend --verdict`): for every pair of shapes, broadcasting succeeds exactly when some shape fits both (`broadcast_complete`), its result fits both (`broadcast_sound`), and it fits every shape both fit (`broadcast_least`): together, NumPy's rule and nothing else. Literal laws pin NumPy's broadcasting examples, reshape, transpose, reduction, slice and concatenation shapes. `mutants.sh` runs ten wrong shape cores; nine are refused, and the tenth is equivalent (a permutation of length n that holds every axis at least once holds each exactly once). - **The values** (`test/cases.bend`, `test/compare.py`, or `test/run.sh` for everything): 70 cases against NumPy, integers and bools exactly, float32 element-wise within 2 units in the last place and reductions within 1e-6: every operation, broadcasting across dimensions, wrap-around, Python's `//` and `%` on negative numbers and floats, NaN in `minimum` and comparisons, conversions, empty reductions, and padding never read as data. ## Requirements Bend 2.0.40. Pure Bend: no foreign code, nothing unsafe. `test/compare.py` needs Python 3 with NumPy.