Low-Density Parity-Check Codes
Random codes approach capacity but cannot be decoded efficiently. Algebraic codes can be decoded efficiently but stay far from capacity at long lengths. Low-density parity-check (LDPC) codes, invented by Robert Gallager in 1960 and rediscovered by MacKay and Neal in the 1990s, get both: they are random enough to approach capacity and sparse enough to decode with fast iterative message passing. Wi-Fi, 5G, DVB-S2, 10G Ethernet and SSD controllers all use them.
Sparse parity checks
An LDPC code is a linear code (Linear Block Codes) defined by a parity-check matrix that is sparse: each column has a small number of ones (each bit is in checks), and each row has a small number of ones (each check involves bits). A regular code has the same weights everywhere and design rate .
Gallager's construction stacks bands: the first band has row covering bits to , and each other band is a random column permutation of the first.
import numpy as np
def gallager_H(n, wc, wr, rng):
band = np.zeros((n // wr, n), dtype=np.int8)
for i in range(n // wr):
band[i, i * wr:(i + 1) * wr] = 1
return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)])
rng = np.random.default_rng(0)
H = gallager_H(24, 3, 6, rng)
print("shape:", H.shape, " column weights:", set(H.sum(axis=0).tolist()), " row weights:", set(H.sum(axis=1).tolist()))
print("density:", round(float(H.mean()), 3))
for row in H[:6]:
print("".join(".#"[v] for v in row))shape: (12, 24) column weights: {3} row weights: {6}
density: 0.25
######..................
......######............
............######......
..................######
.#...#...#..#.....#...#.
...##..#...#.....#...#..
For a real code with (DVB-S2), the density is below 0.1%, so the decoder touches only a few hundred thousand matrix entries per iteration instead of billions.
The Tanner graph
is the adjacency matrix of a bipartite graph: variable nodes (one per bit) on one side, check nodes (one per parity check) on the other, with an edge wherever has a 1. Decoders pass messages along the edges (Bit-Flipping Decoding, Sum-Product (Belief Propagation) Decoding). Short cycles in this graph (especially 4-cycles, two bits sharing two checks) hurt iterative decoding, so constructions avoid them.
import numpy as np
def gallager_H(n, wc, wr, rng):
band = np.zeros((n // wr, n), dtype=np.int8)
for i in range(n // wr):
band[i, i * wr:(i + 1) * wr] = 1
return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)])
rng = np.random.default_rng(1)
H = gallager_H(96, 3, 6, rng).astype(int)
overlap = H.T @ H # entry (i, j): checks shared by bits i and j
np.fill_diagonal(overlap, 0)
print("edges in the Tanner graph:", int(H.sum()))
print("pairs of bits sharing 2 or more checks (4-cycles):", int(np.sum(overlap >= 2) // 2))edges in the Tanner graph: 288
pairs of bits sharing 2 or more checks (4-cycles): 38
Encoding
defines the code, but encoding needs a generator. Gaussian elimination over brings to the form after a column permutation; then the bits in the part are free (the message) and the parity bits are . Some rows of a Gallager are dependent, so the actual rate is a little above the design rate.
import numpy as np
def gallager_H(n, wc, wr, rng):
band = np.zeros((n // wr, n), dtype=np.int8)
for i in range(n // wr):
band[i, i * wr:(i + 1) * wr] = 1
return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)])
def make_encoder(H):
"""Return (message positions, parity positions, A) so that parity = A @ message mod 2."""
H = H.copy() % 2; m, n = H.shape; pivots = []; r = 0
for c in range(n - 1, -1, -1): # pivot from the right so parity bits sit at the end
rows = np.nonzero(H[r:, c])[0]
if len(rows) == 0:
continue
p = r + rows[0]; H[[r, p]] = H[[p, r]]
for i in range(m):
if i != r and H[i, c]:
H[i] ^= H[r]
pivots.append(c); r += 1
if r == m:
break
H = H[:r]
free = [c for c in range(n) if c not in pivots]
return free, pivots, H[:, free]
rng = np.random.default_rng(1)
H = gallager_H(96, 3, 6, rng)
free, pivots, A = make_encoder(H)
print(f"n = 96, independent checks = {len(pivots)}, message bits k = {len(free)}, rate = {len(free) / 96:.3f}")
s = rng.integers(0, 2, len(free))
c = np.zeros(96, dtype=int); c[free] = s; c[pivots] = A @ s % 2
print("H c = 0:", not np.any(H.astype(int) @ c % 2))n = 96, independent checks = 46, message bits k = 50, rate = 0.521
H c = 0: True
Why LDPC codes work
- Random-like: the permutations make the code behave like a random linear code, whose typical performance approaches capacity as grows (Random Codes and Typical-Set Decoding).
- Local decoding: each check involves few bits, so a check can tell its bits something useful. Iterating spreads this information through the graph.
- Density evolution predicts a noise threshold: below it, decoding succeeds with probability approaching 1 as grows. For the regular code on a BSC the threshold is about , compared with the capacity limit for rate . Irregular degree distributions close most of that gap.
In software
- Standards define structured "quasi-cyclic" LDPC matrices built from shifted identity blocks, which allow parallel hardware decoders and simple encoding.
scipy.sparsestores large matrices efficiently; the Python packagepyldpcimplements construction, encoding and decoding.
Exercises
Exercise 1: Design rate
What is the design rate of a regular LDPC code? And of ?
Answer
and .
Solution
: and .
Exercise 2: Counting edges
A regular code has bits. How many check nodes and edges does its Tanner graph have?
Answer
500 checks and 3000 edges.
Solution
Edges , so .
Exercise 3: Rank deficiency (code)
Build a Gallager matrix with and compute its rank over . Why can it never have full rank 60?
Answer
58, two less than the 60 rows.
Solution
import numpy as np
def gallager_H(n, wc, wr, rng):
band = np.zeros((n // wr, n), dtype=np.int8)
for i in range(n // wr):
band[i, i * wr:(i + 1) * wr] = 1
return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)])
def gf2_rank(M):
M = M.copy() % 2; r = 0
for c in range(M.shape[1]):
piv = np.nonzero(M[r:, c])[0]
if len(piv) == 0:
continue
p = r + piv[0]; M[[r, p]] = M[[p, r]]
for i in range(M.shape[0]):
if i != r and M[i, c]:
M[i] ^= M[r]
r += 1
if r == M.shape[0]:
break
return r
H = gallager_H(120, 3, 6, np.random.default_rng(5))
print("rows:", H.shape[0], " rank:", gf2_rank(H))rows: 60 rank: 58
Each band covers every bit exactly once, so the rows of each band sum to the all-ones vector. The three bands give the same sum, so at least 2 rows are dependent and the rank is at most .
Test yourself
What makes a code low-density parity-check?
- Its parity-check matrix has very few ones
- Its codewords have low weight
- It has few codewords
- Its generator matrix is the identity
The Tanner graph of a code connects…
- bits to the parity checks they appear in
- codewords to each other
- messages to codewords
- errors to syndromes
The design rate of a regular (wc, wr) LDPC code is…