// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Histograms of symbols, and the two things the compressor does with //! many of them: merging those alike so they can share a prefix code, and //! finding where a stream of symbols should switch from one code to //! another. //! //! Histograms are kept back to back in one slice, `alphabet` counts each. const std = @import("std"); const Allocator = std.mem.Allocator; /// `n * log2(n)` for the small counts that most histograms are made of, /// which saves a logarithm for nearly every symbol. const n_log2_n = blk: { @setEvalBranchQuota(100_000); var table: [1024]f64 = undefined; table[0] = 0; for (1..table.len) |n| { const f: f64 = @floatFromInt(n); table[n] = f * @log2(f); } break :blk table; }; pub inline fn nLog2N(n: u64) f64 { if (n < n_log2_n.len) return n_log2_n[n]; const f: f64 = @floatFromInt(n); return f * @log2(f); } /// The entropy of a histogram: the fewest bits its symbols could be coded /// in. pub fn entropy(h: []const u32) f64 { var total: u64 = 0; var sum: f64 = 0; for (h) |c| { total += c; sum += nLog2N(c); } return nLog2N(total) - sum; } /// What coding a histogram costs, in bits: its entropy, plus a rough cost /// for writing its prefix code down. pub fn cost(h: []const u32) f64 { var total: u64 = 0; var used: u32 = 0; var sum: f64 = 0; for (h) |c| { if (c == 0) continue; total += c; used += 1; sum += nLog2N(c); } if (total == 0) return 0; return nLog2N(total) - sum + headerCost(used); } fn headerCost(used: u32) f64 { const u: f64 = @floatFromInt(used); return if (used <= 4) 4 + 8 * u else 40 + 4.5 * u; } /// `cost` of the sum of two histograms, without making the sum. pub fn costOfSum(a: []const u32, b: []const u32) f64 { var total: u64 = 0; var used: u32 = 0; var sum: f64 = 0; for (a, b) |x, y| { const c = x + y; if (c == 0) continue; total += c; used += 1; sum += nLog2N(c); } if (total == 0) return 0; return nLog2N(total) - sum + headerCost(used); } fn isEmpty(h: []const u32) bool { for (h) |c| { if (c != 0) return false; } return true; } /// Marks a histogram with no symbols in it, which belongs to no cluster. pub const unassigned = std.math.maxInt(u16); /// Merges the `n` histograms in `hists` greedily, always the pair whose /// merging costs least, for as long as merging saves bits or there are more /// than `max_clusters`. Writes each histogram's cluster to `assignment`, /// numbered in order of first appearance, or `unassigned` for an empty one, /// and the clusters' histograms to the front of `hists`. Returns how many /// clusters there are. pub fn cluster(gpa: Allocator, hists: []u32, alphabet: usize, assignment: []u16, max_clusters: usize) Allocator.Error!usize { const n = assignment.len; std.debug.assert(hists.len == n * alphabet); std.debug.assert(max_clusters >= 1); // Live clusters, each identified by the histogram slot that holds it. const slots = try gpa.alloc(u16, n); defer gpa.free(slots); const self = try gpa.alloc(f64, n); defer gpa.free(self); // Which live cluster each histogram belongs to. const owner = try gpa.alloc(u16, n); defer gpa.free(owner); var live: usize = 0; for (0..n) |i| { const h = hists[i * alphabet ..][0..alphabet]; if (isEmpty(h)) { owner[i] = unassigned; continue; } slots[live] = @intCast(i); self[live] = cost(h); owner[i] = @intCast(live); live += 1; } // The cost of merging each pair, upper triangle only. const delta = try gpa.alloc(f64, live * live); defer gpa.free(delta); for (0..live) |i| { for (i + 1..live) |j| { delta[i * live + j] = costOfSum(hist(hists, alphabet, slots[i]), hist(hists, alphabet, slots[j])) - self[i] - self[j]; } } const stride = live; while (live > 1) { var bi: usize = 0; var bj: usize = 1; for (0..live) |i| { for (i + 1..live) |j| { if (delta[i * stride + j] < delta[bi * stride + bj]) { bi = i; bj = j; } } } if (delta[bi * stride + bj] >= 0 and live <= max_clusters) break; const into = hist(hists, alphabet, slots[bi]); for (into, hist(hists, alphabet, slots[bj])) |*a, b| a.* += b; self[bi] = cost(into); for (owner) |*o| { if (o.* == bj) o.* = @intCast(bi); } // Move the last live cluster into the gap. const last = live - 1; if (bj != last) { slots[bj] = slots[last]; self[bj] = self[last]; for (owner) |*o| { if (o.* == last) o.* = @intCast(bj); } for (0..live) |k| { if (k == bj or k == last) continue; delta[@min(k, bj) * stride + @max(k, bj)] = delta[@min(k, last) * stride + @max(k, last)]; } } live -= 1; for (0..live) |k| { if (k == bi) continue; delta[@min(k, bi) * stride + @max(k, bi)] = costOfSum(hist(hists, alphabet, slots[bi]), hist(hists, alphabet, slots[k])) - self[bi] - self[k]; } } // Number the clusters in order of first appearance, and gather their // histograms at the front. const number = try gpa.alloc(u16, live); defer gpa.free(number); @memset(number, unassigned); const merged = try gpa.alloc(u32, live * alphabet); defer gpa.free(merged); var k: usize = 0; for (owner, assignment) |o, *a| { if (o == unassigned) { a.* = unassigned; continue; } if (number[o] == unassigned) { number[o] = @intCast(k); @memcpy(merged[k * alphabet ..][0..alphabet], hist(hists, alphabet, slots[o])); k += 1; } a.* = number[o]; } @memcpy(hists[0 .. k * alphabet], merged[0 .. k * alphabet]); return k; } fn hist(hists: []u32, alphabet: usize, i: usize) []u32 { return hists[i * alphabet ..][0..alphabet]; } /// Assigns each symbol of `symbols` to one of the `k` histograms in `hists`, /// so as to minimize the bits the symbols cost under them, plus /// `switch_cost` for every change from one to another: the reference /// compressor's block finder. Writes the assignment to `ids`. pub fn findBlocks(gpa: Allocator, symbols: []const u16, alphabet: usize, hists: []const u32, k: usize, switch_cost: f64, ids: []u8) Allocator.Error!void { std.debug.assert(ids.len == symbols.len and k >= 1 and k <= 256); if (symbols.len == 0) return; if (k == 1) { @memset(ids, 0); return; } // What each symbol costs under each histogram, by symbol and then // histogram. A symbol a histogram has never seen costs a little more // than its rarest one. const insert_cost = try gpa.alloc(f64, alphabet * k); defer gpa.free(insert_cost); for (0..k) |j| { const h = hists[j * alphabet ..][0..alphabet]; var total: u64 = 0; for (h) |c| total += c; const log_total = @log2(@as(f64, @floatFromInt(@max(total, 1)))); for (h, 0..) |c, s| { insert_cost[s * k + j] = if (c == 0) log_total + 2 else log_total - @log2(@as(f64, @floatFromInt(c))); } } const cost_by_type = try gpa.alloc(f64, k); defer gpa.free(cost_by_type); @memset(cost_by_type, 0); const words = (k + 63) / 64; const switches = try gpa.alloc(u64, symbols.len * words); defer gpa.free(switches); @memset(switches, 0); for (symbols, ids, 0..) |s, *id, i| { var min: f64 = std.math.inf(f64); for (cost_by_type, 0..) |*c, j| { c.* += insert_cost[@as(usize, s) * k + j]; if (c.* < min) { min = c.*; id.* = @intCast(j); } } // A histogram that has fallen further behind than a switch costs // is better reached by switching to it here; remember that. const cap = min + switch_cost; for (cost_by_type, 0..) |*c, j| { if (c.* >= cap) { c.* = cap; switches[i * words + j / 64] |= @as(u64, 1) << @intCast(j % 64); } } } // Back from the end, switching only where switching was the cheaper way // to be in the current type. var i = symbols.len - 1; var current = ids[i]; while (i > 0) { i -= 1; if (switches[i * words + current / 64] & (@as(u64, 1) << @intCast(current % 64)) != 0) { current = ids[i]; } ids[i] = current; } } test "cluster merges what is alike and keeps apart what is not" { const gpa = std.testing.allocator; const alphabet = 4; // Two kinds, each three times, and an empty one. var hists = [_]u32{ 100, 0, 0, 1, 0, 100, 1, 0, 90, 0, 0, 2, 0, 0, 0, 0, 0, 95, 2, 0, 98, 1, 0, 1, 0, 99, 1, 1, }; var assignment: [7]u16 = undefined; const k = try cluster(gpa, &hists, alphabet, &assignment, 8); try std.testing.expectEqual(2, k); try std.testing.expectEqualSlices(u16, &.{ 0, 1, 0, unassigned, 1, 0, 1 }, &assignment); try std.testing.expectEqual(288, hists[0]); // And no more than asked. var many: [16 * 4]u32 = undefined; for (&many, 0..) |*c, i| c.* = @intCast((i * 7919) % 101); var a16: [16]u16 = undefined; try std.testing.expect(try cluster(gpa, &many, 4, &a16, 3) <= 3); } test "findBlocks switches where the statistics change" { const gpa = std.testing.allocator; var symbols: [400]u16 = undefined; for (&symbols, 0..) |*s, i| s.* = if (i < 200) @intCast(i % 2) else @intCast(2 + i % 2); const hists = [_]u32{ 50, 50, 0, 0, 0, 0, 50, 50 }; var ids: [400]u8 = undefined; try findBlocks(gpa, &symbols, 4, &hists, 2, 20, &ids); for (ids, 0..) |id, i| try std.testing.expectEqual(@as(u8, if (i < 200) 0 else 1), id); }