Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
adaptive_huffman_demo_support.H
Go to the documentation of this file.
1/*
2 Aleph-w: Data structures & Algorithms
3 Copyright (c) 2026 Leandro Rabindranath Leon
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 SOFTWARE.
22*/
23
31#ifndef ALEPH_ADAPTIVE_HUFFMAN_DEMO_SUPPORT_H
32#define ALEPH_ADAPTIVE_HUFFMAN_DEMO_SUPPORT_H
33
34#include <Adaptive_Huffman.H>
35#include <ah-errors.H>
36#include <tpl_array.H>
37
38#include <cstddef>
39#include <cstdint>
40#include <ostream>
41#include <string>
42#include <string_view>
43#include <utility>
44
46{
51 inline std::string byte_label(const unsigned char byte)
52 {
53 switch (byte)
54 {
55 case 0: return "NUL";
56 case '\n': return "LF";
57 case '\r': return "CR";
58 case '\t': return "TAB";
59 case ' ': return "SPACE";
60 default:
61 if (byte >= 33 and byte <= 126)
62 return std::string(1, static_cast<char>(byte));
63 constexpr char hex[] = "0123456789ABCDEF";
64 std::string label = "0x";
65 label += hex[byte >> 4];
66 label += hex[byte & 15];
67 return label;
68 }
69 }
70
76 inline std::string next_code(const Aleph::Adaptive_Huffman_Encoder &encoder,
77 const unsigned char byte)
78 {
79 auto copy = encoder;
81 copy.encode(byte, bits);
82 return bits.get_bit_str();
83 }
84
87 {
88 int children[2] = {-1, -1};
89 int symbol = -2;
90 std::uint64_t weight = 0;
91 std::string code;
92 double x = 0;
93 double y = 0;
94 };
95
97 struct Snapshot
98 {
100 size_t leaf_count = 0;
101 size_t depth = 0;
102 };
103
110 inline void insert_code(Snapshot &tree, const std::string &code,
111 const int symbol, const std::uint64_t weight)
112 {
113 int node = 0;
114 tree.nodes[node].weight += weight;
115 for (const char digit : code)
116 {
117 const int bit = digit - '0';
118 if (tree.nodes[node].children[bit] == -1)
119 {
120 const int child = static_cast<int>(tree.nodes.size());
121 Display_Node added;
122 added.code = tree.nodes[node].code + digit;
123 tree.nodes.append(added);
124 // append() may reallocate: reacquire the parent by index.
125 tree.nodes[node].children[bit] = child;
126 }
127 node = tree.nodes[node].children[bit];
128 tree.nodes[node].weight += weight;
129 }
130 tree.nodes[node].symbol = symbol;
131 }
132
139 inline void position_nodes(Snapshot &tree, const int node, const size_t depth,
140 size_t &next_leaf)
141 {
142 auto &entry = tree.nodes[node];
143 entry.y = 48 + 86 * depth;
144 if (depth > tree.depth)
145 tree.depth = depth;
146 if (entry.symbol != -2)
147 entry.x = 60 + 108 * next_leaf++;
148 else
149 {
150 position_nodes(tree, entry.children[0], depth + 1, next_leaf);
151 position_nodes(tree, entry.children[1], depth + 1, next_leaf);
152 entry.x = (tree.nodes[entry.children[0]].x +
153 tree.nodes[entry.children[1]].x) / 2;
154 }
155 }
156
163 {
164 Snapshot result;
165 result.nodes.append(Display_Node{});
166 int unseen = -1;
167 for (int byte = 0; byte < 256; ++byte)
168 {
169 const auto value = static_cast<unsigned char>(byte);
170 const auto frequency = encoder.frequency(value);
171 if (frequency != 0)
172 insert_code(result, next_code(encoder, value), byte, frequency);
173 else if (unseen == -1)
174 unseen = byte;
175 }
176 if (unseen != -1)
177 {
178 auto code = next_code(encoder, static_cast<unsigned char>(unseen));
179 code.resize(code.size() - 8); // Remove the literal; retain the NYT path.
180 insert_code(result, code, -1, 0);
181 }
182 else
183 {
184 // With all bytes present, NYT is the single unused branch of the trie.
185 const size_t count = result.nodes.size();
186 bool found = false;
187 for (size_t i = 0; i < count and not found; ++i)
188 if (result.nodes[i].symbol == -2)
189 for (int bit = 0; bit < 2; ++bit)
190 if (result.nodes[i].children[bit] == -1)
191 {
192 const auto code = result.nodes[i].code + static_cast<char>('0' + bit);
193 insert_code(result, code, -1, 0);
194 found = true;
195 break;
196 }
197 ah_logic_error_unless(found) << "Display tree is missing its NYT branch";
198 }
199
200 for (const auto &node : result.nodes)
201 if (node.symbol == -2)
202 {
203 ah_logic_error_if(node.children[0] == -1 or node.children[1] == -1)
204 << "Display tree contains an incomplete internal node";
205 ah_logic_error_if(node.weight != result.nodes[node.children[0]].weight +
206 result.nodes[node.children[1]].weight)
207 << "Display tree contains inconsistent frequencies";
208 }
209 ah_logic_error_if(result.nodes[0].weight != encoder.symbols_processed())
210 << "Display tree does not represent the encoder's current state";
211 position_nodes(result, 0, 0, result.leaf_count);
212 return result;
213 }
214
216 struct Frame
217 {
218 unsigned char byte = 0;
219 bool first_appearance = false;
220 std::string path;
221 std::string literal;
222 size_t total_bits = 0;
224 };
225
231 inline Aleph::Array<Frame> trace(const std::string_view input)
232 {
233 Aleph::Array<Frame> frames;
236 Frame initial;
237 initial.tree = snapshot(encoder);
238 frames.append(std::move(initial));
239 size_t total = 0;
240 for (const unsigned char byte : input)
241 {
242 Frame frame;
243 frame.byte = byte;
244 frame.first_appearance = encoder.frequency(byte) == 0;
246 total += encoder.encode(byte, bits);
247 frame.path = bits.get_bit_str();
248 if (frame.first_appearance)
249 {
250 frame.literal = frame.path.substr(frame.path.size() - 8);
251 frame.path.resize(frame.path.size() - 8);
252 }
253 unsigned char decoded = 0;
254 for (size_t i = 0; i < bits.size(); ++i)
255 {
256 const bool ready = decoder.decode_bit(bits[i], decoded);
257 ah_logic_error_if(ready != (i + 1 == bits.size()))
258 << "A byte was emitted at the wrong bit boundary";
259 }
260 decoder.finish();
261 ah_logic_error_if(decoded != byte) << "Online Huffman round trip failed";
262 frame.total_bits = total;
263 frame.tree = snapshot(encoder);
264 frames.append(std::move(frame));
265 }
266 return frames;
267 }
268
276 inline void print_tree(std::ostream &out, const Snapshot &tree, const int node = 0,
277 const std::string &indent = " ",
278 const std::string &edge = "")
279 {
280 const auto &entry = tree.nodes[node];
281 out << indent << edge;
282 if (entry.symbol == -2)
283 out << '[' << entry.weight << ']';
284 else
285 out << (entry.symbol == -1 ? "NYT" : byte_label(static_cast<unsigned char>(entry.symbol)))
286 << " (" << entry.weight << ")";
287 out << '\n';
288 if (entry.symbol == -2)
289 {
290 const std::string next_indent = indent + (edge.empty() ? "" :
291 edge[0] == '+' ? "| " : " ");
292 print_tree(out, tree, entry.children[0], next_indent, "+-0- ");
293 print_tree(out, tree, entry.children[1], next_indent, "`-1- ");
294 }
295 }
296}
297
298#endif // ALEPH_ADAPTIVE_HUFFMAN_DEMO_SUPPORT_H
One-pass adaptive Huffman coding of bytes using FGK updates.
Exception handling system with formatted messages for Aleph-w.
#define ah_logic_error_unless(C)
Throws std::logic_error if condition does NOT hold.
Definition ah-errors.H:458
#define ah_logic_error_if(C)
Throws std::logic_error if condition holds.
Definition ah-errors.H:474
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Incremental FGK decoder accepting arbitrarily fragmented bits.
void finish() const
Verify that an externally framed message ended at a byte boundary.
bool decode_bit(const unsigned int bit, unsigned char &symbol)
Consume one bit and emit a byte if its codeword is complete.
Stateful, one-pass FGK Huffman encoder for binary byte strings.
size_t encode(const unsigned char symbol, BitArray &output)
Append the current code for one byte, then update the tree.
std::uint64_t frequency(const unsigned char symbol) const noexcept
Return the current frequency of a byte.
std::uint64_t symbols_processed() const noexcept
Return the number of bytes encoded since construction or reset.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Contiguous array of bits.
Definition bitArray.H:201
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
void position_nodes(Snapshot &tree, const int node, const size_t depth, size_t &next_leaf)
Assign inorder leaf positions and center parents over children.
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.
Snapshot snapshot(const Aleph::Adaptive_Huffman_Encoder &encoder)
Reconstruct and validate the tree using public encoder operations.
void insert_code(Snapshot &tree, const std::string &code, const int symbol, const std::uint64_t weight)
Insert a code into the display trie and accumulate its frequency.
std::string next_code(const Aleph::Adaptive_Huffman_Encoder &encoder, const unsigned char byte)
Probe a byte's code without changing the source encoder.
void print_tree(std::ostream &out, const Snapshot &tree, const int node=0, const std::string &indent=" ", const std::string &edge="")
Print a byte-labelled, edge-labelled tree using portable ASCII.
One node of a reconstructed display tree.
int children[2]
Child indices; -1 denotes absence.
int symbol
Byte value, -1 for NYT, -2 for an internal node.
std::uint64_t weight
Sum of the descendant symbol frequencies.
double x
Horizontal drawing coordinate.
One verified encoding event, plus the tree after the event.
std::string literal
Eight raw bits on a first appearance.
unsigned char byte
Byte consumed by this event.
std::string path
Tree path before the update.
bool first_appearance
Whether the byte was previously unseen.
Snapshot tree
Encoder state after the update.
size_t total_bits
Cumulative encoded length.
A complete tree for one externally observable encoder state.
size_t leaf_count
Includes the retained NYT leaf.
Aleph::Array< Display_Node > nodes
Root at index zero.
Dynamic array container with automatic resizing.