# bend-ndarray N-dimensional arrays for Bend 2, in the manner of NumPy: dtypes, shapes, broadcasting, element-wise arithmetic, math functions, random numbers, .npy files, 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 import bend-ndarray@/io.bend as NIO # .npy files: NIO.load(path), NIO.save(path, a) ``` ```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. - **.npy files** (`io.bend`; the encoding is pure, in `npy.bend`): `save` writes version 1.0, the array's dtype, little-endian, C order, the data aligned to 64 bytes, as `np.save` does. `load` reads versions 1, 2 and 3 as `np.load` does: Fortran-order arrays are transposed into row-major order and big-endian ones byte-swapped. Other dtypes convert: float64 to float32 (rounded to nearest, ties to even, exactly as NumPy's `astype`), float16 to float32 exactly, int8, int16 and uint16 to int32; int64 to int32 and uint64 to uint32 when every value fits, and otherwise the load is refused naming the first element that does not. Complex, string and structured dtypes are refused. Files are read and written with Base's `File` effects: pure Bend, no foreign code. - **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 | | files (since 0.1.3.0) | `io.bend`: `load(path)`, `save(path, a)`; `npy.bend`: `to_npy(a)` (the file's bytes) and `from_npy(bytes)` | | 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). Loading and saving a .npy file of a million elements takes 0.66 s for float32 (4 MB), 1.1 s for float64 converted to float32 (8 MB) and 0.3 s for uint8: the bytes travel as Bend lists. ## 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 twenty-four wrong cores; twenty-three are refused, and the other is equivalent (a permutation of length n that holds every axis at least once holds each exactly once). For .npy files: float64 to float32 rounding at its edge cases (ties both ways, the smallest subnormal and the tie below it, overflow to infinity at the exact boundary, -0, NaN), float16 to float32, save-then-load returning the array, and Fortran order, big-endian, int16, a Python 2 header and an int64 that fits loading right while an int64 past int32, complex64, a short file and a non-.npy file are refused. Six of the mutants break the file code (ties rounding up, Fortran read as C, big-endian read as little, no int64 range check, a float16 exponent off by one, a 1-byte header length). - **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 files** (`test/npy_cases.bend`, `test/npy_check.py`): NumPy writes 32 files, bend-ndarray loads and saves each, and NumPy reads them back: every element equals `np.load(input).astype(...)` bit for bit, including all 65,536 float16 values, 5,000 random float64 bit patterns and the float64 edge cases; every dtype, 0-d and empty shapes, Fortran order, big-endian, versions 2.0 and 3.0, a Python 2 header; the refusals name the right element or dtype; every file written has its data aligned to 64 bytes. - **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.