forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB09cb0afTahinli2 months ago2549 commits

learn11.py137 lines, 4.3 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Codebook 11 (escape) and the scalefactor codebook.
3
4cb11: an all-ones filler makes the escape's unary length run away, so the
5filler is `1^6 0` repeated -- bounded escapes -- and probes that land their
6END element on one of those zeros are retried at another phase.
7
8sfb: the probe sits in the scale_factor_data field of a one-band frame whose
9spectral field is the all-ones filler; the band's scalefactor is read back from
10the dequantised magnitudes (|X| = x^(4/3) * 2^((sf-100)/4), x integral).
11"""
12
13import json
14import os
15import subprocess
16import sys
17
18import numpy as np
19
20import aacprobe as A
21import learn as L
22
23FILLERS = [([1] * k + [0]) * (140 // (k + 1)) for k in (12, 20, 9, 6, 16, 24, 7, 30)]
24
25
26def eval_cb11(nodes, cache):
27 todo = [b for b in nodes if b not in cache]
28 pending = list(todo)
29 for filler in FILLERS:
30 if not pending:
31 break
32 nxt = []
33 for i in range(0, len(pending), 400):
34 chunk = pending[i : i + 400]
35 res = L.run_batch(11, chunk, filler)
36 for b, r in zip(chunk, res):
37 if r is None:
38 nxt.append(b)
39 else:
40 cache[b] = tuple(min(abs(v), 16) for v in r[:2])
41 pending = nxt
42 for b in pending:
43 cache[b] = None
44
45
46def learn_cb11():
47 cache = {}
48 codewords = {}
49 frontier = [()]
50 depth = 0
51 while frontier and depth < 32:
52 eval_cb11(frontier + [b + (0,) for b in frontier], cache)
53 nxt = []
54 for b in frontier:
55 g, g0 = cache[b], cache[b + (0,)]
56 if g is None or g0 is None:
57 print(" UNRESOLVED", b, file=sys.stderr)
58 continue
59 if g == g0:
60 codewords[b] = g
61 else:
62 nxt += [b + (0,), b + (1,)]
63 frontier = nxt
64 depth += 1
65 print(f" cb11 depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
66 file=sys.stderr)
67 return codewords
68
69
70# --- scalefactor codebook ---------------------------------------------------
71
72
73def sf_batch(probes, tag=None):
74 """Scalefactor of the second coded band, one frame per probe."""
75 frames = [A.probe_frame(3, [0] + list(p), [1] * 96, gg=160, max_sfb=2) for p in probes]
76 out = []
77 for blk in L._blocks(frames):
78 if blk is None:
79 out.append(None)
80 continue
81 peak = float(np.abs(L.spectrum(blk)[4:8]).max())
82 if peak < 1e-9:
83 out.append(None)
84 continue
85 # |X| = x^(4/3) * 2^((sf-100)/4) with x in {1, 2} (codebook 3, lav 2);
86 # only one of the two makes sf integral.
87 best = None
88 for x in (1, 2):
89 sf = 100 + 4 * np.log2(peak / x ** (4 / 3))
90 if abs(sf - round(sf)) < 0.02:
91 best = int(round(sf))
92 out.append(best)
93 return out
94
95
96def learn_sf():
97 cache = {}
98
99 def evaluate(nodes):
100 todo = [b for b in nodes if b not in cache]
101 for i in range(0, len(todo), 400):
102 chunk = todo[i : i + 400]
103 for b, r in zip(chunk, sf_batch(chunk)):
104 cache[b] = r
105
106 codewords = {}
107 frontier = [()]
108 depth = 0
109 while frontier and depth < 32:
110 evaluate(frontier + [b + (0,) for b in frontier])
111 nxt = []
112 for b in frontier:
113 g, g0 = cache[b], cache[b + (0,)]
114 if g is not None and g == g0:
115 codewords[b] = g
116 else:
117 nxt += [b + (0,), b + (1,)]
118 frontier = nxt
119 depth += 1
120 print(f" sfb depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
121 file=sys.stderr)
122 return codewords
123
124
125if __name__ == "__main__":
126 if sys.argv[1] == "11":
127 cw = learn_cb11()
128 print(f"cb11: {len(cw)} codewords, {len(set(cw.values()))} tuples, "
129 f"kraft={L.kraft(cw):.6f}")
130 json.dump({"".join(map(str, b)): list(t) for b, t in cw.items()},
131 open("cb11.json", "w"))
132 else:
133 cw = learn_sf()
134 print(f"sfb: {len(cw)} codewords, {len(set(cw.values()))} values, "
135 f"kraft={L.kraft(cw):.6f}, range={min(cw.values())}..{max(cw.values())}")
136 json.dump({"".join(map(str, b)): v for b, v in cw.items()},
137 open("sfb.json", "w"))