Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S9 · B1·09

Surviving the Channel

Stage 9 of Squeeze, after chapter 9: `protect.py` wraps a Squeeze file in a correcting code (three copies of every bit, or Hamming(7,4)) for a noisy channel or medium, and `noise.py` measures what survives; with one bit in 10,000 flipped, both codes recover the packed server log almost every time, but with one in 1,000, where capacity says 1.15 % of extra bits would be enough, Hamming's 75 % recovers only 3 files in 20 and three copies (200 %) only half, and every damaged file that couldn't be repaired is caught by stage 8's checks.

6 topics · ~11 min read
Updated Suggest a correction

Stage 9: surviving the channel

The brief

What you'll build. protect.py, a layer around Squeeze files: wrap encodes a sealed file with a correcting code (none, rep3 or ham74) after a small header (which code, and the length) that's itself sent five times over; unwrap decodes it. Then noise.py sends the packed server log through binary symmetric channels with flip probabilities from 10−5 to 0.03, 20 times each, and counts files decoded exactly, damage caught by stage 8's checks, and wrong data accepted.

Why a compressor needs this. Stage 8 made damage visible; it didn't make it survivable. A file stored on a medium that degrades (old flash, tape, a damaged disc) or sent where it can't be sent again needs redundancy that can repair, and chapter 9 says how little redundancy that could take.

Why now. The chapter supplies capacity, 1−h(p), the minimum redundancy it implies, and the warning that simple codes fall far short of it.

What you'll have at the end. protect.py, the noise table, and a clear number for how far Squeeze's protection is from what the theorem allows.

Theory to own

  1. The least redundancy. On a channel that flips a fraction p of bits, why does every n bits of message need at least n/(1−h(p)) bits sent? Compute it for p=0.001. (Chapter: "Capacity of some channels"; the coding theorem.)
  2. Why a whole file is harder than a bit. If each Hamming block fails with probability q, what's the chance that all 83,536 blocks of the packed log survive? (Chapter 8: "Long blocks almost always have errors".)
  3. Correct, then check. Why does the correcting code go outside stage 8's checks? (Chapter: "Separation".)
  4. Why the header gets its own protection. What happens if the length field is damaged? (Stage 8's senior lens.)

Build it

Step 1: the protection layer. Hamming(7,4) and repetition from chapter 8, written with NumPy so a whole file is coded at once.

Python
"""Squeeze, stage 9: wrap a Squeeze file in an error-correcting code, for a noisy channel or medium.
Usage: python3 protect.py wrap none|rep3|ham74 IN OUT  or  python3 protect.py unwrap IN OUT"""
import sys
from pathlib import Path
import numpy as np

CODES = {0: "none", 1: "rep3", 2: "ham74"}

def _bits(data):
    return np.unpackbits(np.frombuffer(data, dtype=np.uint8))

def _rep_encode(bits, n):
    return np.repeat(bits, n)

def _rep_decode(bits, n):
    return (bits.reshape(-1, n).sum(axis=1) > n // 2).astype(np.uint8)

def _ham_encode(bits):
    d = bits.reshape(-1, 4)
    d1, d2, d3, d4 = d.T
    return np.stack([d1 ^ d2 ^ d4, d1 ^ d3 ^ d4, d1, d2 ^ d3 ^ d4, d2, d3, d4], axis=1).ravel()

def _ham_decode(bits):
    c = bits.reshape(-1, 7).copy()
    s = (c[:, 0] ^ c[:, 2] ^ c[:, 4] ^ c[:, 6]) + 2 * (c[:, 1] ^ c[:, 2] ^ c[:, 5] ^ c[:, 6]) + 4 * (c[:, 3] ^ c[:, 4] ^ c[:, 5] ^ c[:, 6])
    rows = np.nonzero(s)[0]
    c[rows, s[rows] - 1] ^= 1                          # each block with a failed check: flip the bit the syndrome names
    return c[:, [2, 4, 5, 6]].ravel()

def wrap(blob, code):
    """A 5-byte header (code, length), sent 5 times over, then the payload coded."""
    cid = next(k for k, v in CODES.items() if v == code)
    header = bytes([cid]) + len(blob).to_bytes(4, "big")
    bits = _bits(blob)
    if code == "rep3":
        bits = _rep_encode(bits, 3)
    elif code == "ham74":
        bits = _ham_encode(bits)                       # a byte is 8 bits, two whole blocks of 4
    return np.packbits(_rep_encode(_bits(header), 5)).tobytes() + np.packbits(bits).tobytes()

def unwrap(data):
    header = np.packbits(_rep_decode(_bits(data[:25]), 5)).tobytes()   # majority vote on each header bit
    code, n = CODES.get(header[0], "none"), int.from_bytes(header[1:5], "big")
    bits = _bits(data[25:])
    if code == "rep3":
        bits = _rep_decode(bits[: 8 * n * 3], 3)
    elif code == "ham74":
        bits = _ham_decode(bits[: 8 * n * 7 // 4])
    return np.packbits(bits[: 8 * n]).tobytes()

if __name__ == "__main__":
    a = sys.argv[1:]
    if a[:1] == ["wrap"] and len(a) == 4 and a[1] in CODES.values():
        Path(a[3]).write_bytes(wrap(Path(a[2]).read_bytes(), a[1]))
    elif a[:1] == ["unwrap"] and len(a) == 3:
        Path(a[2]).write_bytes(unwrap(Path(a[1]).read_bytes()))
    else:
        sys.exit(__doc__)

Step 2: check it round-trips, and that Hamming really corrects. Every file through every code, then one flipped bit in every Hamming block of the packed log.

Python
import random
from pathlib import Path
import numpy as np
import squeeze, protect

rng = random.Random(9)
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    sealed = squeeze.pack(Path(name).read_bytes())
    row = []
    for code in ("none", "rep3", "ham74"):
        w = protect.wrap(sealed, code)
        row.append(f"{code} {len(w):,} {'exact' if protect.unwrap(w) == sealed else 'FAILED'}")
    print(f"{name:<16}" + "   ".join(row))

sealed = squeeze.pack(Path("server.log").read_bytes())
w = protect.wrap(sealed, "ham74")
bits = np.unpackbits(np.frombuffer(w[25:], dtype=np.uint8))
blocks = bits.size // 7
bits[np.arange(blocks) * 7 + np.array([rng.randrange(7) for _ in range(blocks)])] ^= 1   # one error in every block
damaged = w[:25] + np.packbits(bits).tobytes()
print(f"one flipped bit in each of {blocks:,} Hamming blocks: unpacked {'exactly' if squeeze.unpack(protect.unwrap(damaged)) == Path('server.log').read_bytes() else 'WRONG'}")
Text
shakespeare.txt none 492,361 exact   rep3 1,477,033 exact   ham74 861,613 exact
zeros.bin       none 44 exact   rep3 82 exact   ham74 59 exact
random.bin      none 200,041 exact   rep3 600,073 exact   ham74 350,053 exact
squares.csv     none 80,842 exact   rep3 242,476 exact   ham74 141,455 exact
server.log      none 41,793 exact   rep3 125,329 exact   ham74 73,119 exact
one flipped bit in each of 83,536 Hamming blocks: unpacked exactly

Step 3: through the channel.

Python
"""Send a packed server log through binary symmetric channels with and without protection, and compare with capacity."""
import math
from pathlib import Path
import numpy as np
import squeeze, protect

rng = np.random.default_rng(9)
h = lambda p: -p * math.log2(p) - (1 - p) * math.log2(1 - p)
data = Path("server.log").read_bytes()
sealed = squeeze.pack(data)
wrapped = {c: protect.wrap(sealed, c) for c in ("none", "rep3", "ham74")}
print(f"server.log {len(data):,} bytes, packed {len(sealed):,}; protected: " + ", ".join(f"{c} {len(w):,}" for c, w in wrapped.items()))

def channel(blob, p):
    bits = np.unpackbits(np.frombuffer(blob, dtype=np.uint8))
    return np.packbits(bits ^ (rng.random(bits.size) < p)).tobytes()

trials = 20
print(f"\nfiles out of {trials}: decoded exactly / damage caught / wrong data accepted")
print(f"{'p':>7}{'least overhead possible':>25}" + "".join(f"{c:>18}" for c in wrapped))
for p in (1e-5, 1e-4, 1e-3, 1e-2, 3e-2):
    cells = []
    for code, blob in wrapped.items():
        ok = caught = wrong = 0
        for _ in range(trials):
            try:
                out = squeeze.unpack(protect.unwrap(channel(blob, p)))
                ok += out == data
                wrong += out != data
            except ValueError:                          # Damaged, or a header so damaged it isn't a Squeeze file
                caught += 1
        cells.append(f"{ok} / {caught} / {wrong}")
    print(f"{p:>7g}{100 * (1 / (1 - h(p)) - 1):>23.2f} %" + "".join(f"{c:>18}" for c in cells))
print("\noverhead of the codes: rep3 200 %, ham74 75 %")
Text
server.log 200,000 bytes, packed 41,768; protected: none 41,793, rep3 125,329, ham74 73,119

files out of 20: decoded exactly / damage caught / wrong data accepted
      p  least overhead possible              none              rep3             ham74
  1e-05                   0.02 %        0 / 20 / 0        20 / 0 / 0        20 / 0 / 0
 0.0001                   0.15 %        0 / 20 / 0        20 / 0 / 0        19 / 1 / 0
  0.001                   1.15 %        0 / 20 / 0       10 / 10 / 0        3 / 17 / 0
   0.01                   8.79 %        0 / 20 / 0        0 / 20 / 0        0 / 20 / 0
   0.03                  24.13 %        0 / 20 / 0        0 / 20 / 0        0 / 20 / 0

overhead of the codes: rep3 200 %, ham74 75 %

Step 4: read the table.

  • Unprotected, nothing survives. Even at p=10−5, the packed log (334,000 bits) expects about 3 errors, and the chance of none is about 4 %: all 20 copies were damaged, and stage 8's checks caught every one.
  • At 10−4, both codes work: 20 of 20 with three copies, 19 of 20 with Hamming. Capacity says 0.15 % of extra bits would do; the codes spend 200 % and 75 %.
  • At 10−3, they fail often. Hamming loses a block when it holds two errors, probability about 21p2≈2×10−5, small for one block but not for 83,536: about 1.75 failures expected per file, so only about e−1.75, 17 %, of files should survive whole (measured: 3 of 20). Three copies fail when two of a bit's copies flip, about 3p2 per bit over 334,000 bits: about one failure per file, so about e−1, 37 %, should survive (measured: 10 of 20). Capacity says 1.15 % of redundancy would be enough with a good long code.
  • At 10−2 and above, neither code helps, though capacity still allows reliable transmission with 8.8 % (at 0.01) and 24 % (at 0.03) of extra bits.
  • Nothing wrong got through. In 300 noisy trials, every file was either exact or caught by stage 8's checks: the code repairs what it can, and the check catches what it can't.

Senior and architect lens

  • Measure distance from the limit. The table's "least overhead possible" column is the yardstick: at p=10−3, Squeeze spends 65 times the theoretical minimum redundancy and still fails most of the time. A design review that knows the limit asks the right question ("why are we this far away?"); one that doesn't argues about which simple code is better.
  • Whole-file reliability compounds. A code that's excellent per block can be poor per file, because a file is many blocks and all must survive. Size codes for the unit that matters (the file, the transaction), not the block.
  • Layer the protection. Correct inside (the code), detect outside (the CRCs), and resend or restore from a copy when detection fires. Each layer handles what the one inside it misses, and nothing wrong is silently accepted.
  • Strong codes are a library choice, not a weekend project. Reaching within a few percent of capacity needs long LDPC or similar codes with soft decoding: use a tested implementation, or, for storage, an erasure code across separate copies (as RAID and distributed storage do), and keep the format's code identifier so it can be upgraded.

Evidence

  • protect.py, run.py with every round trip "exact" and the every-block test passing, and your noise table.
  • For p=0.001: the least possible overhead, each code's overhead, and the share of files each recovered, with the calculation of why Hamming recovers so few.
  • A paragraph on why stage 8's checks still matter once a correcting code is in place.

Carry forward

Stage 10, after chapter 10, tests Squeeze on real data of very different kinds (text in other languages, genomes, images, logs, already-compressed files) and compares each with its measured entropy, to see where the order-1 model does well and where it falls short.