shape.bend source
shape.bend on the hub · documented module
# bend-ndarray's shape rules, pure: broadcasting, reshape, transpose, reductions, slices and concatenation decide the# result's shape (or why there is none) here, before any data moves. LAWS.bend states what they guarantee.import Base# ---- what can go wrong ----type DType is Data: DF32{} DI32{} DU32{} DU8{} DBool{}type NdErr is Data: NoBroadcast{a: List<&2, Nat>, b: List<&2, Nat>} BadReshape{from: List<&2, Nat>, to: List<&2, Nat>} BadAxis{axis: Nat, ndim: Nat} BadPerm{perm: List<&2, Nat>, ndim: Nat} BadConcat{axis: Nat, a: List<&2, Nat>, b: List<&2, Nat>} BadCount{need: Nat, got: Nat} BadDType{op: String, dt: DType} MixedDTypes{a: DType, b: DType} EmptyReduce{axis: Nat} BadStep{step: Nat} BadIndex{index: List<&2, Nat>, shape: List<&2, Nat>} NoArrays{}def size(s: List<&2, Nat>) -> Nat: match s: case []: 1n case n <> t: Nat.mul(n, size(t))def ndim(s: List<&2, Nat>) -> Nat: List.length(&2, Nat, s)# ---- broadcasting (NumPy's rule): shapes aligned at their last dimension; a missing dimension counts as 1; two# dimensions agree when they are equal or one of them is 1, and the result takes the other ----# one aligned pair, given its three tests: x is 1, y is 1, x equals ydef bpick(x1: Bool, y1: Bool, e: Bool, +x: Nat, +y: Nat) -> Maybe<&2, Nat>: match x1 y1 e: case True{} _ _: Some{y} case False{} True{} _: Some{x} case False{} False{} True{}: Some{x} case False{} False{} False{}: None{}def bdim(+x: Nat, +y: Nat) -> Maybe<&2, Nat>: bpick(Nat.is_eq(x, 1n), Nat.is_eq(y, 1n), Nat.is_eq(x, y), x, y)def mcons(m: Maybe<&2, Nat>, r: Maybe<&2, List<&2, Nat>>) -> Maybe<&2, List<&2, Nat>>: match m r: case Some{d} Some{l}: Some{d <> l} case _ _: None{}# broadcasting on shapes written last dimension firstdef bcast_rev(ra: List<&2, Nat>, rb: List<&2, Nat>) -> Maybe<&2, List<&2, Nat>>: match ra rb: case Nil{} Nil{}: Some{[]} case Nil{} y <> ys: Some{y <> ys} case x <> xs Nil{}: Some{x <> xs} case +x <> xs +y <> ys: mcons(bdim(x, y), bcast_rev(xs, ys))def bcast_done(m: Maybe<&2, List<&2, Nat>>, a: List<&2, Nat>, b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: match m: case Some{r}: Done{List.reverse(&2, Nat, r)} case None{}: Fail{NoBroadcast{a, b}}# the shape a and b broadcast to, or NoBroadcast{a, b}def broadcast(+a: List<&2, Nat>, +b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: bcast_done(bcast_rev(List.reverse(&2, Nat, a), List.reverse(&2, Nat, b)), a, b)# a fits s: a broadcasts to s unchanged (each of a's dimensions, aligned at the end, is 1 or s's; a is no longer)def fits_rev(ra: List<&2, Nat>, rs: List<&2, Nat>) -> Bool: match ra rs: case Nil{} _: True{} case x <> xs Nil{}: False{} case +x <> xs +y <> ys: Bool.and(Bool.or(Nat.is_eq(x, 1n), Nat.is_eq(x, y)), fits_rev(xs, ys))def fits(a: List<&2, Nat>, s: List<&2, Nat>) -> Bool: fits_rev(List.reverse(&2, Nat, a), List.reverse(&2, Nat, s))# ---- reshape: the same number of elements ----def reshape_pick(ok: Bool, +a: List<&2, Nat>, +b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: match ok: case True{}: Done{b} case False{}: Fail{BadReshape{a, b}}def reshape(+a: List<&2, Nat>, +b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: reshape_pick(Nat.is_eq(size(a), size(b)), a, b)# ---- axes ----def axis_pick(ok: Bool, +axis: Nat, +n: Nat) -> Result<&2, &2, NdErr, Nat>: match ok: case True{}: Done{axis} case False{}: Fail{BadAxis{axis, n}}# axis of a shape with n dimensions: 0 .. n - 1def axis_of(+axis: Nat, +n: Nat) -> Result<&2, &2, NdErr, Nat>: axis_pick(Nat.is_lt(axis, n), axis, n)def nth(s: List<&2, Nat>, i: Nat) -> Nat: match s i: case Nil{} _: 0n case x <> t 0n: x case x <> t 1n+j: nth(t, j)def drop_at(s: List<&2, Nat>, i: Nat) -> List<&2, Nat>: match s i: case Nil{} _: [] case x <> t 0n: t case x <> t 1n+j: x <> drop_at(t, j)def set_at(s: List<&2, Nat>, i: Nat, +v: Nat) -> List<&2, Nat>: match s i: case Nil{} _: [] case x <> t 0n: v <> t case x <> t 1n+j: x <> set_at(t, j, v)def insert_at(s: List<&2, Nat>, i: Nat, +v: Nat) -> List<&2, Nat>: match s i: case _ 0n: v <> s case Nil{} 1n+j: [v] case x <> t 1n+j: x <> insert_at(t, j, v)# the shape after reducing axis (kept as a 1 with keep)def reduce_keep(k: Bool, +s: List<&2, Nat>, +axis: Nat) -> List<&2, Nat>: match k: case True{}: set_at(s, axis, 1n) case False{}: drop_at(s, axis)# ---- transpose: perm lists every axis once ----def count_of(+x: Nat, p: List<&2, Nat>) -> Nat: match p: case []: 0n case +y <> t: Nat.add(Bool.pick(Nat, Nat.is_eq(x, y), 1n, 0n), count_of(x, t))# each of 0 .. k - 1 occurs exactly once in pdef once_each(k: Nat, +p: List<&2, Nat>) -> Bool: match k: case 0n: True{} case 1n+ +j: Bool.and(Nat.is_eq(count_of(j, p), 1n), once_each(j, p))def is_perm(+p: List<&2, Nat>, +n: Nat) -> Bool: Bool.and(Nat.is_eq(List.length(&2, Nat, p), n), once_each(n, p))def permute(+s: List<&2, Nat>, p: List<&2, Nat>) -> List<&2, Nat>: match p: case []: [] case i <> t: nth(s, i) <> permute(s, t)def perm_pick(ok: Bool, +s: List<&2, Nat>, +p: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: match ok: case True{}: Done{permute(s, p)} case False{}: Fail{BadPerm{p, ndim(s)}}# the shape after transposing s by perm p: result axis k is s's axis p[k]def transpose(+s: List<&2, Nat>, +p: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: perm_pick(is_perm(p, ndim(s)), s, p)# ---- slices: start, stop (clamped to the length), step >= 1 ----def clamp(+x: Nat, +n: Nat) -> Nat: Bool.pick(Nat, Nat.is_le(x, n), x, n)# how many of start, start + step, ... are below stop (step >= 1)def slice_len(+n: Nat, +start: Nat, +stop: Nat, +step: Nat) -> Nat: Nat.div(Nat.add(Nat.sub(clamp(stop, n), clamp(start, n)), Nat.sub(step, 1n)), step)# ---- concatenation: equal everywhere but the axis ----def eq_dims(s: List<&2, Nat>, t: List<&2, Nat>) -> Bool: match s t: case Nil{} Nil{}: True{} case x <> xs y <> ys: Bool.and(Nat.is_eq(x, y), eq_dims(xs, ys)) case _ _: False{}# s and t have the same number of dimensions and agree on every one but axis idef same_but(s: List<&2, Nat>, t: List<&2, Nat>, i: Nat) -> Bool: match s t i: case Nil{} Nil{} _: True{} case x <> xs y <> ys 0n: eq_dims(xs, ys) case x <> xs y <> ys 1n+j: Bool.and(Nat.is_eq(x, y), same_but(xs, ys, j)) case _ _ _: False{}def concat_pick(ok: Bool, +axis: Nat, +a: List<&2, Nat>, +b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: match ok: case True{}: Done{set_at(a, axis, Nat.add(nth(a, axis), nth(b, axis)))} case False{}: Fail{BadConcat{axis, a, b}}# the shape of a and b joined along axis (which must be one of their axes)def concat(+axis: Nat, +a: List<&2, Nat>, +b: List<&2, Nat>) -> Result<&2, &2, NdErr, List<&2, Nat>>: concat_pick(Bool.and(Nat.is_lt(axis, ndim(a)), same_but(a, b, axis)), axis, a, b)