Documentation

CslibFrontier.Algorithms.Lean.Huffman.TwoQueue

Two-Queue Huffman Construction #

When input symbols are already sorted in nondecreasing order of nonnegative weight, van Leeuwen ([vL76]) observed that Huffman's algorithm does not need a general priority queue: maintaining a list q₁ of unmerged leaves alongside a single FIFO queue q₂ of merged internal nodes keeps q₂ automatically sorted, because consecutive merged pair sums w(t₁) + w(t₂) are monotone nondecreasing under nonnegative weights.

This module provides the pure mathematical construction and optimality theorems; machine-level Word-RAM running-time bounds (O(n) from pre-sorted weights and O(n log n) from unsorted weights) are proved in CslibFrontier.Algorithms.WordRAM.Huffman:

  1. Two-list functional FIFO queue (FifoQueue γ) ([CLRS09], Exercise 10.1-6): peek? inspects front.head? directly under the canonical invariant front = [] → back = [], and enqueue / dequeue? satisfy explicit potential-method list-reversal bounds (enqueue_revCost_bound, dequeue?_revCost_bound). Unlike Std.Queue (Init.Data.Queue, which does not maintain dList = [] → eList = [], so inspecting the head without committing a dequeue would repeatedly reverse eList) and Cslib.DataStructure.Queue (an abstract Cslib.DataStructure two-stack module without peek?), FifoQueue inspects the head directly when popMin compares the heads of q₁ and q₂ and pops q₁ while leaving q₂ unchanged.
  2. Cached-weight trees (WeightedTree α β): each queue entry caches wt = tree.weight w, so each merge computes a.wt + b.wt without re-traversing subtrees.
  3. Van Leeuwen two-queue construction (huffmanFromSorted): fuel-free step equation twoQueueLoop_step, queue-list specification popMin_spec_toList, and correctness on sorted nonnegative inputs (huffmanFromSorted_spec).
  4. End-to-end unsorted Huffman construction (huffman): sorts syms with List.mergeSort and runs huffmanFromSorted, producing a tree certified by IsHuffmanBuild (hence optimal over all CodeTrees and all injective IsPrefixFree binary codes, and—when 2 ≤ syms.length, avoiding the 1-symbol CodeTree.leaf a degeneracy whose codewordSet = {[]} is IsPrefixFree in Mathlib but not IsUniquelyDecodable—producing a uniquely decodable codebook optimal over all injective IsUniquelyDecodable binary codes).

Main definitions #

Main results #

References #

Two-list functional FIFO queue #

Two-list functional FIFO queue representing front ++ back.reverse.

  • front : List γ

    Dequeue-ready prefix in FIFO order.

  • back : List γ

    Recently enqueued suffix in reverse FIFO order.

Instances For
    @[instance_reducible]
    def Cslib.Algorithms.Lean.Huffman.instDecidableEqFifoQueue.decEq {γ✝ : Type u_1} [DecidableEq γ✝] (x✝ x✝¹ : FifoQueue γ✝) :
    Decidable (x✝ = x✝¹)
    @[instance_reducible]

    Abstract FIFO sequence represented by q.

    Number of elements stored in q.

    Canonical two-list invariant: front is empty only when back is also empty.

    Smart constructor restoring WF by reversing back when front becomes empty.

    Number of list-reversal steps performed by checkf f b.

    Enqueue x at the back of q.

    Peek at the front element of q by inspecting front.head?.

    Dequeue the front element of q if non-empty.

    @[simp]
    theorem Cslib.Algorithms.Lean.Huffman.FifoQueue.size_enqueue {γ : Type u_1} (q : FifoQueue γ) (x : γ) :
    (q.enqueue x).size = q.size + 1
    theorem Cslib.Algorithms.Lean.Huffman.FifoQueue.front_cons_spec {γ : Type u_1} {q : FifoQueue γ} {x : γ} {f : List γ} (hf : q.front = x :: f) :
    theorem Cslib.Algorithms.Lean.Huffman.FifoQueue.dequeue?_spec {γ : Type u_1} {q : FifoQueue γ} (hwf : q.WF) :
    match q.dequeue? with | none => q.toList = [] | some (x, q') => q.toList = x :: q'.toList ∧ q'.WF

    Potential bound for enqueue with potential Φ(q) = q.back.length: reversal steps plus ΔΦ is at most 1.

    Potential bound for dequeue? with potential Φ(q) = q.back.length: reversal steps plus ΔΦ is 0.

    Cached-weight trees and van Leeuwen's two-queue loop #

    structure Cslib.Algorithms.Lean.Huffman.WeightedTree (α : Type u_1) (β : Type u_2) :
    Type (max u_1 u_2)

    A CodeTree α paired with its cached total weight wt : β.

    • tree : CodeTree α

      Underlying code tree.

    • wt : β

      Cached subtree weight (tree.weight w).

    Instances For
      def Cslib.Algorithms.Lean.Huffman.instDecidableEqWeightedTree.decEq {α✝ : Type u_1} {β✝ : Type u_2} [DecidableEq α✝] [DecidableEq β✝] (x✝ x✝¹ : WeightedTree α✝ β✝) :
      Decidable (x✝ = x✝¹)
      @[instance_reducible]
      instance Cslib.Algorithms.Lean.Huffman.instDecidableEqWeightedTree {α✝ : Type u_1} {β✝ : Type u_2} [DecidableEq α✝] [DecidableEq β✝] :
      def Cslib.Algorithms.Lean.Huffman.instReprWeightedTree.repr {α✝ : Type u_1} {β✝ : Type u_2} [Repr α✝] [Repr β✝] :
      WeightedTree α✝ β✝ → ℕ → Std.Format
      @[instance_reducible]
      instance Cslib.Algorithms.Lean.Huffman.instReprWeightedTree {α✝ : Type u_1} {β✝ : Type u_2} [Repr α✝] [Repr β✝] :
      Repr (WeightedTree α✝ β✝)
      def Cslib.Algorithms.Lean.Huffman.popMin {α β : Type u} [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (q₁ : List (WeightedTree α β)) (q₂ : FifoQueue (WeightedTree α β)) :

      Pop a minimum-weight entry from leaf list q₁ and internal-node queue q₂ (preferring q₁ on ties, as in [vL76]). Matching directly on q₂.front ensures FifoQueue.checkf is evaluated under strict evaluation only in branches that actually dequeue from q₂.

      theorem Cslib.Algorithms.Lean.Huffman.popMin_spec_toList {α β : Type u} [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (q₁ : List (WeightedTree α β)) {q₂ : FifoQueue (WeightedTree α β)} (hwf : q₂.WF) :
      match q₁, q₂.toList with | [], [] => popMin q₁ q₂ = none | [], y :: ys => ∃ (q₂' : FifoQueue (WeightedTree α β)), popMin q₁ q₂ = some (y, [], q₂') ∧ q₂'.WF ∧ q₂'.toList = ys | x :: xs, [] => popMin q₁ q₂ = some (x, xs, q₂) | x :: xs, y :: ys => if x.wt ≤ y.wt then popMin q₁ q₂ = some (x, xs, q₂) else ∃ (q₂' : FifoQueue (WeightedTree α β)), popMin q₁ q₂ = some (y, x :: xs, q₂') ∧ q₂'.WF ∧ q₂'.toList = ys

      Representation-free specification of popMin in terms of q₂.toList whenever q₂.WF holds.

      def Cslib.Algorithms.Lean.Huffman.twoQueueLoop {α β : Type u} [Add β] [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (q₁ : List (WeightedTree α β)) (q₂ : FifoQueue (WeightedTree α β)) :

      Main merge loop of van Leeuwen's two-queue Huffman algorithm ([vL76]).

      theorem Cslib.Algorithms.Lean.Huffman.twoQueueLoop_step {α β : Type u} [Add β] [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (q₁ : List (WeightedTree α β)) (q₂ : FifoQueue (WeightedTree α β)) :
      twoQueueLoop q₁ q₂ = match popMin q₁ q₂ with | none => none | some (a, q₁', q₂') => match popMin q₁' q₂' with | none => some a.tree | some (b, q₁'', q₂'') => twoQueueLoop q₁'' (q₂''.enqueue { tree := a.tree.branch b.tree, wt := a.wt + b.wt })

      Fuel-free unfolding equation for twoQueueLoop.

      def Cslib.Algorithms.Lean.Huffman.huffmanFromSorted {α β : Type u} [Add β] [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (w : α → β) (syms : List α) :

      Two-queue Huffman construction from a symbol list syms sorted by w ([vL76]).

      def Cslib.Algorithms.Lean.Huffman.huffman {α β : Type u} [Add β] [LE β] [DecidableRel fun (x1 x2 : β) => x1 ≤ x2] (w : α → β) (syms : List α) :

      Huffman construction from an arbitrary symbol list syms, sorting first via List.mergeSort and then running huffmanFromSorted.

      Correctness of van Leeuwen's two-queue invariant and optimality of huffman #

      theorem Cslib.Algorithms.Lean.Huffman.IsHuffmanBuild.of_perm {α : Type u_1} {β : Type u_2} [Add β] [LE β] {w : α → β} {F₁ F₂ : List (CodeTree α)} {T : CodeTree α} (hperm : F₁.Perm F₂) (hbuild : IsHuffmanBuild w F₂ T) :

      IsHuffmanBuild depends on the starting forest F only up to List.Perm.

      theorem Cslib.Algorithms.Lean.Huffman.huffmanFromSorted_spec {α β : Type u} [AddCommMonoid β] [LinearOrder β] [IsOrderedAddMonoid β] {w : α → β} {syms : List α} (hne : syms ≠ []) (hsorted : List.Pairwise (fun (a b : α) => w a ≤ w b) syms) (hw : ∀ a ∈ syms, 0 ≤ w a) :

      Correctness of Two-Queue Huffman Construction ([vL76]): on any nonempty symbol list syms sorted in nondecreasing order of w with nonnegative weights, huffmanFromSorted w syms returns some T satisfying IsHuffmanBuild w (syms.map .leaf) T and T.leaves.Perm syms.

      theorem Cslib.Algorithms.Lean.Huffman.huffman_spec {α β : Type u} [AddCommMonoid β] [LinearOrder β] [IsOrderedAddMonoid β] {w : α → β} {syms : List α} (hne : syms ≠ []) (hw : ∀ a ∈ syms, 0 ≤ w a) :
      ∃ (T : CodeTree α), huffman w syms = some T ∧ IsHuffmanBuild w (List.map CodeTree.leaf syms) T ∧ T.leaves.Perm syms

      End-to-End Correctness of huffman: on any nonempty symbol list syms with nonnegative weights, huffman w syms returns some T satisfying IsHuffmanBuild w (syms.map .leaf) T and T.leaves.Perm syms.

      theorem Cslib.Algorithms.Lean.Huffman.huffman_optimal {α β : Type u} [AddCommMonoid β] [LinearOrder β] [IsOrderedAddMonoid β] {w : α → β} {syms : List α} {T : CodeTree α} (hw : ∀ a ∈ syms, 0 ≤ w a) (hT : huffman w syms = some T) (T' : CodeTree α) (hT' : T'.leaves.Perm syms) :

      Optimality of huffman over Full Binary Code Trees: the tree returned by huffman w syms minimizes weightedPathLength w among all full binary CodeTree αs with leaf multiset syms.

      theorem Cslib.Algorithms.Lean.Huffman.huffman_optimal_isPrefixFree {α β : Type u} [AddCommMonoid β] [LinearOrder β] [IsOrderedAddMonoid β] {syms : List α} (hne : syms ≠ []) (hnodup : syms.Nodup) {w : α → β} (hw : ∀ a ∈ syms, 0 ≤ w a) {T : CodeTree α} (hT : huffman w syms = some T) {code : α → List Bool} (hinj : Set.InjOn code {a : α | a ∈ syms}) (hpf : InformationTheory.IsPrefixFree (code '' {a : α | a ∈ syms})) :
      CodeTree.weightedPathLength w T ≤ (List.map (fun (a : α) => (code a).length • w a) syms).sum

      Optimality of huffman over All Prefix-Free Binary Codes: on distinct symbols syms with nonnegative weights, huffman w syms achieves weighted path length at most that of any injective InformationTheory.IsPrefixFree binary code.

      theorem Cslib.Algorithms.Lean.Huffman.huffman_optimal_isUniquelyDecodable {α β : Type u} [AddCommMonoid β] [LinearOrder β] [IsOrderedAddMonoid β] {syms : List α} (h2 : 2 ≤ syms.length) (hnodup : syms.Nodup) {w : α → β} (hw : ∀ a ∈ syms, 0 ≤ w a) {T : CodeTree α} (hT : huffman w syms = some T) {code : α → List Bool} (hinj : Set.InjOn code {a : α | a ∈ syms}) (hud : InformationTheory.IsUniquelyDecodable (code '' {a : α | a ∈ syms})) :

      Optimality of huffman over All Uniquely Decodable Binary Codes: on at least two distinct symbols (2 ≤ syms.length) with nonnegative weights, huffman w syms returns a tree T whose codebook is InformationTheory.IsUniquelyDecodable and achieves weighted path length at most that of any injective InformationTheory.IsUniquelyDecodable binary code.

      On a 1-symbol input, huffman w [a] = some (.leaf a) has codewordSet = {[]}, which is InformationTheory.IsPrefixFree in Mathlib (covered by huffman_optimal_isPrefixFree) but not InformationTheory.IsUniquelyDecodable.