# bend-ndarray N-dimensional arrays for Bend 2, in the manner of NumPy: dtypes, shapes, broadcasting, element-wise arithmetic, math functions, random numbers, 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. - **Math functions** (`exp`, `log`, `sin`, ...) take `float32` only, like true division: NumPy would turn integers into float64, which Bend does not have, so convert with `astype` first. `square`, `sign` and `absolute` take every numeric dtype. `rint` and `round` take a half to the even integer, as NumPy does (2.5 to 2, 3.5 to 4). - **Random numbers** come from a generator, NumPy-style: `g = NP.rng(seed)`, and each draw answers the array and the next generator, `(a, g2) = NP.normal(g, shape, mean, std)`; draw again with `g2` (drawing again with `g` repeats the numbers). The generator is Philox4x32-10 (Random123's, as in JAX and PyTorch): counter-based, so element i of a draw depends only on the seed, the draw's number and i. The same seed gives the same numbers in any order of evaluation, on any machine, and in any shape of the same size (`(6,)` and `(2, 3)` draw the same six numbers); they are not NumPy's numbers for that seed. - **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`, `square`, `sign`; `astype` | | math (float32) | `exp`, `log`, `log2`, `log10`, `sqrt`, `sin`, `cos`, `tan`, `arcsin`, `arccos`, `arctan`, `sinh`, `cosh`, `tanh`, `floor`, `ceil`, `trunc`, `rint`, `round`, `reciprocal`; `arctan2(y, x)`, `hypot(a, b)` (since 0.1.1.0) | | 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 | | random (since 0.1.2.0) | `rng(seed)`, `rng64(hi, lo)`; `random(g, shape)` (float32 in [0, 1), 24 random bits), `uniform(g, shape, low, high)`, `standard_normal(g, shape)`, `normal(g, shape, mean, std)` (Box-Muller), `integers(g, dtype, shape, low, high)` (in [low, high), every value equally likely: Lemire's method with rejection), `permutation(g, n)` (int32 0 .. n - 1 in random order: the indices sorted by random 64-bit keys) | 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. Random draws of a million take 56-94 ms (NumPy 3-14 ms); `permutation` sorts a list, so it takes 81 ms for 100,000 and 2.8 s for a million (NumPy 1 and 12 ms). ## 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, and which dtypes the math functions take. For random numbers: Philox gives Random123's published answer (`philox_known`), and `permutation` is a permutation for every seed: its sort keeps each index as often as its input had it, for every list (`sort_keeps`), and its input holds 0 .. n - 1 once each (`keyed_indices`). `mutants.sh` runs eighteen wrong cores; seventeen are refused, and the other 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): 119 cases against NumPy, integers and bools exactly, float32 arithmetic 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. The math functions are Bend's float32 built-ins (the C library's): on 8,193 points each over their range (and on infinities, signed zeros, NaN and values outside their domain) they are within 2 units in the last place of NumPy's (`exp`), 1 (the others), or equal (`sqrt`); `floor`, `ceil`, `trunc`, `rint`, `round`, `sign`, `square` and `reciprocal` are equal bit for bit. - **The random numbers** (`test/random.bend`, `test/random_check.py`): all three of Random123's known answers for Philox4x32-10; reproducibility, other seeds and successive draws independent; every value in range; the distributions at the 0.1% level: Kolmogorov-Smirnov for `random`, `uniform` and the normals (100,000-200,000 draws), chi-square for `integers` (including a range of 3 x 2^30, where a modulo shortcut would favour a third 2:1; that test rejects such a method at z = 50) and for the 24 orders of `permutation(4)` over 2,400 draws; `permutation(100000)` holding every index once. ## Requirements Bend 2.0.40. Pure Bend: no foreign code, nothing unsafe. `test/compare.py` needs Python 3 with NumPy.