Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
adaptive_huffman_example.cc
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
36#include <Adaptive_Huffman.H>
37#include <ah-errors.H>
39
40#include <algorithm>
41#include <cstddef>
42#include <exception>
43#include <iomanip>
44#include <iostream>
45#include <string>
46#include <string_view>
47
48namespace
49{
54 void heading(const int number, const std::string_view title)
55 {
56 std::cout << '\n' << std::string(76, '=') << '\n'
57 << " " << number << " / " << title << '\n'
58 << std::string(76, '=') << "\n\n";
59 }
60
64 void demonstrate_trace(const std::string_view input)
65 {
66 using namespace adaptive_huffman_demo;
67 heading(1, "THE CODE LEARNS ONE BYTE AT A TIME");
68 std::cout << " Left edge = 0. Right edge = 1. NYT = not yet transmitted.\n"
69 << " A new byte sends the NYT path followed by its 8 literal bits.\n"
70 << " A repeated byte sends only its current tree path.\n\n";
71 const auto frames = trace(input);
72 std::cout << " " << std::left << std::setw(5) << "Step" << std::setw(8) << "Byte"
73 << std::setw(11) << "Status" << std::setw(15) << "Tree path"
74 << std::setw(12) << "Literal" << std::right << std::setw(6) << "Bits"
75 << std::setw(9) << "Total" << '\n'
76 << " " << std::string(66, '-') << '\n';
77 for (size_t i = 1; i < frames.size(); ++i)
78 {
79 const auto &frame = frames[i];
80 std::cout << " " << std::left << std::setw(5) << i
81 << std::setw(8) << byte_label(frame.byte)
82 << std::setw(11) << (frame.first_appearance ? "new / NYT" : "known")
83 << std::setw(15) << (frame.path.empty() ? "(root)" : frame.path)
84 << std::setw(12) << (frame.literal.empty() ? "-" : frame.literal)
85 << std::right << std::setw(6) << frame.path.size() + frame.literal.size()
86 << std::setw(9) << frame.total_bits << '\n';
87 }
88 std::cout << "\n Initial tree\n";
89 print_tree(std::cout, frames[0].tree);
90 if (input.size() > 3)
91 {
92 std::cout << "\n After byte 3 (weights are frequencies)\n";
93 print_tree(std::cout, frames[3].tree);
94 }
95 const auto &last = frames[frames.size() - 1];
96 std::cout << "\n Final tree\n";
97 print_tree(std::cout, last.tree);
98 std::cout << "\n Original: " << input.size() * 8 << " bits Encoded: "
99 << last.total_bits << " bits\n"
100 << " Every byte was decoded exactly on its last bit.\n"
101 << " The displayed trees are AFTER each update; transmitted paths\n"
102 << " in the table come from the tree BEFORE that update.\n";
103 }
104
106 void demonstrate_adaptation()
107 {
109 heading(2, "WHEN THE FREQUENT BYTE CHANGES");
110 std::cout << " One continuous stream, with no reset between phases.\n"
111 << " Bar scale: one # represents about 16 transmitted bits.\n\n";
114 std::string expected, decoded;
115 const std::string phases[] = {std::string(64, 'A'), std::string(128, 'B'),
116 std::string(256, 'A')};
117 for (size_t i = 0; i < 3; ++i)
118 {
119 const auto &phase = phases[i];
120 const auto byte = static_cast<unsigned char>(phase[0]);
121 const auto first_cost = next_code(encoder, byte).size();
123 encoder.encode(phase, bits);
124 decoder.decode(bits, decoded);
125 decoder.finish();
126 expected += phase;
127 ah_logic_error_if(decoded != expected) << "Distribution-change round trip failed";
128 const auto code = next_code(encoder, byte);
129 std::cout << " Phase " << i + 1 << " : " << phase.size() << " x " << phase[0]
130 << "\n Raw " << std::setw(4) << phase.size() * 8
131 << " bits -> " << std::setw(4) << bits.size() << " bits "
132 << std::string((bits.size() + 15) / 16, '#')
133 << "\n First byte: " << first_cost << " bits; next " << phase[0]
134 << " now: " << code << " (" << code.size() << " bit)"
135 << "\n Cumulative frequencies: A=" << encoder.frequency('A')
136 << ", B=" << encoder.frequency('B') << "\n\n";
137 }
138 }
139
141 void demonstrate_fragmentation()
142 {
143 heading(3, "BINARY BYTES, ARBITRARY BIT CHUNKS");
144 const std::string input("\0\xff" "A\0\n\xff\0", 7);
148 encoder.encode(input, bits);
149 std::cout << " Payload: NUL 0xFF A NUL LF 0xFF NUL\n"
150 << " Chunk widths repeat 3, 1, 7, 2, 5 bits; incomplete symbols wait.\n\n"
151 << " " << std::left << std::setw(8) << "Chunk" << std::setw(11) << "Bits"
152 << std::setw(12) << "New bytes" << "Pending symbol\n"
153 << " " << std::string(48, '-') << '\n';
154 constexpr size_t widths[] = {3, 1, 7, 2, 5};
155 std::string output;
156 size_t chunk_number = 0;
157 for (size_t offset = 0; offset < bits.size(); ++chunk_number)
158 {
159 Aleph::BitArray chunk;
160 const size_t count = std::min(widths[chunk_number % 5], bits.size() - offset);
161 for (size_t i = 0; i < count; ++i)
162 chunk.push(bits[offset + i]);
163 offset += count;
164 const size_t emitted = decoder.decode(chunk, output);
165 std::cout << " " << std::setw(8) << chunk_number + 1
166 << std::setw(11) << chunk.get_bit_str() << std::setw(12) << emitted
167 << (decoder.has_pending_symbol() ? "yes" : "no") << '\n';
168 }
169 decoder.finish();
170 ah_logic_error_if(output != input) << "Fragmented binary round trip failed";
171 std::cout << "\n All 7 binary bytes recovered exactly.\n"
172 << " Keep the exact bit count when storing or transmitting the stream.\n";
173 }
174}
175
181int main(int argc, char *argv[])
182{
183 try
184 {
185 if (argc > 1 and std::string_view(argv[1]) == "--help")
186 {
187 std::cout << "Usage: adaptive_huffman_example [text of at most 32 bytes]\n"
188 << "Runs a symbol trace, changing-distribution phases, and binary chunks.\n";
189 return 0;
190 }
191 const std::string_view input = argc > 1 ? argv[1] : "ABRACADABRA";
192 ah_invalid_argument_if(argc > 2 or input.size() > 32)
193 << "Use adaptive_huffman_example [text of at most 32 bytes]";
194 std::cout << "\n ALEPH / ADAPTIVE HUFFMAN\n"
195 << " A guided FGK coding demonstration\n";
196 demonstrate_trace(input);
197 demonstrate_adaptation();
198 demonstrate_fragmentation();
199 std::cout << "\n Round trip verified in all three demonstrations.\n\n";
200 return 0;
201 }
202 catch (const std::exception &error)
203 {
204 std::cerr << error.what() << '\n';
205 return 1;
206 }
207}
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_logic_error_if(C)
Throws std::logic_error if condition holds.
Definition ah-errors.H:474
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
int main()
Incremental FGK decoder accepting arbitrarily fragmented bits.
bool has_pending_symbol() const noexcept
Test whether a tree path or NYT literal is incomplete.
void finish() const
Verify that an externally framed message ended at a byte boundary.
size_t decode(const BitArray &input, std::string &output)
Decode a bit chunk and append all complete bytes to a string.
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.
Contiguous array of bits.
Definition bitArray.H:201
std::string get_bit_str() const
Definition bitArray.H:981
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
Minimal std::expected-style result type for C++20.
void print_tree(Tree_Node< T > *node, int depth=0)
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
and
Check uniqueness with explicit hash + equality functors.
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
Definition ahDefs.C:100
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
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.
std::string next_code(const Aleph::Adaptive_Huffman_Encoder &encoder, const unsigned char byte)
Probe a byte's code without changing the source encoder.
ofstream output
Definition writeHeap.C:215