Algorithm Search⌘K

Algorithmresearch

Constant composition distribution matching

Also called CCDM.

Maps uniform bits to amplitude sequences of a fixed type by arithmetic coding, giving the target distribution for probabilistic shaping.

Time
O(M n² log M / w) worst
Space
O(n log M / w) extra
Where
M = the number of output symbols (amplitudes); n = the output length in symbols; w = the word size in bits
Properties
constant compositiondeterministicfixed lengthinvertible
Origin
Patrick Schulte, Georg Böcherer, 2016

Constant composition distribution matching (CCDM) turns a block of kk uniform bits into a block of nn symbols, each word with the same number of copies of each symbol. The fixed counts, the composition, are chosen so that the word's symbol frequencies match a target distribution. In probabilistic constellation shaping, the symbols are the amplitudes of an ASK constellation, and the target gives small amplitudes more often than large ones. The map is one-to-one, so the receiver gets the bits back with the inverse map. The encoder is an arithmetic coder run backwards, in which each output symbol has the probability "copies left divided by symbols left". With exact integers this is the same as picking the word of a given rank among all words of the composition, which is what this page does.

In plain words

Think of a bag with 4 tiles marked "1", 3 marked "3", 2 marked "5" and 1 marked "7". Every way of drawing all 10 tiles in a row is a possible output, and all outputs contain each mark the same number of times. There are 12600 such rows. The matcher numbers the rows in dictionary order and uses the incoming bits to pick one, spread evenly over the list. The receiver finds the number of the row it received and turns it back into the bits. Because every row has many 1s and few 7s, the signal uses little energy. The cost is that 13 bits pick among only 12600 rows, fewer bits than the symbols could carry with no rule.

The problem

The input is kk independent uniform bits. The output alphabet is a1<a2<⋯<aMa_1 < a_2 < \cdots < a_M and the target distribution is PP on it. Choose counts c=(c1,…,cM)c = (c_1, \ldots, c_M) with ∑scs=n\sum_s c_s = n, and let Tc\mathcal{T}_c be the set of words of length nn in which asa_s appears exactly csc_s times. It has

T=∣Tc∣=n!c1! c2!⋯cM!T = |\mathcal{T}_c| = \frac{n!}{c_1!\, c_2! \cdots c_M!}

words (a multinomial coefficient). With k=⌊log⁡2T⌋k = \lfloor \log_2 T \rfloor, find an injective map f:{0,1}k→Tcf : \{0, 1\}^k \to \mathcal{T}_c and its inverse on the image, both fast. The rate is k/nk/n bits per symbol. Schulte and Böcherer choose c/nc/n as the type of length nn with the smallest divergence D(c/n ∥ P)D(c/n \,\|\, P); the rate can then come close to the entropy H(P)H(P) for large nn.

The algorithm

Order the words of Tc\mathcal{T}_c by dictionary order of the symbol indices. The number of words that start with asa_s is Tcs/nT c_s/n, since fixing the first symbol leaves a word of length n−1n - 1 with one copy of asa_s less. The encoder turns the bits into an integer vv, spreads it over the TT ranks, and unranks. The decoder ranks and divides back.

  1. CCDM-ENCODE(u_1..u_k, c_1..c_M, a_1..a_M)
  2. 1n ← Σ_s c_s ; T ← n! / (c_1! ··· c_M!) ; k ← ⌊log₂ T⌋
  3. 2v ← Σ_t u_t · 2^(k-t) ▷ the bits as an integer, first bit most significant
  4. 3r ← ⌈v · T / 2^k⌉ ▷ 0 ≤ r < T
  5. 4N ← T ▷ the number of words that are still possible
  6. 5for ℓ ← n down to 1 ▷ ℓ symbols are still to place
  7. 6for s ← 1 to M with c_s > 0
  8. 7N_s ← N · c_s / ℓ ▷ an exact integer
  9. 8if r < N_s then x_{n-ℓ+1} ← a_s ; c_s ← c_s - 1 ; N ← N_s ; go to the next ℓ
  10. 9r ← r - N_s
  11. 10return x_1..x_n
  12. CCDM-DECODE(x_1..x_n, c_1..c_M) ▷ T and k as in L1
  13. 11r ← 0 ; N ← T ; ℓ ← n
  14. 12for t ← 1 to n, with x_t = a_q
  15. 13for s ← 1 to q - 1: r ← r + N · c_s / ℓ
  16. 14N ← N · c_q / ℓ ; c_q ← c_q - 1 ; ℓ ← ℓ - 1
  17. 15v ← ⌊r · 2^k / T⌋ ; return the k bits of v

Line L3 picks the smallest rank rr with r≥vT/2kr \ge v T/2^k. In the arithmetic coder of the paper, this is the lowest output interval whose lower end lies in the input interval of vv. Since T≥2kT \ge 2^k, the ranks of different vv differ by at least one, and line L15 recovers vv.

Example

A short block. Take n=5n = 5, the amplitudes 1,3,51, 3, 5 and c=(2,2,1)c = (2, 2, 1). Then T=5!/(2! 2! 1!)=30T = 5!/(2!\,2!\,1!) = 30 and k=4k = 4, so 16 of the 30 words are used. The input 1011 gives v=11v = 11 and r=⌈11⋅30/16⌉=⌈20.625⌉=21r = \lceil 11 \cdot 30/16 \rceil = \lceil 20.625 \rceil = 21. Unranking:

ℓ\ell NN cc before counts Ncs/ℓN c_s/\ell tried rr after symbol
5 30 (2, 2, 1) 12 (skip), 12 (take) 9 3
4 12 (2, 1, 1) 6 (skip), 3 (skip), 3 (take) 0 5
3 3 (2, 1, 0) 2 (take) 0 1
2 2 (1, 1, 0) 1 (take) 0 1
1 1 (0, 1, 0) 1 (take) 0 3

The output is 3,5,1,1,33, 5, 1, 1, 3. The decoder ranks it back to 2121 and computes ⌊21⋅16/30⌋=⌊11.2⌋=11\lfloor 21 \cdot 16/30 \rfloor = \lfloor 11.2 \rfloor = 11, that is 1011. The 16 inputs v=0,…,15v = 0, \ldots, 15 go to the ranks 0,2,4,6,8,10,12,14,15,17,19,21,23,25,27,290, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 29, from 1,1,3,3,51, 1, 3, 3, 5 for v=0v = 0 to 5,3,3,1,15, 3, 3, 1, 1 for v=15v = 15. Every word has the energy 2⋅1+2⋅9+25=452 \cdot 1 + 2 \cdot 9 + 25 = 45, or 99 per symbol, against 35/3=11.735/3 = 11.7 for uniform amplitudes; the rate is 0.80.8 bits per symbol, against an entropy of 1.521.52 for the type.

The binary example of the paper. With n=4n = 4 and two 0s and two 1s, T=6T = 6 and k=2k = 2. The inputs 00, 01, 10, 11 go to the ranks 0,2,3,50, 2, 3, 5, that is to 0011, 0110, 1001, 1100.

Rate against block length. For the target P=(0.4,0.3,0.2,0.1)P = (0.4, 0.3, 0.2, 0.1) on the amplitudes 1,3,5,71, 3, 5, 7, with entropy H(P)=1.8464H(P) = 1.8464 bits and energy 1313 against 2121 for uniform amplitudes, the best type is PP itself at these lengths:

nn kk k/nk/n rate loss H(P)−k/nH(P) - k/n bound (3log⁡2(n+1)+1)/n(3\log_2(n + 1) + 1)/n
10 13 1.300 0.546 1.138
20 30 1.500 0.346 0.709
100 175 1.750 0.0964 0.210
1000 1831 1.831 0.0154 0.0309
10000 18444 1.8444 0.0020 0.0041

Correctness

The count of words that start with a given symbol is Tcs/nT c_s/n, by the multinomial formula. Lines L5 to L9 keep two invariants: NN is the number of words of the remaining composition, and rr is the rank of the wanted word among them. At each step the words are grouped by their first symbol in the order a1,…,aMa_1, \ldots, a_M, the group of asa_s has NsN_s words, and line L8 enters the group that contains rank rr. So the output is the word of rank rr, and it has the composition cc. The decoder adds the sizes of the groups before the actual symbol, which gives back rr. Line L3 gives r−1<vT/2k≤rr - 1 < vT/2^k \le r, and since T≥2kT \ge 2^k this implies v≤r 2k/T<v+1v \le r\,2^k/T < v + 1, so line L15 returns vv. So the map is one-to-one, and every output has the composition cc. For the rate, the type class of a type QQ of length nn on MM symbols has at least 2nH(Q)/(n+M−1M−1)2^{nH(Q)}/\binom{n + M - 1}{M - 1} words, which gives k/n>H(c/n)−((M−1)log⁡2(n+1)+1)/nk/n > H(c/n) - \big((M - 1)\log_2(n + 1) + 1\big)/n. The full proof is below.

Proof: CCDM is a one-to-one map onto words of the composition c, and its rate is close to the entropy of the typefull

Fix the symbols a1<⋯<aMa_1 < \cdots < a_M and the counts c=(c1,…,cM)c = (c_1, \ldots, c_M) with cs≥0c_s \ge 0 and ∑scs=n≥1\sum_s c_s = n \ge 1. Let Tc\mathcal{T}_c be the set of words of length nn with exactly csc_s copies of asa_s, ordered by dictionary order of the symbol indices, and let T(c)=∣Tc∣=n!/∏scs!T(c) = |\mathcal{T}_c| = n!/\prod_s c_s!. The rank of a word is its position in this order, starting at 00.

Lemma 1 (first symbol). If cs≥1c_s \ge 1, the number of words of Tc\mathcal{T}_c that start with asa_s is T(c−es)=T(c) cs/nT(c - e_s) = T(c)\, c_s/n, where ese_s is the unit vector of ss. In particular T(c) cs/nT(c)\,c_s/n is an integer.

Proof. Removing the first symbol is a bijection from the words that start with asa_s onto Tc−es\mathcal{T}_{c - e_s}. And T(c−es)=(n−1)!/((cs−1)!∏s′≠scs′!)=T(c)⋅cs/nT(c - e_s) = (n - 1)!/\big((c_s - 1)!\prod_{s' \ne s} c_{s'}!\big) = T(c)\cdot c_s/n. □\square

Lemma 2 (unranking). For 0≤r<T(c)0 \le r < T(c), lines L4 to L10 return the word of Tc\mathcal{T}_c with rank rr.

Proof. We show the invariant: at the start of each pass of line L5 with ℓ\ell symbols left and the current counts c′c' (with ∑c′=ℓ\sum c' = \ell), N=T(c′)N = T(c'), 0≤r<N0 \le r < N, and the wanted word is x1…xn−ℓx_1 \ldots x_{n-\ell} followed by the word of rank rr in Tc′\mathcal{T}_{c'}.

It holds at the start, with ℓ=n\ell = n, c′=cc' = c and N=T(c)N = T(c) (line L4). In one pass, the words of Tc′\mathcal{T}_{c'} fall into consecutive groups by their first symbol, in the order a1,…,aMa_1, \ldots, a_M, because the order is the dictionary order. The groups of the symbols with cs′=0c'_s = 0 are empty. By Lemma 1 the group of asa_s has Ns=Ncs′/ℓN_s = N c'_s/\ell words (line L7). Line L9 subtracts the sizes of the groups that come before the one that holds rank rr, and line L8 stops at the group ss where the remaining rr is less than NsN_s; such a group exists because the sizes add up to N>rN > r. Inside that group the remaining rr is the rank, and removing the first symbol asa_s keeps the order. So after line L8, with cs′c'_s decreased and N=Ns=T(c′−es)N = N_s = T(c' - e_s), the invariant holds for ℓ−1\ell - 1. When ℓ=0\ell = 0, Tc′\mathcal{T}_{c'} has only the empty word, and x1…xnx_1 \ldots x_n is the wanted word. □\square

Lemma 3 (ranking). For x∈Tcx \in \mathcal{T}_c, lines L11 to L14 compute the rank of xx.

Proof. By the same grouping, the rank of xx in Tc′\mathcal{T}_{c'} is the sum of the sizes of the groups of the symbols before xtx_t (line L13), plus the rank of the rest of the word in Tc′−eq\mathcal{T}_{c' - e_q} (line L14 updates NN and the counts for it). Induction on the length gives the claim. □\square

Lemma 4 (encoder and decoder). Let k=⌊log⁡2T⌋k = \lfloor\log_2 T\rfloor, so that 2k≤T2^k \le T. For 0≤v<2k0 \le v < 2^k, put r(v)=⌈vT/2k⌉r(v) = \lceil vT/2^k\rceil. Then 0≤r(v)<T0 \le r(v) < T, rr is strictly increasing, and ⌊r(v) 2k/T⌋=v\lfloor r(v)\, 2^k/T\rfloor = v.

Proof. r(v)≥0r(v) \ge 0 is clear. Since v≤2k−1v \le 2^k - 1, vT/2k≤T−T/2k≤T−1vT/2^k \le T - T/2^k \le T - 1, so r(v)≤T−1r(v) \le T - 1. By the definition of the ceiling, r(v)−1<vT/2k≤r(v)r(v) - 1 < vT/2^k \le r(v). Multiplying by 2k/T>02^k/T > 0 gives v≤r(v) 2k/T<v+2k/T≤v+1v \le r(v)\,2^k/T < v + 2^k/T \le v + 1, so the floor is vv. If v<v′v < v', then r(v)≤r(v′)r(v) \le r(v'), and r(v)=r(v′)r(v) = r(v') would give v=v′v = v' by the last claim; so rr is strictly increasing. □\square

Theorem. CCDM-ENCODE maps the 2k2^k input blocks one-to-one to words of Tc\mathcal{T}_c, and CCDM-DECODE inverts it on its image.

Proof. Line L2 maps the kk bits one-to-one onto 0≤v<2k0 \le v < 2^k. Line L3 computes r(v)r(v), which by Lemma 4 is a valid rank, and Lemma 2 gives the word xx of that rank, which lies in Tc\mathcal{T}_c. Different vv give different ranks (Lemma 4) and so different words, because unranking is a bijection between {0,…,T−1}\{0, \ldots, T - 1\} and Tc\mathcal{T}_c. The decoder computes the rank r(v)r(v) of xx by Lemma 3 and returns ⌊r(v) 2k/T⌋=v\lfloor r(v)\,2^k/T\rfloor = v by Lemma 4, whose kk bits are the input. ■\blacksquare

Lemma 5 (the most likely type class). Let Q=c/nQ = c/n and let QnQ^n be the i.i.d. distribution with marginal QQ. For every composition c′c' of nn with support in the support of QQ, Qn(Tc)≥Qn(Tc′)Q^n(\mathcal{T}_c) \ge Q^n(\mathcal{T}_{c'}).

Proof. Every word of Tc′\mathcal{T}_{c'} has probability ∏sQ(as)cs′\prod_s Q(a_s)^{c'_s}, so with ms=csm_s = c_s and ls=cs′l_s = c'_s, both sums equal to nn,

Qn(Tc)Qn(Tc′)=∏sls!ms! Q(as)ms−ls.\frac{Q^n(\mathcal{T}_c)}{Q^n(\mathcal{T}_{c'})} = \prod_s \frac{l_s!}{m_s!}\, Q(a_s)^{m_s - l_s}.

For integers l,m≥0l, m \ge 0, l!/m!≥ml−ml!/m! \ge m^{l - m}: if l≥ml \ge m the left side is a product of l−ml - m factors, each at least mm; if l<ml < m it is the inverse of a product of m−lm - l factors, each at most mm. The symbols with ms=0m_s = 0 have ls=0l_s = 0 by the support condition, and their factor is 1. For the others, Q(as)=ms/nQ(a_s) = m_s/n, so

∏sls!ms!Q(as)ms−ls≥∏smsls−ms(msn)ms−ls=∏snls−ms=n∑sls−∑sms=1.□\prod_s \frac{l_s!}{m_s!} Q(a_s)^{m_s - l_s} \ge \prod_s m_s^{l_s - m_s} \Big(\frac{m_s}{n}\Big)^{m_s - l_s} = \prod_s n^{l_s - m_s} = n^{\sum_s l_s - \sum_s m_s} = 1. \qquad \square

Proposition (rate). Let H(Q)=−∑sQ(as)log⁡2Q(as)H(Q) = -\sum_s Q(a_s)\log_2 Q(a_s) with Q=c/nQ = c/n. Then

T≥(n+M−1M−1)−12nH(Q)≥2nH(Q)(n+1)M−1,kn>H(Q)−(M−1)log⁡2(n+1)+1n.T \ge \binom{n + M - 1}{M - 1}^{-1} 2^{nH(Q)} \ge \frac{2^{nH(Q)}}{(n + 1)^{M - 1}}, \qquad \frac{k}{n} > H(Q) - \frac{(M - 1)\log_2(n + 1) + 1}{n}.

Proof. Every word of Tc\mathcal{T}_c has probability ∏sQ(as)cs=2−nH(Q)\prod_s Q(a_s)^{c_s} = 2^{-nH(Q)} under QnQ^n, so Qn(Tc)=T 2−nH(Q)Q^n(\mathcal{T}_c) = T\,2^{-nH(Q)}. The words of length nn with letters in the support of QQ carry all the probability and fall into type classes, one for each composition c′c' of nn with that support. There are at most (n+M−1M−1)\binom{n + M - 1}{M - 1} compositions of nn into MM nonnegative parts. By Lemma 5 each class has probability at most Qn(Tc)Q^n(\mathcal{T}_c), so

1≤(n+M−1M−1)T 2−nH(Q).1 \le \binom{n + M - 1}{M - 1} T\, 2^{-nH(Q)}.

For the second inequality, (n+M−1M−1)=∏i=1M−1n+ii\binom{n + M - 1}{M - 1} = \prod_{i=1}^{M-1}\frac{n + i}{i} and (n+i)/i≤n+1(n + i)/i \le n + 1 for i≥1i \ge 1. Finally k=⌊log⁡2T⌋>log⁡2T−1≥nH(Q)−(M−1)log⁡2(n+1)−1k = \lfloor\log_2 T\rfloor > \log_2 T - 1 \ge nH(Q) - (M - 1)\log_2(n + 1) - 1. Divide by nn. □\square

So for a fixed alphabet the rate loss H(Q)−k/nH(Q) - k/n is O(log⁡n/n)O(\log n/n). If the type is chosen close to the target PP, as below, H(c/n)H(c/n) tends to H(P)H(P), and so does the rate.

Proposition (the type). Let P(as)>0P(a_s) > 0 for the symbols in its support. The greedy rule of composition (start from all counts zero, and nn times add one copy to the symbol with the smallest increase of F(c)=∑scsln⁡(cs/(nP(as)))F(c) = \sum_s c_s\ln\big(c_s/(nP(a_s))\big), never to a symbol with P(as)=0P(a_s) = 0) returns counts with the smallest D(c/n ∥ P)=F(c)/nD(c/n\,\|\,P) = F(c)/n among all compositions of nn.

Proof. FF is a sum of terms fs(cs)=csln⁡(cs/(nP(as)))f_s(c_s) = c_s\ln\big(c_s/(nP(a_s))\big), with fs(0)=0f_s(0) = 0. Since xln⁡xx\ln x is convex on [0,∞)[0, \infty), the increments δs(j)=fs(j+1)−fs(j)\delta_s(j) = f_s(j + 1) - f_s(j) are nondecreasing in jj. Any composition cc has F(c)=∑s∑j<csδs(j)F(c) = \sum_s\sum_{j < c_s}\delta_s(j), the sum of nn elements of the multiset {δs(j)}\{\delta_s(j)\} in which each symbol contributes a prefix of its sequence. Such a sum is at least the sum of the nn smallest elements of the multiset. The greedy rule takes, at each step, the smallest increment that is still available; since each sequence is nondecreasing, the available increments are always the next ones of their sequences, and the nn choices are nn smallest elements of the multiset. So the greedy counts reach the lower bound. Symbols with P(as)=0P(a_s) = 0 would make DD infinite, so an optimal cc gives them 00. □\square

Cost. Each pass of line L7 and line L13 multiplies a number of at most log⁡2T≤nlog⁡2M\log_2 T \le n\log_2 M bits by cs≤nc_s \le n and divides exactly by ℓ≤n\ell \le n; with w≥log⁡2nw \ge \log_2 n this is O(nlog⁡M/w)O(n\log M/w) word operations. There are at most MM passes per symbol and nn symbols, which gives O(Mn2log⁡M/w)O(Mn^2\log M/w) for unranking and ranking. Computing TT as a running product takes nn such steps. Line L3 and line L15 each do one product of numbers of O(nlog⁡M)O(n\log M) bits and one shift or exact division, O((nlog⁡M/w)2)O((n\log M/w)^2) by schoolbook methods, which is at most O(Mn2log⁡M/w)O(Mn^2\log M/w) since log⁡M/w≤1≤M\log M/w \le 1 \le M.

Complexity

In the word RAM with words of w≥log⁡2nw \ge \log_2 n bits, every count is at most T≤MnT \le M^n, a number of at most nlog⁡2Mn\log_2 M bits, or O(nlog⁡M/w)O(n\log M/w) words. Line L7 multiplies such a number by a small integer and divides it exactly by ℓ\ell, in O(nlog⁡M/w)O(n\log M/w) steps. It runs at most MM times per symbol, so unranking and ranking cost O(Mn2log⁡M/w)O(M n^2\log M/w), and computing TT costs O(n2log⁡M/w)O(n^2\log M/w). Line L3 multiplies two numbers of O(nlog⁡M)O(n\log M) bits, in O((nlog⁡M/w)2)O((n\log M/w)^2) steps with schoolbook multiplication, which is not larger. The extra space is the few big numbers, O(nlog⁡M/w)O(n\log M/w) words. A binary search over the cumulative counts in line L6 cuts the factor MM to log⁡M\log M multiplications per symbol. The arithmetic coder of the paper works with finite precision and rescaling, in O(1)O(1) word operations per symbol for fixed precision, at the cost of a small change in the codebook.

Properties

  • Fixed length and one-to-one. Every block of kk bits gives a block of nn symbols, and the decoder is exact. A fixed length suits a channel code with a fixed block size, and an error in one block does not spread to the next.
  • Constant composition. Every output has the same counts, so every word has the same energy, the same number of each amplitude, and the same per-word frequencies. In a long stream, the frequencies of the amplitudes are exactly c/nc/n.
  • Rate loss. The rate k/nk/n is below the entropy H(c/n)H(c/n) of the type, and the loss is at most ((M−1)log⁡2(n+1)+1)/n((M - 1)\log_2(n + 1) + 1)/n, which goes to zero as nn grows. The normalized divergence of the output from i.i.d. PP also goes to zero.
  • Unequal use. Only 2k2^k of the TT words are used, and each used word has probability 2−k2^{-k}. The symbols at one position are not exactly i.i.d. with distribution PP.
  • Serial. Each output symbol depends on all earlier decisions, which limits the speed in hardware.

Variants and improvements

  • Finite precision arithmetic coding. The original encoder is an arithmetic coder with registers of fixed width and rescaling, which avoids big numbers.
  • Binary decomposition. Write each amplitude as a few bits and match each bit level with a binary CCDM. Binary CCDM indexes the words of a fixed weight, as enumerative coding does.
  • Shorter blocks with less loss. Multiset-partition matching and sphere shaping allow words of more than one type, for example all words with energy below a bound. They lose less rate at short nn, which CCDM needs for low latency.
  • Parallel matchers. Several short CCDMs in parallel raise the throughput, at the cost of a larger rate loss.
  • Other targets. The same encoder matches any distribution on a finite alphabet, not only amplitudes, for example the bits of a rate-adapted code.

When to use it

Use CCDM for the amplitudes of probabilistic amplitude shaping when the block can be long (hundreds to thousands of symbols), so that the rate loss is small, and when a fixed length and an exact inverse matter more than the lowest latency. For short blocks, a matcher that allows several types loses less.

Pitfalls

  • Short blocks. At n=10n = 10 the rate loss is 0.550.55 bits per symbol, more than the shaping gain is worth. Check the rate table before choosing nn.
  • The type. Rounding nPnP independently for each symbol need not give counts that sum to nn, and may not give the type with the smallest divergence. Choose cc as a whole.
  • Exact arithmetic. TT grows like 2nH2^{nH}, so n=1000n = 1000 needs integers of about 18501850 bits. Floating point loses the exact ranks and breaks the inverse.
  • The rounding direction. Line L3 rounds up and line L15 rounds down. Rounding both the same way can map two inputs to one rank, or give a rank that the decoder sends back to a different vv.
  • Errors in the decoder input. The decoder assumes a word of composition cc. After a channel error, the received word may not be in Tc\mathcal{T}_c, or may be a word that the encoder never produces. In probabilistic amplitude shaping the channel decoder corrects the errors first, so the matcher sees error-free amplitudes most of the time; the receiver must still handle the other case.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

constant_composition_distribution_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-composition-distribution-matching/. The authors are listed in prov/EKQBW6.jsonl.

"""Constant composition distribution matching (CCDM) with exact integer arithmetic.

The output alphabet is a list of distinct symbols in a fixed order, and the
composition c gives how often each symbol appears in every output word of
length n = sum(c). The set of such words has T = n! / prod(c_s!) elements,
and the matcher maps k = floor(log2 T) input bits to one of them.

Encoder: the input bits, most significant first, form the integer v, and the
output is the word of lexicographic rank r = ceil(v T / 2^k) among all words
of the composition. Decoder: rank the word to get r, then v = floor(r 2^k / T).
This is the codebook of the arithmetic coder of Schulte and Boecherer (2016)
with infinite precision.
"""

import math


def multinomial(c: list[int]) -> int:
    """The number n! / prod(c_s!) of words with the composition c."""
    total, n = 1, 0
    for cs in c:
        if cs < 0:
            raise ValueError("counts must be nonnegative")
        for t in range(1, cs + 1):
            n += 1
            total = total * n // t
    return total


def num_bits(c: list[int]) -> int:
    """k = floor(log2 T), the number of input bits per word."""
    return multinomial(c).bit_length() - 1


def unrank(r: int, c: list[int], symbols: list) -> list:
    """The word of lexicographic rank r (0 <= r < T) among all words of the composition c."""
    c = list(c)
    n = sum(c)
    big_n = multinomial(c)
    if not 0 <= r < big_n:
        raise ValueError("rank out of range")
    out = []
    for ell in range(n, 0, -1):  # @line L5
        for s in range(len(c)):  # @line L6
            if c[s] == 0:
                continue
            ns = big_n * c[s] // ell  # @line L7
            if r < ns:  # @line L8
                out.append(symbols[s])
                c[s] -= 1
                big_n = ns
                break
            r -= ns  # @line L9
    return out  # @line L10


def rank(word: list, c: list[int], symbols: list) -> int:
    """The lexicographic rank of word among all words of the composition c."""
    c = list(c)
    if len(word) != sum(c):
        raise ValueError("the word has the wrong length")
    index = {a: s for s, a in enumerate(symbols)}
    big_n = multinomial(c)
    r = 0  # @line L11
    ell = len(word)
    for a in word:  # @line L12
        x = index[a]
        if c[x] == 0:
            raise ValueError("the word does not have the composition c")
        for s in range(x):  # @line L13
            r += big_n * c[s] // ell
        big_n = big_n * c[x] // ell  # @line L14
        c[x] -= 1
        ell -= 1
    return r


def encode(bits: list[int], c: list[int], symbols: list) -> list:
    """Map k = floor(log2 T) bits (most significant first) to a word of composition c."""
    big_t = multinomial(c)  # @line L1
    k = big_t.bit_length() - 1
    if len(bits) != k:
        raise ValueError("the encoder needs exactly k bits")
    v = 0
    for b in bits:  # @line L2
        if b not in (0, 1):
            raise ValueError("bits must be 0 or 1")
        v = 2 * v + b
    r = -((-v * big_t) >> k)  # @line L3
    return unrank(r, c, symbols)  # @line L4


def decode(word: list, c: list[int], symbols: list) -> list[int]:
    """Recover the k input bits from a word that encode produced."""
    big_t = multinomial(c)
    k = big_t.bit_length() - 1
    v = (rank(word, c, symbols) << k) // big_t  # @line L15
    return [(v >> (k - 1 - t)) & 1 for t in range(k)]


def composition(probs: list[float], n: int) -> list[int]:
    """The counts c (sum n) whose type c/n has the smallest divergence D(c/n || P) from P.

    D is separable and convex in each count, so adding one unit at a time to the
    symbol with the smallest increase of n D is optimal. Ties go to the lower index.
    Symbols with probability 0 get count 0.
    """
    if n < 1 or any(p < 0 for p in probs) or not math.isclose(sum(probs), 1.0, rel_tol=0, abs_tol=1e-9):
        raise ValueError("need n >= 1 and a probability vector")
    c = [0] * len(probs)

    def f(cs: int, p: float) -> float:
        return 0.0 if cs == 0 else cs * math.log(cs / (n * p))

    for _ in range(n):
        best, arg = math.inf, -1
        for s, p in enumerate(probs):
            if p == 0:
                continue
            inc = f(c[s] + 1, p) - f(c[s], p)
            if inc < best - 1e-12:
                best, arg = inc, s
        c[arg] += 1
    return c


def rate(c: list[int]) -> float:
    """The rate k / n in input bits per output symbol."""
    return num_bits(c) / sum(c)
test_constant_composition_distribution_matching.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-composition-distribution-matching/. The authors are listed in prov/EKQBW6.jsonl.

import itertools
import math
import random
import unittest

from constant_composition_distribution_matching import (
    composition,
    decode,
    encode,
    multinomial,
    num_bits,
    rank,
    rate,
    unrank,
)


def all_words(c, symbols):
    """All words of the composition c in lexicographic order of the symbol indices, by brute force."""
    pool = [s for s, cs in enumerate(c) for _ in range(cs)]
    idx = sorted(set(itertools.permutations(pool)))
    return [[symbols[s] for s in w] for w in idx]


def to_bits(v, k):
    return [(v >> (k - 1 - t)) & 1 for t in range(k)]


def divergence(c, probs):
    n = sum(c)
    return sum((cs / n) * math.log((cs / n) / p) for cs, p in zip(c, probs) if cs > 0)


def entropy(probs):
    return -sum(p * math.log2(p) for p in probs if p > 0)


class TestCCDM(unittest.TestCase):
    def test_multinomial(self):
        self.assertEqual(multinomial([4, 3, 2, 1]), 12600)
        self.assertEqual(multinomial([2, 2, 1]), 30)
        self.assertEqual(multinomial([2, 2]), 6)
        self.assertEqual(multinomial([0, 5, 0]), 1)
        self.assertEqual(num_bits([4, 3, 2, 1]), 13)
        self.assertEqual(num_bits([2, 2, 1]), 4)

    def test_unrank_matches_sorted_permutations(self):
        for c in ([2, 2], [2, 2, 1], [3, 1, 1], [1, 1, 1, 1], [2, 1, 2, 1], [4, 0, 2]):
            symbols = list(range(len(c)))
            words = all_words(c, symbols)
            self.assertEqual(len(words), multinomial(c))
            for r, w in enumerate(words):
                self.assertEqual(unrank(r, c, symbols), w)
                self.assertEqual(rank(w, c, symbols), r)

    def test_paper_codebook(self):
        c, symbols = [2, 2], [0, 1]
        book = ["".join(map(str, encode(to_bits(v, 2), c, symbols))) for v in range(4)]
        self.assertEqual(book, ["0011", "0110", "1001", "1100"])

    def test_page_example(self):
        c, symbols = [2, 2, 1], [1, 3, 5]
        self.assertEqual(encode([0, 0, 0, 0], c, symbols), [1, 1, 3, 3, 5])
        self.assertEqual(encode([1, 0, 1, 1], c, symbols), [3, 5, 1, 1, 3])
        self.assertEqual(encode([1, 1, 1, 1], c, symbols), [5, 3, 3, 1, 1])
        ranks = [rank(encode(to_bits(v, 4), c, symbols), c, symbols) for v in range(16)]
        self.assertEqual(ranks, [0, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 29])

    def test_bijection_and_composition(self):
        for c in ([2, 2, 1], [3, 2, 2, 1], [3, 3, 2], [5, 1], [1, 2, 0, 3]):
            symbols = [2 * s + 1 for s in range(len(c))]
            k = num_bits(c)
            seen = set()
            for v in range(1 << k):
                word = encode(to_bits(v, k), c, symbols)
                self.assertEqual([word.count(a) for a in symbols], c)
                self.assertEqual(decode(word, c, symbols), to_bits(v, k))
                seen.add(tuple(word))
            self.assertEqual(len(seen), 1 << k)

    def test_encoder_order(self):
        c, symbols = [3, 2, 2, 1], [1, 3, 5, 7]
        k = num_bits(c)
        prev = -1
        for v in range(1 << k):
            r = rank(encode(to_bits(v, k), c, symbols), c, symbols)
            self.assertEqual(r, -((-v * multinomial(c)) // (1 << k)))
            self.assertGreater(r, prev)
            prev = r

    def test_long_words(self):
        rng = random.Random(41)
        probs = [0.4, 0.3, 0.2, 0.1]
        c = composition(probs, 400)
        symbols = [1, 3, 5, 7]
        k = num_bits(c)
        for _ in range(20):
            bits = [rng.randrange(2) for _ in range(k)]
            word = encode(bits, c, symbols)
            self.assertEqual([word.count(a) for a in symbols], c)
            self.assertEqual(decode(word, c, symbols), bits)

    def test_composition_is_optimal(self):
        rng = random.Random(42)
        for _ in range(40):
            size = rng.randint(2, 4)
            raw = [rng.random() + 0.01 for _ in range(size)]
            probs = [x / sum(raw) for x in raw]
            n = rng.randint(1, 9)
            c = composition(probs, n)
            self.assertEqual(sum(c), n)
            best = min(
                divergence(list(cc), probs)
                for cc in itertools.product(range(n + 1), repeat=size)
                if sum(cc) == n
            )
            self.assertLess(divergence(c, probs), best + 1e-12)
        self.assertEqual(composition([0.4, 0.3, 0.2, 0.1], 10), [4, 3, 2, 1])
        self.assertEqual(composition([0.5, 0.0, 0.5], 4), [2, 0, 2])

    def test_rates(self):
        probs = [0.4, 0.3, 0.2, 0.1]
        h = entropy(probs)
        table = {10: 13, 20: 30, 50: 84, 100: 175, 200: 358, 1000: 1831}
        for n, k in table.items():
            c = composition(probs, n)
            self.assertEqual(num_bits(c), k, n)
            self.assertLessEqual(rate(c), entropy([cs / n for cs in c]) + 1e-12)
            bound = ((len(probs) - 1) * math.log2(n + 1) + 1) / n
            self.assertLessEqual(entropy([cs / n for cs in c]) - rate(c), bound)
        self.assertAlmostEqual(h, 1.8464, delta=1e-4)

    def test_errors(self):
        with self.assertRaises(ValueError):
            encode([0, 1], [2, 2, 1], [1, 3, 5])
        with self.assertRaises(ValueError):
            unrank(30, [2, 2, 1], [1, 3, 5])
        with self.assertRaises(ValueError):
            rank([1, 1, 1, 3, 5], [2, 2, 1], [1, 3, 5])
        with self.assertRaises(ValueError):
            composition([0.5, 0.6], 3)


if __name__ == "__main__":
    unittest.main()

History

Fixed-to-fixed distribution matching came up with probabilistic shaping for higher-order modulation. Böcherer, Steiner and Schulte in 2015 proposed probabilistic amplitude shaping, in which a distribution matcher produces the amplitudes and a systematic LDPC code adds the signs. Schulte and Böcherer in 2016 gave the constant composition matcher: choose the type with the smallest divergence from the target, use all words of that type as the codebook, and index them by arithmetic coding with the probabilities "copies left divided by symbols left". They showed that the rate approaches the entropy of the target as the block length grows. The idea of indexing all words of a fixed composition is older: it is the enumerative source coding of Cover in 1973 for fixed weights.

References

  1. Patrick Schulte and Georg Böcherer, Constant composition distribution matching, IEEE Transactions on Information Theory 62(1), 430-434, 2016, the choice of the output type, the arithmetic coding encoder and decoder, and the rate and divergence results
  2. Georg Böcherer, Fabian Steiner and Patrick Schulte, Bandwidth efficient and rate-matched low-density parity-check coded modulation, IEEE Transactions on Communications 63(12), 4651-4665, 2015, probabilistic amplitude shaping, where a distribution matcher produces the amplitudes

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example