62 std::string escape(
const std::string_view text)
65 for (
const char c : text)
68 case '&': result +=
"&";
break;
69 case '<': result +=
"<";
break;
70 case '>': result +=
">";
break;
71 case '"': result +=
""";
break;
72 case '\'': result +=
"'";
break;
83 std::string message_label(
const std::string_view text)
86 for (
const unsigned char byte : text)
87 if (byte >= 32
and byte <= 126)
88 result += static_cast<char>(byte);
99 void draw_tree(std::ostream &
out,
const Snapshot &tree,
const int current)
101 const double actual_width = 120 + 108 * (tree.leaf_count - 1);
102 const double width = std::max(540.0, actual_width);
103 const double height = 100 + 86 * tree.depth;
104 std::string current_code;
105 for (
const auto &node : tree.
nodes)
107 current_code = node.
code;
108 out <<
"<svg class='tree' role='img' aria-label='Huffman tree after the update' "
109 <<
"viewBox='0 0 " << width <<
' ' << height <<
"' style='min-width:" << width
110 <<
"px'><title>Current adaptive Huffman tree</title>"
111 <<
"<desc>Left edges are zero, right edges are one. Node weights are frequencies. "
112 <<
"NYT represents unseen bytes. The last byte's new path is highlighted.</desc>"
113 <<
"<g transform='translate(" << (width - actual_width) / 2 <<
",0)'>";
114 for (
const auto &parent : tree.
nodes)
115 for (int bit = 0; bit < 2; ++bit)
116 if (parent.children[bit] != -1)
118 const auto &child = tree.nodes[parent.children[bit]];
119 const bool active = not current_code.empty()
and current_code.starts_with(child.code);
120 const double mid_y = (parent.y + child.y) / 2;
121 out <<
"<path class='edge" << (active ?
" active" :
"") <<
"' d='M"
122 << parent.x <<
' ' << parent.y + 18 <<
" C" << parent.x <<
' ' << mid_y
123 <<
' ' << child.x <<
' ' << mid_y <<
' ' << child.x <<
' ' << child.y - 22
124 <<
"'/><text class='edge-label' x='" << (parent.x + child.x) / 2 + (bit ? 10 : -10)
125 <<
"' y='" << mid_y - 4 <<
"'>" << bit <<
"</text>";
127 for (
const auto &node : tree.
nodes)
129 const bool leaf = node.symbol != -2;
130 const auto label = node.symbol == -1 ? std::string(
"NYT") :
132 out <<
"<g class='node" << (leaf ?
" leaf" :
"") << (node.symbol == -1 ?
" nyt" :
"")
133 << (leaf
and node.symbol ==
current ?
" current" :
"")
134 <<
"' transform='translate(" << node.x <<
',' << node.
y <<
")'>"
135 <<
"<title>" << escape(label) <<
": frequency " << node.weight
136 <<
", path " << (node.
code.empty() ?
"root" : node.
code) <<
"</title>";
138 out <<
"<rect x='-35' y='-23' width='70' height='51' rx='9'/>"
139 <<
"<text class='symbol' y='-2'>" << escape(label) <<
"</text>"
140 <<
"<text class='weight' y='17'>" << node.weight <<
"</text>";
142 out <<
"<circle r='19'/><text class='sum' y='5'>" << label <<
"</text>";
154 void write_frame(std::ostream &
out,
const Frame &frame,
const size_t step,
155 const size_t initial_step)
157 out <<
"<article class='frame' data-step='" << step <<
"'"
158 << (step == initial_step ?
"" :
" hidden") <<
"><div class='metrics'>"
159 <<
"<div><span>Bytes processed</span><strong>" << step <<
"</strong></div>"
160 <<
"<div><span>Original bits</span><strong>" << 8 * step <<
"</strong></div>"
161 <<
"<div><span>Encoded bits</span><strong>" << frame.total_bits <<
"</strong></div>"
162 <<
"<div><span>Known bytes</span><strong>" << frame.tree.leaf_count - 1
163 <<
"</strong></div></div><div class='workspace'><section class='tree-panel'>"
164 <<
"<div class='panel-heading'><h2>Tree after the update</h2><span class='step-tag'>"
165 << (step == 0 ?
"Initial model" :
"Byte " +
std::
to_string(step))
166 <<
"</span></div><div class='tree-wrap'>";
167 draw_tree(
out, frame.tree, step == 0 ? -2 : frame.byte);
168 out <<
"</div><p class='caption'>0 = left 1 = right Weight = frequency"
169 <<
"<br>Highlight: the latest byte's path in the updated tree.</p></section>"
170 <<
"<aside><section class='event'><span class='eyebrow'>";
172 out <<
"BEFORE THE FIRST BYTE</span><h2>A single NYT leaf.</h2>"
173 <<
"<p>No frequencies are known yet. The first byte will travel as eight literal bits.</p>";
176 out << (frame.first_appearance ?
"FIRST APPEARANCE" :
"KNOWN BYTE")
177 <<
"</span><h2>Byte <code>" << escape(
byte_label(frame.byte)) <<
"</code></h2>"
178 <<
"<p>Bits sent <em>before</em> the tree update:</p>"
179 <<
"<div class='bit-fields'><div><span>"
180 << (frame.first_appearance ?
"NYT path" :
"Leaf path") <<
"</span><code>"
181 << (frame.path.empty() ?
"root" : frame.path) <<
"</code></div>";
182 if (frame.first_appearance)
183 out <<
"<div class='literal'><span>8 literal bits</span><code>" << frame.literal
185 out <<
"</div><p class='event-total'>" << frame.path.size() + frame.literal.size()
186 <<
" bits transmitted for this byte.</p>";
188 out <<
"</section><section class='codes'><h2>Codes now</h2>"
189 <<
"<table><thead><tr><th>Byte</th><th>Count</th><th>Path</th></tr></thead><tbody>";
190 for (
const auto &node : frame.tree.
nodes)
191 if (node.symbol != -2)
192 out <<
"<tr" << (step != 0
and node.symbol == frame.byte ?
" class='selected'" :
"")
193 <<
"><td>" << escape(node.symbol == -1 ?
"NYT" :
194 byte_label(static_cast<unsigned char>(node.symbol)))
195 <<
"</td><td>" << node.weight <<
"</td><td><code>"
196 << (node.
code.empty() ?
"root" : node.
code) <<
"</code></td></tr>";
197 out <<
"</tbody></table></section></aside></div></article>";
206 if (frames.
size() == 1)
210 for (
size_t i = 1; i < frames.
size(); ++i)
211 maximum = std::max(maximum, frames[i].path.size() + frames[i].literal.size());
212 const double width = std::max(600.0, 60.0 +
count * 32.0);
213 const double pitch = (width - 80) /
count;
214 const double scale = 106.0 / maximum;
215 out <<
"<section class='costs'><h2>Cost of each byte</h2>"
216 <<
"<div class='chart-wrap'><svg class='cost-chart' role='img' "
217 <<
"aria-label='Transmitted bits per byte compared with an eight-bit literal' viewBox='0 0 "
218 << width <<
" 180'><title>Actual encoded bits per byte</title>"
219 <<
"<text class='axis-label' x='8' y='15'>Bits / byte</text>"
220 <<
"<line class='baseline' x1='44' x2='" << width - 10 <<
"' y1='"
221 << 135 - 8 * scale <<
"' y2='" << 135 - 8 * scale <<
"'/>"
222 <<
"<text class='axis-label' x='18' y='" << 139 - 8 * scale <<
"'>8</text>";
223 for (
size_t i = 1; i < frames.
size(); ++i)
225 const auto &frame = frames[i];
226 const size_t cost = frame.path.
size() + frame.literal.size();
227 const double x = 50 + (i - 1) * pitch;
228 const double height = cost * scale;
229 out <<
"<g class='cost-bar' data-index='" << i <<
"'><title>Byte " << i <<
": "
230 << escape(
byte_label(frame.byte)) <<
", " << cost <<
" bits</title>"
231 <<
"<rect x='" << x <<
"' y='" << 135 - height <<
"' width='"
232 << pitch * .58 <<
"' height='" << height <<
"' rx='2'/>"
233 <<
"<text class='cost-value' x='" << x + pitch * .29 <<
"' y='"
234 << 128 - height <<
"'>" << cost <<
"</text><text class='cost-byte' x='"
235 << x + pitch * .29 <<
"' y='152'>" << escape(
byte_label(frame.byte))
238 out <<
"<text class='axis-label' x='" << width / 2 <<
"' y='176'>Byte position in the message</text>"
239 <<
"</svg></div><p class='caption'>Dashed line: 8-bit literal. Bright bars: bytes already processed. "
240 <<
"Source: actual Aleph FGK encoding of this message.</p></section>";
248 void write_scenario(std::ostream &
out,
const std::string_view input,
const size_t index)
251 const size_t initial = std::min<size_t>(4, input.size());
252 out <<
"<div class='scenario' data-case='" << index <<
"' data-length='" << input.size()
253 <<
"' data-current='" << initial <<
"'" << (index == 0 ?
"" :
" hidden")
254 <<
"><div class='message' aria-label='Jump to a byte'><button type='button' data-jump='0' "
255 <<
"aria-label='Show the initial tree'>Start</button>";
256 for (
size_t i = 0; i < input.size(); ++i)
257 out <<
"<button type='button' data-jump='" << i + 1 <<
"' aria-label='Show byte " << i + 1
258 <<
"'>" << escape(
byte_label(
static_cast<unsigned char>(input[i]))) <<
"</button>";
260 for (
size_t i = 0; i < frames.
size(); ++i)
261 write_frame(
out, frames[i], i, initial);
262 write_cost_chart(
out, frames);
272 out << R
"HTML(<!doctype html>
273<html lang="en"><head><meta charset="utf-8">
274<meta name="viewport" content="width=device-width,initial-scale=1">
275<title>Aleph / Adaptive Huffman, one byte at a time</title>
277:root{color-scheme:light;--bg:#f6f5f1;--paper:#fff;--ink:#24342f;--muted:#62716a;--line:#dbe1da;--accent:#147764;--soft:#e5f3ec;--literal:#9b601b;--literal-bg:#f9efdf;--node:#f0f2ed}
278@media(prefers-color-scheme:dark){:root{color-scheme:dark;--bg:#16211d;--paper:#1e2c26;--ink:#e3ebe4;--muted:#afbeb3;--line:#42554b;--accent:#80d3b3;--soft:#243f34;--literal:#f2c387;--literal-bg:#403322;--node:#2b3931}}
279*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,sans-serif}main{max-width:1200px;margin:auto;padding:44px 32px}h1,h2,p{margin:0}h1{font-size:clamp(28px,4vw,42px);font-weight:650;letter-spacing:-1.4px;line-height:1.15;margin:12px 0}h2{font-size:16px;font-weight:650}p{color:var(--muted)}.brand,.eyebrow{font-size:11px;letter-spacing:2px;font-weight:750;color:var(--accent)}.intro{max-width:700px;font-size:16px}.hero{display:flex;justify-content:space-between;gap:30px;align-items:flex-start;margin-bottom:30px}.verified{white-space:nowrap;border:1px solid var(--line);border-radius:24px;padding:7px 12px;font-size:12px;color:var(--accent);margin-top:4px}button,select,input{font:inherit}button,select{color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:8px 12px}button{cursor:pointer}button:hover{background:var(--soft)}button:disabled{opacity:.35;cursor:default}button:focus-visible,select:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.controls{display:flex;align-items:center;gap:10px;flex-wrap:wrap;border-block:1px solid var(--line);padding:16px 0}.controls label{font-size:12px;color:var(--muted)}.controls select{max-width:100%}.transport{display:flex;gap:6px;margin-left:auto}#play{background:var(--accent);color:var(--paper);border-color:var(--accent);min-width:70px}.slider-row{display:flex;align-items:center;gap:16px;margin:18px 0 14px}.slider-row label{font-size:13px;white-space:nowrap}input[type=range]{flex:1;min-width:60px;accent-color:var(--accent)}output{font:13px ui-monospace,monospace;min-width:62px;text-align:right}.message{display:flex;gap:5px;overflow-x:auto;padding:6px 0 20px}.message button{font:14px ui-monospace,monospace;min-width:30px;padding:7px 9px;white-space:nowrap}.message button.past{background:var(--soft)}.message button[aria-pressed=true]{background:var(--accent);color:var(--paper);border-color:var(--accent)}.metrics{display:flex;gap:32px;padding:12px 0 23px}.metrics div{min-width:90px}.metrics span{display:block;font-size:12px;color:var(--muted)}.metrics strong{font-size:28px;font-weight:600;font-variant-numeric:tabular-nums}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 265px;gap:22px;align-items:start}.tree-panel{background:var(--paper);border:1px solid var(--line);border-radius:12px;overflow:hidden}.panel-heading{display:flex;justify-content:space-between;gap:16px;align-items:center;padding:20px 22px}.step-tag{font-size:12px;color:var(--muted)}.tree-wrap{overflow:auto;padding:4px 12px}.tree{width:100%;display:block;max-height:650px}.edge{fill:none;stroke:var(--line);stroke-width:1.5}.edge.active{stroke:var(--accent);stroke-width:2.4}.edge-label,.tree text{font-family:ui-monospace,monospace;text-anchor:middle;fill:var(--muted);font-size:12px}.node circle,.node rect{fill:var(--node);stroke:var(--line);stroke-width:1}.node .symbol{fill:var(--ink);font-weight:650;font-size:14px}.node .sum{fill:var(--ink);font-size:14px}.node .weight{font-size:11px}.node.current rect{fill:var(--soft);stroke:var(--accent);stroke-width:1.7}.node.nyt rect{fill:var(--literal-bg);stroke:var(--literal);stroke-dasharray:4 3}.caption{font-size:11px;line-height:1.6;padding:14px 22px 18px}.event{padding:0 0 22px;border-bottom:1px solid var(--line)}.event h2{font-size:24px;margin:8px 0}.event p{font-size:13px}.event code,.codes code{font-family:ui-monospace,monospace}.bit-fields{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0}.bit-fields div{padding:10px 12px;background:var(--soft);border-radius:6px}.bit-fields span{display:block;font-size:10px;color:var(--muted);margin-bottom:3px}.bit-fields code{font-size:16px;color:var(--accent);overflow-wrap:anywhere}.bit-fields .literal{background:var(--literal-bg)}.literal code{color:var(--literal)}.event-total{font-size:12px!important}.codes{padding-top:20px}.codes h2{margin-bottom:9px}table{width:100%;border-collapse:collapse;font-size:12px}th,td{padding:7px 5px;text-align:left;border-bottom:1px solid var(--line)}th{font-weight:500;color:var(--muted)}th:nth-child(2),td:nth-child(2){text-align:right;padding-right:14px}td:last-child{overflow-wrap:anywhere;max-width:130px}.selected td{background:var(--soft)}.costs{margin-top:25px;border-top:1px solid var(--line);padding-top:20px}.costs h2{margin-bottom:12px}.chart-wrap{overflow:auto}.cost-chart{width:100%;min-width:550px;max-height:220px;display:block}.baseline{stroke:var(--muted);stroke-width:1;stroke-dasharray:5 4}.cost-bar rect{fill:var(--accent)}.cost-bar.future{opacity:.25}.cost-value,.cost-byte,.axis-label{font:11px ui-monospace,monospace;fill:var(--muted)}.cost-value,.cost-byte{text-anchor:middle}.cost-value{fill:var(--ink)}.costs .caption{padding-left:0}footer{border-top:1px solid var(--line);padding-top:18px;margin-top:18px;font-size:12px;color:var(--muted)}[hidden]{display:none!important}
280@media(max-width:800px){main{padding:26px 16px}.hero{display:block}.verified{display:inline-block;margin-top:18px}.workspace{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:22px}.event{border:0}.codes{padding:0}.metrics{gap:18px;flex-wrap:wrap}.metrics div{min-width:80px}.controls{align-items:flex-end}.transport{margin-left:0}.tree{max-height:550px}}
281@media(max-width:430px){aside{grid-template-columns:1fr}.metrics strong{font-size:24px}.codes{padding-bottom:10px}.hero h1{letter-spacing:-.8px}}
282</style></head><body><main id="huffman-gallery">
283<header class="hero"><div><div class="brand">ALEPH / ALGORITHM EXPLORER</div>
284<h1>Watch the code learn.</h1><p class="intro">One byte arrives. A code is sent. The tree changes. Step through adaptive Huffman coding and see exactly what both peers know.</p></div>
285<span class="verified">Every step round-trip verified</span></header>
286<div class="controls"><label for="scenario">Message</label><select id="scenario">
288 for (
size_t i = 0; i < messages.
size(); ++i)
289 out <<
"<option value='" << i <<
"'>"
290 << (messages[i].empty() ?
"Empty message" : escape(message_label(messages[i]))) <<
"</option>";
291 out << R
"HTML(</select><div class="transport"><button id="previous" type="button" aria-label="Previous byte">Previous</button><button id="play" type="button" aria-pressed="false">Play</button><button id="next" type="button" aria-label="Next byte">Next</button></div></div>
292<div class="slider-row"><label for="step">Processed bytes</label><input id="step" type="range" min="0" value="0" max="0"><output id="position" for="step" aria-live="polite"></output></div>
294 for (
size_t i = 0; i < messages.
size(); ++i)
295 write_scenario(
out, messages[i], i);
296 out << R
"HTML(<footer>FGK / Faller–Gallager–Knuth. First appearance = NYT path + 8 literal bits; known byte = current leaf path. Tree and code table show the state <strong>after</strong> the update. There is no tree header or end marker: preserve the exact bit count.</footer>
300 const root = document.getElementById('huffman-gallery');
301 const cases = [...root.querySelectorAll('.scenario')];
302 const select = root.querySelector('#scenario');
303 const slider = root.querySelector('#step');
304 const position = root.querySelector('#position');
305 const previous = root.querySelector('#previous');
306 const next = root.querySelector('#next');
307 const play = root.querySelector('#play');
309 const currentCase = () => cases[Number(select.value)];
311 if (timer !== null) clearInterval(timer);
313 play.textContent = 'Play';
314 play.setAttribute('aria-pressed', 'false');
316 function show(value) {
317 const current = currentCase();
318 const length = Number(current.dataset.length);
319 const step = Math.max(0, Math.min(length, Number(value)));
320 current.dataset.current = String(step);
321 cases.forEach(item => { item.hidden = item !== current; });
322 current.querySelectorAll('.frame').forEach(frame => {
323 frame.hidden = Number(frame.dataset.step) !== step;
325 current.querySelectorAll('[data-jump]').forEach(button => {
326 const at = Number(button.dataset.jump);
327 button.setAttribute('aria-pressed', String(at === step));
328 button.classList.toggle('past', at > 0 && at < step);
330 current.querySelectorAll('.cost-bar').forEach(bar => {
331 bar.classList.toggle('future', Number(bar.dataset.index) > step);
333 slider.max = String(length);
334 slider.value = String(step);
335 position.textContent = `${step} / ${length}`;
336 previous.disabled = step === 0;
337 next.disabled = step === length;
338 play.disabled = length === 0;
339 if (step === length) stop();
341 slider.addEventListener('input', () => { stop(); show(slider.value); });
342 select.addEventListener('change', () => { stop(); show(currentCase().dataset.current); });
343 previous.addEventListener('click', () => { stop(); show(Number(slider.value) - 1); });
344 next.addEventListener('click', () => { stop(); show(Number(slider.value) + 1); });
345 root.addEventListener('click', event => {
346 const button = event.target.closest('[data-jump]');
347 if (button) { stop(); show(button.dataset.jump); }
349 play.addEventListener('click', () => {
350 if (timer !== null) { stop(); return; }
351 if (Number(slider.value) === Number(slider.max)) show(0);
352 play.textContent = 'Pause';
353 play.setAttribute('aria-pressed', 'true');
354 timer = setInterval(() => show(Number(slider.value) + 1), 950);
356 document.addEventListener('visibilitychange', () => { if (document.hidden) stop(); });
357 show(currentCase().dataset.current);
359</script></body></html>
369int main(
int argc,
char *argv[])
373 if (argc > 1
and std::string_view(argv[1]) ==
"--help")
375 std::cout <<
"Usage: adaptive_huffman_visual_example [output.html] [text]\n"
376 <<
"Text may contain at most 32 bytes; default: three illustrated scenarios.\n";
383 const std::string_view input(argv[2]);
385 messages.
append(std::string(input));
389 messages.
append(
"ABRACADABRA");
390 messages.
append(
"BANANA BANDANA");
391 messages.
append(
"AAAAAAAABBBBBBBBBBBBBBBB");
393 const std::string path = argc > 1 ? argv[1] :
"adaptive_huffman_gallery.html";
394 std::ofstream
output(path);
396 output.imbue(std::locale::classic());
397 write_gallery(
output, messages);
400 std::cout <<
"Generated adaptive Huffman gallery: " << path <<
'\n'
401 <<
"Scenarios: " << messages.
size() <<
'\n'
402 <<
"All frames verified against the real online encoder and decoder.\n"
403 <<
"Open the HTML file in a browser; it works entirely offline.\n";
406 catch (
const std::exception &
error)
408 std::cerr <<
error.what() <<
'\n';
One-pass adaptive Huffman coding of bytes using FGK updates.
Shared, public-API-only traces for the adaptive Huffman examples.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
T & append(const T &data)
Append a copy of data
DynArray< Graph::Node * > nodes
decltype(auto) current(It &it) noexcept(current_is_noexcept< It >)
Current item of an iterator that is positioned on one.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
and
Check uniqueness with explicit hash + equality functors.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Aleph::Array< Frame > trace(const std::string_view input)
Record an actual online round trip, starting with the empty model.
std::string byte_label(const unsigned char byte)
Return an unambiguous, terminal-safe label for a byte.
One verified encoding event, plus the tree after the event.
A complete tree for one externally observable encoder state.
static void draw_tree(Node *root)
Dynamic array container with automatic resizing.