# bend-ndarray's .npy files, pure: an array to the bytes of a .npy file (version 1.0, little-endian, C order), and the # bytes of a .npy file (versions 1, 2 and 3) back to an array. Reading and writing the files: io.bend. # float64 loads as float64, bit for bit (NaN payloads too). Other dtypes are converted as they load: float16 to float32 # (exactly); int8, int16 and uint16 to int32 (exactly); int64 to int32 and uint64 to uint32 when # every value fits, else the load is refused naming the first that does not. Fortran-order arrays are transposed into # row-major order and big-endian ones byte-swapped, so an array loads as np.load reads it. import Base import ./shape.bend as S import ./cells.bend as C import ./tree.bend as T import ./ndarray.bend as NP # ---- bytes and words ---- def b0(+x: U32) -> U32: U32.and(x, 255) def b1(+x: U32) -> U32: U32.and(U32.div(x, 256), 255) def b2(+x: U32) -> U32: U32.and(U32.div(x, 65536), 255) def b3(+x: U32) -> U32: U32.div(x, 16777216) def le4(xs: List<&2, U32>) -> List<&2, U32>: match xs: case []: [] case +x <> t: b0(x) <> b1(x) <> b2(x) <> b3(x) <> le4(t) def le1(xs: List<&2, U32>) -> List<&2, U32>: match xs: case []: [] case x <> t: U32.and(x, 255) <> le1(t) def ascii(s: String) -> List<&2, U32>: match s: case SNil{}: [] case SCon{c, t}: Char.to_u32(c) <> ascii(t) def text(bs: List<&2, U32>) -> String: match bs: case []: SNil{} case b <> t: SCon{Chr{b}, text(t)} def btake(n: Nat, xs: List<&2, U32>) -> List<&2, U32>: match n xs: case 1n+m x <> t: x <> btake(m, t) case _ _: [] def bdrop(n: Nat, xs: List<&2, U32>) -> List<&2, U32>: match n xs: case 1n+m x <> t: bdrop(m, t) case _ ys: ys def bnth(xs: List<&2, U32>, n: Nat) -> U32: match xs n: case Nil{} _: 0 case x <> t 0n: x case x <> t 1n+m: bnth(t, m) def spaces(n: Nat) -> List<&2, U32>: match n: case 0n: [] case 1n+m: 32 <> spaces(m) # ---- float16 to float32, exactly ---- # the highest set bit of m (1 .. 1023), counted from 0 def top_bit(fuel: Nat, +m: U32, +p: Nat) -> Nat: match fuel: case 0n: p case 1n+f: Bool.pick(Nat, U32.is_le(U32.shln(1, Nat.add(p, 1n)), m), top_bit(f, m, Nat.add(p, 1n)), p) def f16_sub(+sign: U32, +m: U32, +p: Nat) -> U32: U32.or(sign, U32.or(U32.mul((U32.from_nat(p) + 103 : U32), 8388608), U32.and(U32.shln(m, Nat.sub(23n, p)), 8388607))) def f16_parts(+sign: U32, +e: U32, +m: U32) -> U32: Bool.pick(U32, U32.is_eq(e, 31), U32.or(sign, U32.or(2139095040, U32.shln(m, 13n))), Bool.pick(U32, U32.is_eq(e, 0), Bool.pick(U32, U32.is_eq(m, 0), sign, f16_sub(sign, m, top_bit(10n, m, 0n))), U32.or(sign, U32.or(U32.shln((e + 112 : U32), 23n), U32.shln(m, 13n))))) # ---- writing ---- def f16_to_f32(+h: U32) -> U32: f16_parts(U32.mul(U32.and(h, 32768), 65536), U32.and(U32.div(h, 1024), 31), U32.and(h, 1023)) def descr(dt: S.DType) -> String: match dt: case S.DF32{}: " Bool: match dt: case S.DU8{}: False{} case S.DBool{}: False{} case _: True{} # the header dict as np.save writes it def header_text(+dt: S.DType, +s: List<&2, Nat>) -> List<&2, U32>: ascii("{'descr': '" ++ descr(dt) ++ "', 'fortran_order': False, 'shape': " ++ NP.shape_str(s) ++ ", }") # padded with spaces and a newline so the data starts at a multiple of 64 bytes def header_padded(+h: List<&2, U32>) -> List<&2, U32>: List.append(&2, U32, h, List.append(&2, U32, spaces(Nat.sub(63n, Nat.mod(Nat.add(List.length(&2, U32, h), 10n), 64n))), [10])) def data_bytes(w: Bool, cells: List<&2, U32>) -> List<&2, U32>: match w: case True{}: le4(cells) case False{}: le1(cells) # a float64 element's cells (high word, low word) in the order its bytes are stored (low word first) def lo_first(xs: List<&2, U32>) -> List<&2, U32>: match xs: case +h <> +l <> t: l <> h <> lo_first(t) case _: [] def stored(dt: S.DType, xs: List<&2, U32>) -> List<&2, U32>: match dt: case S.DF64{}: lo_first(xs) case _: xs def file_bytes(+dt: S.DType, +h: List<&2, U32>, cells: List<&2, U32>) -> List<&2, U32>: List.append(&2, U32, [147, 78, 85, 77, 80, 89, 1, 0, b0(U32.from_nat(List.length(&2, U32, h))), b1(U32.from_nat(List.length(&2, U32, h)))], List.append(&2, U32, h, data_bytes(wide(dt), stored(dt, cells)))) # the bytes of a .npy file holding a (version 1.0: the array's dtype, little-endian, C order) def to_npy(a: NP.ND) -> List<&2, U32>: match a: case NP.ND{+dt, +s, d}: file_bytes(dt, header_padded(header_text(dt, s)), T.elems(NP.ps(dt, s), d)) # ---- reading the header ---- type Tok is Data: TStr{s: List<&2, U32>} TWord{s: List<&2, U32>} TNum{n: Nat} TMark{c: U32} type Lex is Data: LIdle{} LStr{q: U32, acc: List<&2, U32>} LWord{acc: List<&2, U32>} LNum{n: Nat} def is_digit(+b: U32) -> Bool: Bool.and(U32.is_ge(b, 48), U32.is_le(b, 57)) def is_alpha(+b: U32) -> Bool: Bool.or(Bool.or(Bool.and(U32.is_ge(b, 65), U32.is_le(b, 90)), Bool.and(U32.is_ge(b, 97), U32.is_le(b, 122))), U32.is_eq(b, 95)) def is_quote(+b: U32) -> Bool: Bool.or(U32.is_eq(b, 39), U32.is_eq(b, 34)) def is_mark(+b: U32) -> Bool: Bool.or(Bool.or(Bool.or(U32.is_eq(b, 123), U32.is_eq(b, 125)), Bool.or(U32.is_eq(b, 40), U32.is_eq(b, 41))), Bool.or(U32.is_eq(b, 58), U32.is_eq(b, 44))) # the state after one byte from idle, and the token list type LexT is Data: LexT{st: Lex, out: List<&2, Tok>} def idle_byte(+b: U32, +out: List<&2, Tok>) -> LexT: Bool.pick(LexT, is_quote(b), LexT{LStr{b, []}, out}, Bool.pick(LexT, is_digit(b), LexT{LNum{U32.to_nat((b - 48 : U32))}, out}, Bool.pick(LexT, is_alpha(b), LexT{LWord{[b]}, out}, Bool.pick(LexT, is_mark(b), LexT{LIdle{}, TMark{b} <> out}, LexT{LIdle{}, out})))) def lex_step(l: LexT, +b: U32) -> LexT: match l: case LexT{LIdle{}, +out}: idle_byte(b, out) case LexT{LStr{+q, +acc}, +out}: Bool.pick(LexT, U32.is_eq(b, q), LexT{LIdle{}, TStr{List.reverse(&2, U32, acc)} <> out}, LexT{LStr{q, b <> acc}, out}) case LexT{LWord{+acc}, +out}: Bool.pick(LexT, Bool.or(is_alpha(b), is_digit(b)), LexT{LWord{b <> acc}, out}, idle_byte(b, TWord{List.reverse(&2, U32, acc)} <> out)) case LexT{LNum{+n}, +out}: Bool.pick(LexT, is_digit(b), LexT{LNum{Nat.add(Nat.mul(n, 10n), U32.to_nat((b - 48 : U32)))}, out}, idle_byte(b, TNum{n} <> out)) def lex_go(bs: List<&2, U32>, l: LexT) -> LexT: match bs: case []: l case +b <> t: lex_go(t, lex_step(l, b)) def lex_end(l: LexT) -> List<&2, Tok>: match l: case LexT{LNum{n}, out}: List.reverse(&2, Tok, TNum{n} <> out) case LexT{LWord{acc}, out}: List.reverse(&2, Tok, TWord{List.reverse(&2, U32, acc)} <> out) case LexT{_, out}: List.reverse(&2, Tok, out) # the header's tokens: strings, words, numbers and the marks { } ( ) : , def lex(bs: List<&2, U32>) -> List<&2, Tok>: lex_end(lex_go(bs, LexT{LIdle{}, []})) def bytes_eq(a: List<&2, U32>, b: List<&2, U32>) -> Bool: match a b: case Nil{} Nil{}: True{} case x <> xs y <> ys: Bool.and(U32.is_eq(x, y), bytes_eq(xs, ys)) case _ _: False{} def is_key(t: Tok, +k: List<&2, U32>) -> Bool: match t: case TStr{s}: bytes_eq(s, k) case _: False{} # the tokens after the key k and its colon def bdrop_tok(ts: List<&2, Tok>) -> List<&2, Tok>: match ts: case []: [] case t <> r: r def after_key(ts: List<&2, Tok>, +k: List<&2, U32>) -> List<&2, Tok>: match ts: case []: [] case +t <> +r: Bool.pick(List<&2, Tok>, is_key(t, k), bdrop_tok(r), after_key(r, k)) def str_val(ts: List<&2, Tok>) -> Maybe<&2, List<&2, U32>>: match ts: case TStr{s} <> r: Some{s} case _: None{} def bool_val(ts: List<&2, Tok>) -> Maybe<&2, Bool>: match ts: case TWord{+s} <> r: Bool.pick(Maybe<&2, Bool>, bytes_eq(s, ascii("True")), Some{True{}}, Bool.pick(Maybe<&2, Bool>, bytes_eq(s, ascii("False")), Some{False{}}, None{})) case _: None{} # the numbers of a tuple: from its ( to its ), skipping commas and Python 2's L suffixes def nums_go(ts: List<&2, Tok>, +acc: List<&2, Nat>) -> Maybe<&2, List<&2, Nat>>: match ts: case []: None{} case TMark{+c} <> r: Bool.pick(Maybe<&2, List<&2, Nat>>, U32.is_eq(c, 41), Some{List.reverse(&2, Nat, acc)}, nums_go(r, acc)) case TNum{n} <> r: nums_go(r, n <> acc) case _ <> r: nums_go(r, acc) def tuple_val(ts: List<&2, Tok>) -> Maybe<&2, List<&2, Nat>>: match ts: case TMark{+c} <> r: Bool.pick(Maybe<&2, List<&2, Nat>>, U32.is_eq(c, 40), nums_go(r, []), None{}) case _: None{} type Hdr is Data: Hdr{descr: List<&2, U32>, fortran: Bool, shape: List<&2, Nat>} def hdr_of(d: Maybe<&2, List<&2, U32>>, f: Maybe<&2, Bool>, s: Maybe<&2, List<&2, Nat>>) -> Result<&2, &2, S.NdErr, Hdr>: match d f s: case Some{dd} Some{ff} Some{ss}: Done{Hdr{dd, ff, ss}} case _ _ _: Fail{S.BadNpy{"the header lacks descr, fortran_order or shape"}} # the header dict's three entries def header(+ts: List<&2, Tok>) -> Result<&2, &2, S.NdErr, Hdr>: hdr_of(str_val(after_key(ts, ascii("descr"))), bool_val(after_key(ts, ascii("fortran_order"))), tuple_val(after_key(ts, ascii("shape")))) # ---- reading the elements ---- # how a stored element becomes a cell: its kind (f, i, u, b), its size in bytes, and the dtype it loads as type Elt is Data: Elt{kd: U32, size: Nat, big: Bool, dt: S.DType} def kind_of(+k: U32, +n: Nat, +big: Bool) -> Maybe<&2, Elt>: Bool.pick(Maybe<&2, Elt>, U32.is_eq(k, 102), Bool.pick(Maybe<&2, Elt>, Bool.or(Nat.is_eq(n, 2n), Nat.is_eq(n, 4n)), Some{Elt{k, n, big, S.DF32{}}}, Bool.pick(Maybe<&2, Elt>, Nat.is_eq(n, 8n), Some{Elt{k, n, big, S.DF64{}}}, None{})), Bool.pick(Maybe<&2, Elt>, U32.is_eq(k, 105), Bool.pick(Maybe<&2, Elt>, Bool.or(Bool.or(Nat.is_eq(n, 1n), Nat.is_eq(n, 2n)), Bool.or(Nat.is_eq(n, 4n), Nat.is_eq(n, 8n))), Some{Elt{k, n, big, S.DI32{}}}, None{}), Bool.pick(Maybe<&2, Elt>, U32.is_eq(k, 117), Bool.pick(Maybe<&2, Elt>, Nat.is_eq(n, 1n), Some{Elt{k, n, big, S.DU8{}}}, Bool.pick(Maybe<&2, Elt>, Nat.is_eq(n, 2n), Some{Elt{k, n, big, S.DI32{}}}, Bool.pick(Maybe<&2, Elt>, Bool.or(Nat.is_eq(n, 4n), Nat.is_eq(n, 8n)), Some{Elt{k, n, big, S.DU32{}}}, None{}))), Bool.pick(Maybe<&2, Elt>, Bool.and(U32.is_eq(k, 98), Nat.is_eq(n, 1n)), Some{Elt{k, n, big, S.DBool{}}}, None{})))) # descr: a byte order (<, >, =, | or none), a kind letter, a size in bytes def num_go(bs: List<&2, U32>, +acc: Nat) -> Nat: match bs: case []: acc case +b <> t: num_go(t, Nat.add(Nat.mul(acc, 10n), U32.to_nat((b - 48 : U32)))) def num_of(bs: List<&2, U32>) -> Nat: num_go(bs, 0n) def parse_descr(d: List<&2, U32>) -> Maybe<&2, Elt>: match d: case +o <> +k <> +rest: Bool.pick(Maybe<&2, Elt>, Bool.or(Bool.or(U32.is_eq(o, 60), U32.is_eq(o, 62)), Bool.or(U32.is_eq(o, 61), U32.is_eq(o, 124))), kind_of(k, num_of(rest), U32.is_eq(o, 62)), kind_of(o, num_of(k <> rest), False{})) case _: None{} # the element's bytes, lowest first def ordered(+big: Bool, +bs: List<&2, U32>) -> List<&2, U32>: Bool.pick(List<&2, U32>, big, List.reverse(&2, U32, bs), bs) def w4(+bs: List<&2, U32>) -> U32: (bnth(bs, 0n) + (bnth(bs, 1n) * 256 : U32) + (bnth(bs, 2n) * 65536 : U32) + (bnth(bs, 3n) * 16777216 : U32) : U32) def w2(+bs: List<&2, U32>) -> U32: (bnth(bs, 0n) + (bnth(bs, 1n) * 256 : U32) : U32) def sext(+x: U32, +bits: U32, +n: Nat) -> U32: Bool.pick(U32, U32.is_ge(x, bits), (x - U32.from_nat(n) : U32), x) # a 64-bit integer as a 32-bit cell: signed (int64 to int32) or not (uint64 to uint32), if it fits def wide_int(+signed: Bool, +lo: U32, +hi: U32) -> Maybe<&2, U32>: Bool.pick(Maybe<&2, U32>, Bool.pick(Bool, signed, U32.is_eq(hi, Bool.pick(U32, C.is_neg(lo), 4294967295, 0)), U32.is_eq(hi, 0)), Some{lo}, None{}) # how one stored element becomes a cell, decided once per file type Mode is Data: MF16{} MF32{} MF64{} MI64{} MU64{} MI8{} MI16{} MU16{} MByte{} MBool{} MWord{} def mode_of(k: Elt) -> Mode: match k: case Elt{+kd, +size, big, dt}: Bool.pick(Mode, U32.is_eq(kd, 102), Bool.pick(Mode, Nat.is_eq(size, 2n), MF16{}, Bool.pick(Mode, Nat.is_eq(size, 4n), MF32{}, MF64{})), Bool.pick(Mode, Nat.is_eq(size, 8n), Bool.pick(Mode, U32.is_eq(kd, 105), MI64{}, MU64{}), Bool.pick(Mode, Nat.is_eq(size, 1n), Bool.pick(Mode, U32.is_eq(kd, 105), MI8{}, Bool.pick(Mode, U32.is_eq(kd, 98), MBool{}, MByte{})), Bool.pick(Mode, Nat.is_eq(size, 2n), Bool.pick(Mode, U32.is_eq(kd, 105), MI16{}, MU16{}), MWord{})))) def one(m: Maybe<&2, U32>) -> Maybe<&2, List<&2, U32>>: match m: case Some{x}: Some{[x]} case None{}: None{} # one element (its bytes lowest first) as its cells (a float64's two, the high word first), or None when it does not # fit def elem(m: Mode, +bs: List<&2, U32>) -> Maybe<&2, List<&2, U32>>: match m: case MF16{}: Some{[f16_to_f32(w2(bs))]} case MF32{}: Some{[w4(bs)]} case MF64{}: Some{[w4(bdrop(4n, bs)), w4(bs)]} case MI64{}: one(wide_int(True{}, w4(bs), w4(bdrop(4n, bs)))) case MU64{}: one(wide_int(False{}, w4(bs), w4(bdrop(4n, bs)))) case MI8{}: Some{[sext(bnth(bs, 0n), 128, 256n)]} case MI16{}: Some{[sext(w2(bs), 32768, 65536n)]} case MU16{}: Some{[w2(bs)]} case MByte{}: Some{[bnth(bs, 0n)]} case MBool{}: Some{[C.b2u(U32.is_ne(bnth(bs, 0n), 0))]} case MWord{}: Some{[w4(bs)]} # the cells pushed onto acc (which is reversed at the end) def push(xs: List<&2, U32>, acc: List<&2, U32>) -> List<&2, U32>: match xs: case []: acc case x <> t: push(t, x <> acc) def elem_got(r: Maybe<&2, List<&2, U32>>, +i: Nat, acc: List<&2, U32>, +name: String, more: Unit -> List<&2, U32> -> Result<&2, &2, S.NdErr, List<&2, U32>>) -> Result<&2, &2, S.NdErr, List<&2, U32>>: match r: case Some{xs}: more(Unit{}, push(xs, acc)) case None{}: Fail{S.NpyValue{name, i}} def elems_go(n: Nat, +k: Mode, +size: Nat, +big: Bool, +i: Nat, +bs: List<&2, U32>, acc: List<&2, U32>, +name: String) -> Result<&2, &2, S.NdErr, List<&2, U32>>: match n: case 0n: Done{List.reverse(&2, U32, acc)} case 1n+m: elem_got(elem(k, ordered(big, btake(size, bs))), i, acc, name, u => r => elems_go(m, k, size, big, Nat.add(i, 1n), bdrop(size, bs), r, name)) def kind_size(k: Elt) -> Nat: match k: case Elt{a, n, b, d}: n def kind_big(k: Elt) -> Bool: match k: case Elt{a, n, b, d}: b def kind_dt(k: Elt) -> S.DType: match k: case Elt{a, n, b, d}: d # ---- reading the file ---- def fortran_fix(f: Bool, a: NP.ND) -> NP.ND: match f: case True{}: NP.t(a) case False{}: a def shaped(r: Result<&2, &2, S.NdErr, List<&2, U32>>, +dt: S.DType, +s: List<&2, Nat>, +fortran: Bool) -> Result<&1, &1, S.NdErr, NP.ND>: match r: case Done{cells}: Done{fortran_fix(fortran, NP.ND{dt, Bool.pick(List<&2, Nat>, fortran, List.reverse(&2, Nat, s), s), T.from_rows(NP.ps(dt, Bool.pick(List<&2, Nat>, fortran, List.reverse(&2, Nat, s), s)), cells)})} case Fail{e}: Fail{e} # a Fortran-order array is stored as its transpose in C order def enough(+need: Nat, +have: Nat) -> Bool: Nat.is_le(need, have) def kind_go(ok: Bool, +k: Elt, +d: List<&2, U32>, +f: Bool, +s: List<&2, Nat>, +data: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match ok: case True{}: shaped(elems_go(S.size(s), mode_of(k), kind_size(k), kind_big(k), 0n, data, [], text(d)), kind_dt(k), s, f) case False{}: Fail{S.BadNpy{"the file ends before its data does"}} def with_kind(m: Maybe<&2, Elt>, h: Hdr, +data: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match m h: case Some{+k} Hdr{+d, +f, +s}: kind_go(enough(Nat.mul(S.size(s), kind_size(k)), List.length(&2, U32, data)), k, d, f, s, data) case None{} Hdr{d, f, s}: Fail{S.NpyDType{text(d)}} def hdr_descr(h: Hdr) -> List<&2, U32>: match h: case Hdr{d, f, s}: d def with_header(r: Result<&2, &2, S.NdErr, Hdr>, +data: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match r: case Done{+h}: with_kind(parse_descr(hdr_descr(h)), h, data) case Fail{e}: Fail{e} def body(+start: Nat, +hlen: Nat, +bs: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: with_header(header(lex(btake(hlen, bdrop(start, bs)))), bdrop(Nat.add(start, hlen), bs)) def v_two(ok: Bool, +v: U32, +bs: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match ok: case True{}: body(12n, U32.to_nat(w4(bdrop(8n, bs))), bs) case False{}: Fail{S.BadNpy{"unknown format version " ++ U32.show(v)}} def v_one(is1: Bool, +v: U32, +bs: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match is1: case True{}: body(10n, U32.to_nat(w2(bdrop(8n, bs))), bs) case False{}: v_two(Bool.or(U32.is_eq(v, 2), U32.is_eq(v, 3)), v, bs) def magic_ok(m: Bool, +bs: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: match m: case True{}: v_one(U32.is_eq(bnth(bs, 6n), 1), bnth(bs, 6n), bs) case False{}: Fail{S.BadNpy{"not a .npy file (no \\x93NUMPY at the start)"}} # the array in a .npy file's bytes def from_npy(+bs: List<&2, U32>) -> Result<&1, &1, S.NdErr, NP.ND>: magic_ok(bytes_eq(btake(6n, bs), [147, 78, 85, 77, 80, 89]), bs)