# bend-ndarray: n-dimensional arrays for Bend 2, in the manner of NumPy. # # import bend-ndarray@/ndarray.bend as NP # # An ND is a dtype, a shape (a list of Nats) and its elements. Every operation takes its arrays and answers a new one # (no views; NP.clone makes two of one). An operation that can fail (shapes that do not broadcast, an axis that does # not exist, two dtypes) answers Result<&1, &1, NP.Err, ND>: Done{array} or Fail{why}. dtypes: f32, i32, u32, u8 and # bool; an operation takes one dtype (NP.astype converts), and integers wrap around. Shapes follow NumPy (shape.bend # and LAWS.bend: broadcasting proved to be NumPy's rule). import Base import ./shape.bend as S import ./cells.bend as C import ./tree.bend as T type ND is Type: ND{dt: S.DType, shape: List<&2, Nat>, data: Array} # ---- the dtypes and errors, by short names ---- def f32() -> S.DType: S.DF32{} def i32() -> S.DType: S.DI32{} def u32() -> S.DType: S.DU32{} def u8() -> S.DType: S.DU8{} def bool() -> S.DType: S.DBool{} def dt_eq(a: S.DType, b: S.DType) -> Bool: match a b: case S.DF32{} S.DF32{}: True{} case S.DI32{} S.DI32{}: True{} case S.DU32{} S.DU32{}: True{} case S.DU8{} S.DU8{}: True{} case S.DBool{} S.DBool{}: True{} case _ _: False{} def dt_name(dt: S.DType) -> String: match dt: case S.DF32{}: "float32" case S.DI32{}: "int32" case S.DU32{}: "uint32" case S.DU8{}: "uint8" case S.DBool{}: "bool" def nat_strs(s: List<&2, Nat>) -> List<&2, String>: match s: case []: [] case n <> t: Nat.show(n) <> nat_strs(t) # a shape as Python writes it: (2, 3), (4,), () def shape_str(+s: List<&2, Nat>) -> String: "(" ++ String.join(nat_strs(s), ", ") ++ Bool.pick(String, Nat.is_eq(List.length(&2, Nat, s), 1n), ",)", ")") # an error in words def why(e: S.NdErr) -> String: match e: case S.NoBroadcast{a, b}: "shapes " ++ shape_str(a) ++ " and " ++ shape_str(b) ++ " do not broadcast" case S.BadReshape{from, to}: "cannot reshape " ++ shape_str(from) ++ " into " ++ shape_str(to) case S.BadAxis{axis, ndim}: "axis " ++ Nat.show(axis) ++ " is out of bounds for " ++ Nat.show(ndim) ++ " dimensions" case S.BadPerm{perm, ndim}: "axes " ++ shape_str(perm) ++ " are not a permutation of " ++ Nat.show(ndim) ++ " axes" case S.BadConcat{axis, a, b}: "cannot join " ++ shape_str(a) ++ " and " ++ shape_str(b) ++ " along axis " ++ Nat.show(axis) case S.BadCount{need, got}: "the shape holds " ++ Nat.show(need) ++ " elements, the list " ++ Nat.show(got) case S.BadDType{op, dt}: op ++ " does not take " ++ dt_name(dt) case S.MixedDTypes{a, b}: "dtypes " ++ dt_name(a) ++ " and " ++ dt_name(b) ++ " differ (convert one with astype)" case S.EmptyReduce{axis}: "reduction along axis " ++ Nat.show(axis) ++ " of length 0 has no identity" case S.NoArrays{}: "no arrays" case S.BadStep{step}: "slice step " ++ Nat.show(step) ++ " (must be 1 or more)" case S.BadIndex{index, shape}: "index " ++ shape_str(index) ++ " is out of bounds for shape " ++ shape_str(shape) # ---- the pieces of an array ---- def dtype(a: ND) -> S.DType & ND: match a: case ND{+dt, s, d}: (dt, ND{dt, s, d}) def shape(a: ND) -> List<&2, Nat> & ND: match a: case ND{dt, +s, d}: (s, ND{dt, s, d}) def clone_got(+dt: S.DType, +s: List<&2, Nat>, p: Array & Array) -> ND & ND: match p: case Tuple{x, y}: (ND{dt, s, x}, ND{dt, s, y}) # ---- making arrays ---- def clone(a: ND) -> ND & ND: match a: case ND{+dt, +s, d}: clone_got(dt, s, Array.clone(U32, d)) def full(+dt: S.DType, +s: List<&2, Nat>, +v: U32) -> ND: ND{dt, s, T.fill(T.depth(s), v)} def zeros(+dt: S.DType, +s: List<&2, Nat>) -> ND: full(dt, s, 0) def one_of(dt: S.DType) -> U32: match dt: case S.DF32{}: 1065353216 case _: 1 def ones(+dt: S.DType, +s: List<&2, Nat>) -> ND: full(dt, s, one_of(dt)) def count_pick(ok: Bool, +dt: S.DType, +s: List<&2, Nat>, xs: List<&2, U32>, +got: Nat) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: Done{ND{dt, s, T.from_rows(s, xs)}} case False{}: Fail{S.BadCount{S.size(s), got}} # an array of shape s from its elements in row-major order (cells: float32 bits for f32, see cells.bend) def from_list(+dt: S.DType, +s: List<&2, Nat>, +xs: List<&2, U32>) -> Result<&1, &1, S.NdErr, ND>: count_pick(Nat.is_eq(List.length(&2, U32, xs), S.size(s)), dt, s, xs, List.length(&2, U32, xs)) def bits_of(xs: List<&2, F32>) -> List<&2, U32>: match xs: case []: [] case x <> t: C.bf(x) <> bits_of(t) def floats_of(xs: List<&2, U32>) -> List<&2, F32>: match xs: case []: [] case x <> t: C.fb(x) <> floats_of(t) # a float32 array from floats def from_f32s(+s: List<&2, Nat>, xs: List<&2, F32>) -> Result<&1, &1, S.NdErr, ND>: from_list(S.DF32{}, s, bits_of(xs)) # the elements in row-major order (cells) def to_list(a: ND) -> List<&2, U32>: match a: case ND{dt, s, d}: T.elems(s, d) def to_f32s(a: ND) -> List<&2, F32>: floats_of(to_list(a)) def range_cells(+dt: S.DType, i: Nat, +n: Nat) -> List<&2, U32>: match i: case 0n: [] case 1n+ +j: C.cell1(C.UConv{dt}, S.DU32{}, U32.from_nat(Nat.sub(n, 1n+j))) <> range_cells(dt, j, n) # 0, 1, ..., n - 1 def arange(+dt: S.DType, +n: Nat) -> ND: ND{dt, [n], T.tab(dt, T.dep(n), 0n, n)} def lin_cells(+start: F32, +step: F32, +stop: F32, i: Nat, +n: Nat) -> List<&2, U32>: match i: case 0n: [] case 1n+0n: [C.bf(stop)] case 1n+ +j: C.bf(F32.add(start, F32.mul(U32.to_f32(U32.from_nat(Nat.sub(n, 1n+j))), step))) <> lin_cells(start, step, stop, j, n) # num float32s from start to stop, both included def linspace(+start: F32, +stop: F32, +num: Nat) -> ND: ND{S.DF32{}, [num], T.from_rows([num], lin_cells(start, F32.div(F32.sub(stop, start), U32.to_f32(U32.from_nat(Nat.sub(num, 1n)))), stop, num, num))} def eye_cells(+one: U32, i: Nat, +n: Nat) -> List<&2, U32>: match i: case 0n: [] case 1n+ +j: Bool.pick(U32, Nat.is_eq(Nat.mod(Nat.sub(Nat.mul(n, n), 1n+j), Nat.add(n, 1n)), 0n), one, 0) <> eye_cells(one, j, n) # the n x n identity def eye(+dt: S.DType, +n: Nat) -> ND: ND{dt, [n, n], T.from_rows([n, n], eye_cells(one_of(dt), Nat.mul(n, n), n))} # ---- element-wise ---- def out_dt(op: C.B2, +dt: S.DType) -> S.DType: Bool.pick(S.DType, C.is_cmp(op), S.DBool{}, dt) def bin_shaped(r: Result<&2, &2, S.NdErr, List<&2, Nat>>, +op: C.B2, +dt: S.DType, +sa: List<&2, Nat>, +sb: List<&2, Nat>, ta: Array, tb: Array) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{+s}: Done{ND{out_dt(op, dt), s, T.zip(op, dt, T.stretch(sa, s, ta), T.stretch(sb, s, tb))}} case Fail{e}: Fail{e} def bin_typed(ok: Bool, +op: C.B2, +dt: S.DType, +sa: List<&2, Nat>, +sb: List<&2, Nat>, ta: Array, tb: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: bin_shaped(S.broadcast(sa, sb), op, dt, sa, sb, ta, tb) case False{}: Fail{S.BadDType{C.op_name(op), dt}} def bin_same(same: Bool, +op: C.B2, +da: S.DType, +db: S.DType, +sa: List<&2, Nat>, +sb: List<&2, Nat>, ta: Array, tb: Array) -> Result<&1, &1, S.NdErr, ND>: match same: case True{}: bin_typed(C.supports(op, da), op, da, sa, sb, ta, tb) case False{}: Fail{S.MixedDTypes{da, db}} # a binary operation (cells.bend's B2), broadcasting a and b def binop(+op: C.B2, a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: match a b: case ND{+da, sa, ta} ND{+db, sb, tb}: bin_same(dt_eq(da, db), op, da, db, sa, sb, ta, tb) def add(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BAdd{}, a, b) def subtract(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BSub{}, a, b) def multiply(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BMul{}, a, b) # true division, float32 only (integers: floor_divide) def divide(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BDiv{}, a, b) def floor_divide(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BFloorDiv{}, a, b) def remainder(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BRem{}, a, b) def minimum(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BMin{}, a, b) def maximum(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BMax{}, a, b) def power(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BPow{}, a, b) def equal(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BEq{}, a, b) def not_equal(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BNe{}, a, b) def less(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BLt{}, a, b) def less_equal(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BLe{}, a, b) def greater(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BGt{}, a, b) def greater_equal(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BGe{}, a, b) def logical_and(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BAnd{}, a, b) def logical_or(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BOr{}, a, b) def logical_xor(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BXor{}, a, b) def un_typed(ok: Bool, +op: C.U1, +name: String, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: Done{ND{dt, s, T.amap(op, dt, d)}} case False{}: Fail{S.BadDType{name, dt}} def negative(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(Bool.not(C.is_bool(dt)), C.UNeg{}, "negative", dt, s, d) def absolute(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(Bool.not(C.is_bool(dt)), C.UAbs{}, "absolute", dt, s, d) def logical_not(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(C.is_bool(dt), C.UNot{}, "logical_not", dt, s, d) # ---- math (float32; Base's F32 functions; rint and round take halves to the even integer, as NumPy) ---- def math1(+f: C.MF, +name: String, a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(C.is_f32(dt), C.UMath{f}, name, dt, s, d) def exp(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MExp{}, "exp", a) def log(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MLog{}, "log", a) def log2(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MLog2{}, "log2", a) def log10(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MLog10{}, "log10", a) def sqrt(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MSqrt{}, "sqrt", a) def sin(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MSin{}, "sin", a) def cos(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MCos{}, "cos", a) def tan(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MTan{}, "tan", a) def arcsin(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MAsin{}, "arcsin", a) def arccos(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MAcos{}, "arccos", a) def arctan(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MAtan{}, "arctan", a) def sinh(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MSinh{}, "sinh", a) def cosh(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MCosh{}, "cosh", a) def tanh(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MTanh{}, "tanh", a) def floor(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MFloor{}, "floor", a) def ceil(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MCeil{}, "ceil", a) def trunc(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MTrunc{}, "trunc", a) def rint(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MRint{}, "rint", a) def reciprocal(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MRecip{}, "reciprocal", a) # NumPy's round with no decimals: rint def round(a: ND) -> Result<&1, &1, S.NdErr, ND>: math1(C.MRint{}, "round", a) # x * x, every numeric dtype (integers wrap) def square(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(Bool.not(C.is_bool(dt)), C.USquare{}, "square", dt, s, d) # -1, 0 or 1, every numeric dtype (float32: nan stays nan) def sign(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, s, d}: un_typed(Bool.not(C.is_bool(dt)), C.USign{}, "sign", dt, s, d) # the angle of (x, y) from y's sign and the ratio, float32: arctan2(y, x) def arctan2(y: ND, x: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BAtan2{}, y, x) # sqrt(x * x + y * y) without overflow, float32 def hypot(a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: binop(C.BHypot{}, a, b) # the same elements as another dtype (float32 to integers rounds toward zero; to uint8 wraps; to bool: nonzero) def astype(a: ND, +to: S.DType) -> ND: match a: case ND{+dt, s, d}: ND{to, s, T.amap(C.UConv{to}, dt, d)} # ---- shapes ---- def relaid(dense: Bool, +s: List<&2, Nat>, +s2: List<&2, Nat>, d: Array) -> Array: match dense: case True{}: d case False{}: T.from_rows(s2, T.elems(s, d)) # between two shapes without padding the tree is already in row-major order, so it stays as it is def reshaped(r: Result<&2, &2, S.NdErr, List<&2, Nat>>, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{+s2}: Done{ND{dt, s2, relaid(Bool.and(T.dense(s), T.dense(s2)), s, s2, d)}} case Fail{e}: Fail{e} # the same elements, in row-major order, in shape s2 def reshape(a: ND, +s2: List<&2, Nat>) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: reshaped(S.reshape(s, s2), dt, s, d) def index_of(+x: Nat, xs: List<&2, Nat>) -> Nat: match xs: case []: 0n case +y <> t: Bool.pick(Nat, Nat.is_eq(x, y), 0n, Nat.add(1n, index_of(x, t))) # k, ..., j - 1 counted down: the adjacent swaps that bring position j to k def down(j: Nat, +k: Nat) -> List<&2, Nat>: match j: case 0n: [] case 1n+ +i: Bool.pick(List<&2, Nat>, Nat.is_le(k, i), i <> down(i, k), []) def move(+cur: List<&2, Nat>, +j: Nat, +k: Nat) -> List<&2, Nat>: S.insert_at(S.drop_at(cur, j), k, S.nth(cur, j)) def iota(i: Nat, +n: Nat) -> List<&2, Nat>: match i: case 0n: [] case 1n+ +j: Nat.sub(n, 1n+j) <> iota(j, n) # the adjacent swaps (i with i + 1) that turn axes 0 .. n - 1 into perm def plan(perm: List<&2, Nat>, +k: Nat, +cur: List<&2, Nat>) -> List<&2, Nat>: match perm: case []: [] case +t <> r: List.append(&2, Nat, down(index_of(t, cur), k), plan(r, Nat.add(k, 1n), move(cur, index_of(t, cur), k))) def swap_dims(+s: List<&2, Nat>, +i: Nat) -> List<&2, Nat>: S.set_at(S.set_at(s, i, S.nth(s, Nat.add(i, 1n))), Nat.add(i, 1n), S.nth(s, i)) def apply_swaps(sw: List<&2, Nat>, +s: List<&2, Nat>, t: Array) -> Array: match sw: case []: t case +i <> r: apply_swaps(r, swap_dims(s, i), T.swap_at(T.depth_before(s, i), T.dep(S.nth(s, i)), T.dep(S.nth(s, Nat.add(i, 1n))), t)) def transposed(r: Result<&2, &2, S.NdErr, List<&2, Nat>>, +dt: S.DType, +s: List<&2, Nat>, +perm: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{s2}: Done{ND{dt, s2, apply_swaps(plan(perm, 0n, iota(S.ndim(s), S.ndim(s))), s, d)}} case Fail{e}: Fail{e} # axes permuted: result axis k is a's axis perm[k] def transpose(a: ND, +perm: List<&2, Nat>) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: transposed(S.transpose(s, perm), dt, s, perm, d) def rev_iota(i: Nat) -> List<&2, Nat>: match i: case 0n: [] case 1n+ +j: j <> rev_iota(j) # the axes reversed (NumPy's a.T) def t(a: ND) -> ND: match a: case ND{+dt, +s, d}: ND{dt, S.permute(s, rev_iota(S.ndim(s))), apply_swaps(plan(rev_iota(S.ndim(s)), 0n, iota(S.ndim(s), S.ndim(s))), s, d)} def expanded(ok: Bool, +axis: Nat, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: Done{ND{dt, S.insert_at(s, axis, 1n), d}} case False{}: Fail{S.BadAxis{axis, Nat.add(S.ndim(s), 1n)}} # a new axis of length 1 at axis (0 .. ndim) def expand_dims(a: ND, +axis: Nat) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: expanded(Nat.is_le(axis, S.ndim(s)), axis, dt, s, d) def squeezed(ok: Bool, +axis: Nat, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: Done{ND{dt, S.drop_at(s, axis), d}} case False{}: Fail{S.BadAxis{axis, S.ndim(s)}} # axis removed; it must have length 1 def squeeze(a: ND, +axis: Nat) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: squeezed(Bool.and(Nat.is_lt(axis, S.ndim(s)), Nat.is_eq(S.nth(s, axis), 1n)), axis, dt, s, d) def bto_pick(ok: Bool, +dt: S.DType, +s: List<&2, Nat>, +s2: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: Done{ND{dt, s2, T.stretch(s, s2, d)}} case False{}: Fail{S.NoBroadcast{s, s2}} # a stretched to shape s2 (a must fit s2) def broadcast_to(a: ND, +s2: List<&2, Nat>) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: bto_pick(S.fits(s, s2), dt, s, s2, d) def sliced2(+m: Nat, +ax: Nat, +start: Nat, +step: Nat, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: Done{ND{dt, S.set_at(s, ax, m), T.slice_at(T.depth_before(s, ax), d, T.dep(S.nth(s, ax)), S.clamp(start, S.nth(s, ax)), step, m, T.dep(m), T.depth_after(s, ax))}} def sliced(ok: Bool, +ax: Nat, +start: Nat, +stop: Nat, +step: Nat, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: sliced2(S.slice_len(S.nth(s, ax), start, stop, step), ax, start, step, dt, s, d) case False{}: Fail{Bool.pick(S.NdErr, Nat.is_lt(ax, S.ndim(s)), S.BadStep{step}, S.BadAxis{ax, S.ndim(s)})} # a[..., start:stop:step, ...] along axis (step >= 1; start and stop clamped to the axis, as Python's slices) def slice(a: ND, +axis: Nat, +start: Nat, +stop: Nat, +step: Nat) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: sliced(Bool.and(Nat.is_lt(axis, S.ndim(s)), Nat.is_le(1n, step)), axis, start, stop, step, dt, s, d) def joined(r: Result<&2, &2, S.NdErr, List<&2, Nat>>, +ax: Nat, +dt: S.DType, +sa: List<&2, Nat>, +sb: List<&2, Nat>, ta: Array, tb: Array) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{s2}: Done{ND{dt, s2, T.concat_at(T.depth_before(sa, ax), ta, tb, T.dep(S.nth(sa, ax)), S.nth(sa, ax), T.dep(S.nth(sb, ax)), S.nth(sb, ax), T.dep(Nat.add(S.nth(sa, ax), S.nth(sb, ax))), T.depth_after(sa, ax))}} case Fail{e}: Fail{e} def join_same(same: Bool, +ax: Nat, +da: S.DType, +db: S.DType, +sa: List<&2, Nat>, +sb: List<&2, Nat>, ta: Array, tb: Array) -> Result<&1, &1, S.NdErr, ND>: match same: case True{}: joined(S.concat(ax, sa, sb), ax, da, sa, sb, ta, tb) case False{}: Fail{S.MixedDTypes{da, db}} # a and b joined along axis (equal on every other axis) def concatenate(+axis: Nat, a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: match a b: case ND{+da, sa, ta} ND{+db, sb, tb}: join_same(dt_eq(da, db), axis, da, db, sa, sb, ta, tb) def stack_same(same: Bool, +ax: Nat, a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: match same a b: case True{} ND{+da, +sa, ta} ND{+db, +sb, tb}: concatenate(ax, ND{da, S.insert_at(sa, ax, 1n), ta}, ND{db, S.insert_at(sb, ax, 1n), tb}) case False{} ND{da, sa, ta} ND{db, sb, tb}: Fail{S.BadConcat{ax, sa, sb}} def stack_go(+ax: Nat, a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: match a b: case ND{+da, +sa, ta} ND{+db, +sb, tb}: stack_same(Bool.and(S.eq_dims(sa, sb), Nat.is_le(ax, S.ndim(sa))), ax, ND{da, sa, ta}, ND{db, sb, tb}) # a and b (the same shape) joined along a new axis def stack(+axis: Nat, a: ND, b: ND) -> Result<&1, &1, S.NdErr, ND>: stack_go(axis, a, b) # ---- reductions ---- # the cells an empty reduction gives: sum 0, prod 1, all true, any false; min and max have none def identity(op: C.B2, +dt: S.DType) -> Maybe<&2, U32>: match op: case C.BAdd{}: Some{0} case C.BMul{}: Some{one_of(dt)} case C.BAnd{}: Some{1} case C.BOr{}: Some{0} case _: None{} def red_empty(m: Maybe<&2, U32>, +ax: Nat, +dt: S.DType, +s2: List<&2, Nat>) -> Result<&1, &1, S.NdErr, ND>: match m: case Some{+v}: Done{ND{dt, s2, T.fill(T.depth(s2), v)}} case None{}: Fail{S.EmptyReduce{ax}} def red_n(empty: Bool, +op: C.B2, +ax: Nat, +keep: Bool, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match empty: case True{}: red_empty(identity(op, dt), ax, dt, S.reduce_keep(keep, s, ax)) case False{}: Done{ND{dt, S.reduce_keep(keep, s, ax), T.red_at(op, dt, T.depth_before(s, ax), d, T.dep(S.nth(s, ax)), S.nth(s, ax), T.depth_after(s, ax))}} def red_ok(ok: Bool, +op: C.B2, +name: String, +ax: Nat, +keep: Bool, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, ND>: match ok: case True{}: red_n(Nat.is_eq(S.nth(s, ax), 0n), op, ax, keep, dt, s, d) case False{}: Fail{Bool.pick(S.NdErr, Nat.is_lt(ax, S.ndim(s)), S.BadDType{name, dt}, S.BadAxis{ax, S.ndim(s)})} def red_dt(op: C.B2, dt: S.DType) -> Bool: match op: case C.BAnd{}: C.is_bool(dt) case C.BOr{}: C.is_bool(dt) case _: Bool.not(C.is_bool(dt)) # a reduction along axis, the axis kept as length 1 with keep; pairs combine left to right, as a balanced tree def reduce(+op: C.B2, +name: String, a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: red_ok(Bool.and(Nat.is_lt(axis, S.ndim(s)), red_dt(op, dt)), op, name, axis, keep, dt, s, d) def sum(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BAdd{}, "sum", a, axis, keep) def prod(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BMul{}, "prod", a, axis, keep) def min(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BMin{}, "min", a, axis, keep) def max(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BMax{}, "max", a, axis, keep) def all(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BAnd{}, "all", a, axis, keep) def any(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: reduce(C.BOr{}, "any", a, axis, keep) def scale_by(r: Result<&1, &1, S.NdErr, ND>, +n: Nat) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{ND{+dt, s, d}}: Done{ND{dt, s, T.amap(C.UScale{C.bf(U32.to_f32(U32.from_nat(n)))}, dt, d)}} case Fail{e}: Fail{e} def mean_ok(ok: Bool, a: ND, +axis: Nat, +keep: Bool, +n: Nat) -> Result<&1, &1, S.NdErr, ND>: match ok a: case True{} a0: scale_by(sum(a0, axis, keep), n) case False{} ND{dt, s, d}: Fail{S.BadDType{"mean", dt}} # the mean along axis, float32 only (of a 0-length axis: nan, as NumPy) def mean(a: ND, +axis: Nat, +keep: Bool) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: mean_ok(C.is_f32(dt), ND{dt, s, d}, axis, keep, S.nth(s, axis)) # a reduction over every element: the axes reduced one at a time, the last first (a 0-d result) def red_all_go(k: Nat, +op: C.B2, +name: String, r: Result<&1, &1, S.NdErr, ND>) -> Result<&1, &1, S.NdErr, ND>: match k r: case 1n+ +j Done{a}: red_all_go(j, op, name, reduce(op, name, a, j, False{})) case _ r0: r0 def ndim_of(a: ND) -> Nat & ND: match a: case ND{dt, +s, d}: (S.ndim(s), ND{dt, s, d}) def red_all_at(p: Nat & ND, +op: C.B2, +name: String) -> Result<&1, &1, S.NdErr, ND>: match p: case Tuple{n, a}: red_all_go(n, op, name, Done{a}) def sum_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BAdd{}, "sum") def prod_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BMul{}, "prod") def min_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BMin{}, "min") def max_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BMax{}, "max") def all_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BAnd{}, "all") def any_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: red_all_at(ndim_of(a), C.BOr{}, "any") def mean_all_ok(ok: Bool, +n: Nat, a: ND) -> Result<&1, &1, S.NdErr, ND>: match ok a: case True{} a0: scale_by(sum_all(a0), n) case False{} ND{dt, s, d}: Fail{S.BadDType{"mean", dt}} # the mean of every element, float32 only def mean_all(a: ND) -> Result<&1, &1, S.NdErr, ND>: match a: case ND{+dt, +s, d}: mean_all_ok(C.is_f32(dt), S.size(s), ND{dt, s, d}) # ---- one element ---- def in_bounds(idx: List<&2, Nat>, s: List<&2, Nat>) -> Bool: match idx s: case Nil{} Nil{}: True{} case i <> it n <> st: Bool.and(Nat.is_lt(i, n), in_bounds(it, st)) case _ _: False{} # the cell index of element idx: each axis's index in its dep(n) bits, the first axis's highest def cell_index(idx: List<&2, Nat>, s: List<&2, Nat>, +acc: Nat) -> Nat: match idx s: case i <> it +n <> st: cell_index(it, st, Nat.add(Nat.mul(acc, T.pow2(T.dep(n))), i)) case _ _: acc def got(+dt: S.DType, +s: List<&2, Nat>, r: Array & U32) -> Result<&1, &1, S.NdErr, U32 & ND>: match r: case Tuple{d, v}: Done{(v, ND{dt, s, d})} def get_ok(ok: Bool, +idx: List<&2, Nat>, +dt: S.DType, +s: List<&2, Nat>, d: Array) -> Result<&1, &1, S.NdErr, U32 & ND>: match ok: case True{}: got(dt, s, Array.get(U32, d, U32.from_nat(cell_index(idx, s, 0n)))) case False{}: Fail{S.BadIndex{idx, s}} # element idx (one index per axis) and the array back def get(a: ND, +idx: List<&2, Nat>) -> Result<&1, &1, S.NdErr, U32 & ND>: match a: case ND{+dt, +s, d}: get_ok(in_bounds(idx, s), idx, dt, s, d) # ---- chaining and printing ---- # f applied to r's array, or r's error def and_then(r: Result<&1, &1, S.NdErr, ND>, f: ND -> Result<&1, &1, S.NdErr, ND>) -> Result<&1, &1, S.NdErr, ND>: match r: case Done{a}: f(a) case Fail{e}: Fail{e} # one element as NumPy prints it def cell_str(dt: S.DType, +x: U32) -> String: match dt: case S.DF32{}: F32.show(C.fb(x)) case S.DI32{}: Bool.pick(String, C.is_neg(x), "-" ++ U32.show(C.neg(x)), U32.show(x)) case S.DBool{}: Bool.pick(String, U32.is_eq(x, 0), "False", "True") case _: U32.show(x) def strs_of(+dt: S.DType, xs: List<&2, U32>) -> List<&2, String>: match xs: case []: [] case x <> t: cell_str(dt, x) <> strs_of(dt, t) def stake(n: Nat, xs: List<&2, String>) -> List<&2, String>: match n xs: case 1n+m x <> t: x <> stake(m, t) case _ _: [] def sdrop(n: Nat, xs: List<&2, String>) -> List<&2, String>: match n xs: case 1n+m x <> t: sdrop(m, t) case _ ys: ys # k groups of n strings, each joined by sep in brackets def groups(k: Nat, +n: Nat, +sep: String, +xs: List<&2, String>) -> List<&2, String>: match k: case 0n: [] case 1n+j: ("[" ++ String.join(stake(n, xs), sep) ++ "]") <> groups(j, n, sep, sdrop(n, xs)) def times(k: Nat, +s: String) -> String: match k: case 0n: "" case 1n+j: s ++ times(j, s) # NumPy's separator between the items of axis i of d: a space innermost, else newlines and an indent def sep(+i: Nat, +d: Nat) -> String: Bool.pick(String, Nat.is_eq(Nat.add(i, 1n), d), " ", times(Nat.sub(Nat.sub(d, 1n), i), "\n") ++ times(Nat.add(i, 1n), " ")) def first_str(xs: List<&2, String>) -> String: match xs: case []: "" case x <> t: x # the axes from the innermost out (rs reversed), grouping the strings at each def fmt(rs: List<&2, Nat>, +d: Nat, +strs: List<&2, String>) -> String: match rs: case []: first_str(strs) case +n <> +r: fmt(r, d, groups(S.size(r), n, sep(S.ndim(r), d), strs)) # the array as NumPy prints it: [[0 1 2]\n [3 4 5]] def to_string(a: ND) -> String: match a: case ND{+dt, +s, d}: fmt(List.reverse(&2, Nat, s), S.ndim(s), strs_of(dt, T.elems(s, d))) # a result as text: the array, or "error: " and why def show(r: Result<&1, &1, S.NdErr, ND>) -> String: match r: case Done{a}: to_string(a) case Fail{e}: "error: " ++ why(e)