# bend-ndarray N-dimensional arrays for Bend 2, in the manner of NumPy: dtypes (float64 among them, NumPy's default), 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) import bend-float64@0.1.8.0/float64.bend as F # float64 elements are bend-float64's F64 (a dependency) ``` ```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) IO.print(NP.show(NP.divide(NP.arange(NP.f64(), 3n), NP.astype(NP.full(NP.i32(), [], 3), NP.f64())))) # [0.0 0.3333333333333333 0.6666666666666666] ``` ## 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.** `float64` (`NP.f64()`), `float32` (`NP.f32()`), `int32`, `uint32`, `uint8` and `bool`. Mixing two is an error, float32 with float64 included (NumPy would promote); `NP.astype(a, dt)` converts (float to integer rounds toward zero, to `uint8` wraps, to `bool` is "not zero", float64 to float32 rounds to nearest, ties to even, and everything to float64 is exact). - **float64** elements are bend-float64's `F64`: IEEE 754 binary64 in pure Bend, with the bits NumPy gives on x86-64. Arithmetic and comparisons are IEEE's; `floor_divide` and `remainder` follow NumPy's divmod (and, of two NaNs, `remainder` returns the one glibc's `fmod` picks, as NumPy does); the math functions are correctly rounded, so they match NumPy wherever glibc is, and are closer where it is not. `from_f64s`, `to_f64s`, `full_f64`, `get_f64` and `linspace_f64` take and give `F64`s; `from_list` and `to_list` give a float64 as two cells, its high word first. - **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 floats; `floor_divide` and `remainder` follow Python's `//` and `%` for every numeric dtype (an integer divided by 0 gives 0, as NumPy does). `power` is for floats 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 for floats only. - **Math functions** (`exp`, `log`, `sin`, ...) take floats only, like true division: NumPy would turn integers into float64 by itself; here `astype` does it. float32 uses Bend's built-ins (the C library's); float64 uses bend-float64's, correctly rounded. `square`, `sign` and `absolute` take every numeric dtype; `sign` of either zero is +0, as NumPy's. `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. The float64 draws (`random_f64` and the others) take two of Philox's words for each number: 53 random bits, as NumPy builds a double. - **.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. float64 loads as float64, bit for bit, NaN payloads included (before 0.1.4.0 it was converted to float32). Other dtypes convert: 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)`; float64 (since 0.1.4.0): `from_f64s(shape, F64s)`, `full_f64(shape, x)`, `linspace_f64(start, stop, num)` | | read | `to_list(a)` (cells, row-major), `to_f32s(a)`, `to_f64s(a)`, `get(a, index)`, `get_f64(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 (floats) | `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); float64 (since 0.1.4.0): `random_f64(g, shape)` (53 random bits), `uniform_f64`, `standard_normal_f64`, `normal_f64` | 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; a `float64` element is two cells, its high word first (`from_f64s` and `to_f64s` convert). 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. A float64 element is a node of two cells, as if the array had one more dimension of 2: the operations that move elements work on it unchanged, and the element-wise ones stop at those nodes. 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) and 0.3 s for uint8: the bytes travel as Bend lists. float64 is software arithmetic (bend-float64): on a million elements `add` takes about 0.3 s, `divide` 0.5 s, `sqrt` 0.4 s, `sin` and `exp` 1.3 s (correctly rounded), `random_f64` 0.11 s, `standard_normal_f64` 1.4 s, and loading then saving a float64 file 1.8 s. ## 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`). For .npy files: float16 to float32, save-then-load returning the array (a float64 one included), and Fortran order, big-endian (float64 too), 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. astype from float64 to float32 rounds as NumPy's at its edge cases (ties both ways, the smallest subnormal and the tie below it, overflow to infinity at the exact boundary, -0, NaN). - **The float64 laws** (`F64_LAWS.bend`, `F64_PROOF.bend`; `./bend-check F64_PROOF.bend --verdict`, a gate of its own for the checker's time limit): NumPy's `//` and `%` on signs, zeros, a zero divisor and two NaNs; conversions where going through float32 or the wrong integer width would differ; each element's two cells kept together through reshape, transpose, slices, a sum, a comparison and astype; and padding made of whole elements (the runtime stops on an unbalanced tree, which the checker would read back as the right values). - **Mutants:** `mutants.sh` runs 36 wrong cores against the two gates. 34 are refused; two are equivalent (a permutation of length n that holds every axis at least once holds each exactly once; a reduction's fill depth is never used, since an axis being reduced has an element). They include six in the file code, a float64 to float32 conversion that truncates, and twelve in the float64 dtype: remainder signs, the quotient's adjustment, the NaN choice, fmod's loop, an element's words swapped, an element level forgotten by reshape, slice or join, a comparison giving float64, and int32 conversion through float32. - **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. - **float64** (`test/f64_cases.bend`, `test/f64_check.py`): 4,096 inputs mixing raw random bit patterns (NaNs and infinities among them), special values, quarters, integers and extreme exponents, through every operation. The arithmetic, comparisons, `floor_divide`, `remainder`, `minimum`, `maximum`, `sign`, the roundings, every conversion both ways, shapes and constructors equal NumPy bit for bit; the math functions equal mpmath's correctly rounded values (NumPy's glibc differs on up to 260 of the 4,096 for `sinh`); reductions equal the same sums in bend-ndarray's pairwise order bit for bit, and NumPy's within 1e-12; mixed dtypes and the wrong accessor are refused. - **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)` in the dtype bend-ndarray loads it as, bit for bit, including all 65,536 float16 values, 5,000 random float64 bit patterns (kept as float64) 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. The float64 draws: each of the first 2,000 equals Philox's words turned into 53 bits by a Python Philox (itself checked against the known answers), a normal draw's first element equals Box-Muller on its words, and the same distribution tests pass. ## Requirements Bend 2.0.40 and bend-float64 0.1.8.0 (from the hub). Pure Bend: no foreign code, nothing unsafe. `test/compare.py` needs Python 3 with NumPy; `test/f64_check.py` also needs mpmath.