Algorithm Search⌘K

Algorithmadvanced

Levin-Campello algorithm

Also called Campello bit loading.

Optimal integer bit loading from any start: move bits from the costliest loaded position to the cheapest free one until the loading is efficient, then add or remove bits to meet the target.

Time
O(N + M log(N + M)) worst
Space
O(N + M) extra
Where
M = the number of bit moves (swaps plus additions and removals); N = the number of subcarriers
Properties
deterministicgreedyincrementalneeds csitoptimal
Origin
Jorge Campello, Howard E. Levin, 1999

The Levin-Campello algorithm solves bit loading exactly, starting from any integer loading. A loading is efficient when no loaded bit costs more power than the cheapest bit that could still be added. The algorithm first makes the start efficient by moving bits: while the most expensive loaded bit costs more than the cheapest free bit, it moves that bit. Then it tightens the loading: in the margin-adaptive form it removes the most expensive bits or adds the cheapest ones until the total is the target BB; in the rate-adaptive form it does the same until the power fits the budget PP and the next bit does not. With the costs of the SNR gap model, the result is optimal. It finds the same optimum as the Hughes-Hartogs greedy rule, but it moves only the bits that are wrong, so a good start, such as rounded water-filling or the loading in use before a small change of the channel, makes it fast.

In plain words

A modem has a table that says how many bits each tone carries. The table may be a rough guess, or it may be last minute's table and the line has changed a little.

To fix it, look for the most expensive bit now in the table and the cheapest bit that could be added. If moving that bit saves power, move it, and repeat. When no move saves power, the table is the best one for its number of bits. Then add the cheapest bits or remove the most expensive ones until the number of bits or the power matches what is needed. Only the bits that are in the wrong place get moved, so a good guess is fixed quickly.

The problem

Subcarrier ii has the gain gi>0g_i > 0, and with the gap Γ\Gamma bit kk on it costs di(k)=Γ2k−1/gid_i(k) = \Gamma 2^{k-1}/g_i, so bb bits cost ei(b)=Γ(2b−1)/gie_i(b) = \Gamma(2^{b} - 1)/g_i. Each subcarrier carries at most bmax⁡b_{\max} bits. For a loading bb, the last cost of subcarrier ii is di(bi)d_i(b_i) (if bi>0b_i > 0) and its next cost is di(bi+1)d_i(b_i + 1) (if bi<bmax⁡b_i < b_{\max}). The margin-adaptive (MA) form asks for ∑ibi=B\sum_i b_i = B at the least power; the rate-adaptive (RA) form asks for the most bits with power at most PP. The input also contains a start loading.

Campello's names for the conditions: a loading is efficient (EF) if its largest last cost is at most its smallest next cost; it is B-tight if it has BB bits; it is E-tight if its power is at most PP and adding the cheapest next bit would exceed PP.

The algorithm

  1. LEVIN-CAMPELLO(g[1..N], Γ, b_max, b[1..N], B or P) ▷ b is any start loading
  2. 1E ← Σ_i Γ(2^(b_i) - 1)/g_i; build a max-heap of last costs and a min-heap of next costs
  3. 2while the largest last cost (at m) > the smallest next cost (at n) do ▷ make it efficient
  4. 3b_m ← b_m - 1, b_n ← b_n + 1, update E and both heaps
  5. 4while Σ_i b_i > B (MA) or E > P (RA) do ▷ tighten from above
  6. 5remove the bit with the largest last cost, update E and both heaps
  7. 6while Σ_i b_i < B (MA) or E + the smallest next cost ≤ P (RA) do ▷ tighten from below
  8. 7add the bit with the smallest next cost, update E and both heaps
  9. 8return (b, E)

The heaps break ties by the subcarrier index: the largest (cost, index) leaves and the smallest (cost, index) enters. The heaps use lazy deletion: each change pushes the new entries of one subcarrier, and old entries are dropped when they reach the top.

Example

Take g=(20,9,5,1.5)g = (20, 9, 5, 1.5), Γ=1\Gamma = 1, the MA target B=8B = 8, and the flat start b=(2,2,2,2)b = (2, 2, 2, 2) with power 3.08333.0833.

pass last costs next costs move bits after power after
1 0.1, 0.222, 0.4, 1.333 0.2, 0.444, 0.8, 2.667 carrier 4 to carrier 1 (3, 2, 2, 1) 1.9500
2 0.2, 0.222, 0.4, 0.667 0.4, 0.444, 0.8, 1.333 carrier 4 to carrier 1 (4, 2, 2, 0) 1.6833
3 0.4, 0.222, 0.4, none 0.8, 0.444, 0.8, 0.667 stop: 0.4 is at most 0.444 (4, 2, 2, 0) 1.6833

After two swaps the loading is efficient. It already has 8 bits, so it is B-tight, and the power 101/60≈1.6833101/60 \approx 1.6833 is the optimum that the greedy method also finds. The distance from the start to the optimum is ∣2−4∣+0+0+∣2−0∣=4|2 - 4| + 0 + 0 + |2 - 0| = 4, and each swap closed 2 of it.

For the RA form with P=2P = 2, start from the rounded-down water-filling rates (3,2,1,0)(3, 2, 1, 0), with power 0.88330.8833. This start is already efficient (largest last cost 0.2220.222, smallest next cost 0.40.4). Line L7 adds a bit to carrier 1 for 0.40.4, then one to carrier 3 for 0.40.4, reaching 1.68331.6833; the next bit would cost 0.4440.444 and exceed 2, so the result is again (4,2,2,0)(4, 2, 2, 0).

Correctness

Claim. From any start, the MA form returns a loading with BB bits and the least power, and the RA form returns the most bits within PP at the least power for that number of bits, provided the next-bit costs on each subcarrier increase.

Key steps. Because each list of costs increases, the largest loaded cost is the largest last cost and the cheapest free cost is the smallest next cost. So an efficient loading has every loaded cost at most every free cost, and its loaded costs are the tt smallest of all, which is the least power E∗(t)E^*(t) for tt bits. A swap keeps the bit count and lowers the power strictly, so the swap phase stops, and it stops exactly when the loading is efficient. Removing the most expensive bit or adding the cheapest one keeps a loading efficient, so the tightening phases walk along E∗(t)E^*(t) to the target BB or to the largest tt with E∗(t)≤PE^*(t) \le P. With the tie rule above, each swap removes one element that is not in the optimal set and adds one that is, so the number of swaps is at most half the distance ∑i∣bi−bi∗∣\sum_i |b_i - b_i^*| from the start to the optimum. The full proof is in the proofs folder.

Proof: The Levin-Campello algorithm reaches an optimal loading from any startfull

Setting. Subcarrier ii has the next-bit costs di(k)=Γ2k−1/gid_i(k) = \Gamma 2^{k-1}/g_i for k=1,…,mik = 1, \ldots, m_i, where mi=bmax⁡m_i = b_{\max} or mi=∞m_i = \infty. They are positive and strictly increasing in kk. A loading bb with 0≤bi≤mi0 \le b_i \le m_i is the choice of the prefix di(1),…,di(bi)d_i(1), \ldots, d_i(b_i) of each list, and its power E(b)=∑i∑k≤bidi(k)E(b) = \sum_i \sum_{k \le b_i} d_i(k) is the sum of the chosen costs. Let DD be the set of all pairs (i,k)(i, k) with cost di(k)d_i(k), and let C(b)C(b) be the chosen pairs. For bi>0b_i > 0, the last cost of ii is di(bi)d_i(b_i); for bi<mib_i < m_i, the next cost of ii is di(bi+1)d_i(b_i + 1).

Let E∗(t)E^*(t) be the least power of a loading with tt bits. Since each list is increasing, the tt cheapest elements of DD form a prefix of each list, so E∗(t)E^*(t) is the sum of the tt smallest costs in DD. Since all costs are positive, E∗E^* is strictly increasing.

Definition. A loading is efficient if its largest last cost is at most its smallest next cost (an empty side counts as −∞-\infty or +∞+\infty).

Lemma 1. In any loading, the largest cost in C(b)C(b) is the largest last cost, and the smallest cost in D∖C(b)D \setminus C(b) is the smallest next cost.

Proof. In list ii the chosen part is a prefix and the list is increasing, so its largest chosen cost is di(bi)d_i(b_i) and its smallest unchosen cost is di(bi+1)d_i(b_i + 1). Take the maximum and the minimum over ii. □\square

Lemma 2 (efficient means optimal). An efficient loading with tt bits has the power E∗(t)E^*(t).

Proof. By Lemma 1, every chosen cost is at most every unchosen cost. Sort the costs of DD in increasing order. Then the chosen costs are tt values that are each at most every other value, so as a multiset they are the tt smallest values, and their sum is E∗(t)E^*(t). □\square

Lemma 3 (the swap phase). In each pass of lines L2 and L3 with mm at the largest last cost cℓc_\ell and nn at the smallest next cost cn<cℓc_n < c_\ell: (a) m≠nm \ne n; (b) the bit count does not change and the power falls by cℓ−cn>0c_\ell - c_n > 0; (c) the phase stops, and it stops at an efficient loading.

Proof. (a) If m=nm = n, then cℓ=dm(bm)<dm(bm+1)=cnc_\ell = d_m(b_m) < d_m(b_m + 1) = c_n, which is false. (b) Line L3 removes the chosen element of cost cℓc_\ell and adds the unchosen element of cost cnc_n. Since m≠nm \ne n, the next cost of nn is not changed by the removal, so the new loading is a prefix of each list again. (c) The count t=∑ibit = \sum_i b_i is fixed, and each subcarrier has at most tt bits, so there are finitely many loadings with tt bits. The power falls strictly in every pass, so no loading repeats, and the phase stops. It stops exactly when the test of line L2 fails, which is the definition of efficient. □\square

Lemma 4 (the number of swaps). Order DD totally by (cost,i,k)(\text{cost}, i, k), and let the implementation break ties so that line L3 removes the largest last element and adds the smallest next element in this order. Let b∗b^* be the loading whose chosen set SS is the first tt elements in this order. Then the swap phase makes at most 12∑i∣bi−bi∗∣\frac12 \sum_i |b_i - b^*_i| swaps, where bb is the start.

Proof. As in Lemma 1, the largest chosen element in this order is the largest last element xx, and the smallest unchosen element is the smallest next element yy. Suppose a swap happens, so the cost of xx exceeds the cost of yy, and xx comes after yy in the order. If x∈Sx \in S, then every chosen element, which comes no later than xx, lies in SS, because SS is an initial segment; then C(b)=SC(b) = S, since both have tt elements, and yy, being unchosen, comes after every element of SS, including xx. This contradicts the order of xx and yy. So x∉Sx \notin S. In the same way, if y∉Sy \notin S, then every unchosen element comes no earlier than yy and lies outside SS, so S⊆C(b)S \subseteq C(b) and again C(b)=SC(b) = S, a contradiction. So y∈Sy \in S. The swap removes x∉Sx \notin S and adds y∈Sy \in S, so it lowers ∣C(b)△S∣|C(b) \triangle S| by exactly 2. The size of the symmetric difference is ∑i∣bi−bi∗∣\sum_i |b_i - b^*_i| at the start and is never negative, which gives the bound. □\square

When all costs are different, the phase stops only at C(b)=SC(b) = S, so the bound is met with equality.

Lemma 5 (tightening keeps efficiency). Let bb be efficient with tt bits. Removing a bit at the largest last cost gives an efficient loading with t−1t - 1 bits. Adding a bit at the smallest next cost cc gives an efficient loading with t+1t + 1 bits.

Proof. Removal: let cc be the largest last cost, at subcarrier mm. After the removal, the next cost of mm is cc, and the other next costs are at least cc by efficiency, so the smallest next cost is cc. The last costs are now the old ones except at mm, where the new last cost is c/2c/2 or absent; all are at most cc. So the loading is efficient. Addition: the same argument with the roles of last and next costs exchanged; the new last cost of nn is cc, the old last costs are at most cc, the new next cost of nn is 2c2c, and the other next costs are at least cc. □\square

Theorem 1 (margin-adaptive form). For a target BB with 0≤B≤∑imi0 \le B \le \sum_i m_i and any start bb, the algorithm returns a loading with BB bits and the power E∗(B)E^*(B).

Proof. By Lemma 3, after line L3 the loading is efficient with tt bits. If t>Bt > B, lines L4 and L5 remove t−Bt - B bits; if t<Bt < B, lines L6 and L7 add B−tB - t bits, and a next bit exists at each step because B≤∑imiB \le \sum_i m_i. By Lemma 5 the loading stays efficient, so by Lemma 2 its power at the end is E∗(B)E^*(B). □\square

Theorem 2 (rate-adaptive form). For a budget P≥0P \ge 0 and any start, the algorithm returns a loading with t∗=max⁡{t:E∗(t)≤P}t^* = \max\{t : E^*(t) \le P\} bits and the power E∗(t∗)E^*(t^*), which is the most bits within the budget at the least power for that number of bits.

Proof. After the swap phase, the loading is efficient with some tt bits and power E∗(t)E^*(t) (Lemmas 3 and 2). Lines L4 and L5 remove bits while the power exceeds PP; by Lemma 5 the powers are E∗(t),E∗(t−1),…E^*(t), E^*(t-1), \ldots, and since E∗(0)=0≤PE^*(0) = 0 \le P the loop stops at the largest t′≤tt' \le t with E∗(t′)≤PE^*(t') \le P. Lines L6 and L7 add a bit while E∗(t′)+c≤PE^*(t') + c \le P, where cc is the smallest next cost; by Lemmas 5 and 2 the sum E∗(t′)+cE^*(t') + c equals E∗(t′+1)E^*(t' + 1). So the loop stops at the first t′′t'' with E∗(t′′+1)>PE^*(t'' + 1) > P, or when no next bit exists. Since E∗E^* is increasing, the set {t:E∗(t)≤P}\{t : E^*(t) \le P\} is an interval that starts at 0, and in both phases the loop stops at its largest element, t∗t^*. Any loading within the budget with tt bits has E∗(t)≤PE^*(t) \le P, so t≤t∗t \le t^*. □\square

Remark (cost). With a max-heap of last costs and a min-heap of next costs, each move of a bit costs O(log⁡N)O(\log N) heap work (with lazy deletion, O(log⁡(N+M))O(\log(N + M)) for MM moves). Building the heaps costs O(N)O(N). The total time is O(N+Mlog⁡(N+M))O(N + M \log(N + M)), where MM is the number of swaps plus the number of tightening steps.

Complexity

Line L1 takes O(N)O(N) time. Each move of one bit at lines L3, L5 or L7 takes a constant number of heap operations. With lazy deletion the heaps hold at most N+2MN + 2M entries for MM moves, so each operation costs O(log⁡(N+M))O(\log(N + M)), and the time is O(N+Mlog⁡(N+M))O(N + M \log(N + M)) with O(N+M)O(N + M) extra space; indexed heaps with a decrease-key operation bring the space to O(N)O(N) and each step to O(log⁡N)O(\log N). The number of moves is at most half the distance to the optimum plus the change in the bit count. From the all-zero start, the algorithm is the Hughes-Hartogs rule and M=BM = B. From rounded-down water-filling, the RA form adds fewer than NN bits, because the integer optimum is less than NN bits above the rounded rates.

Properties

  • Optimal from any start. The result does not depend on the start, apart from the choice among equal-power answers.
  • Incremental. A small change of the channel changes the optimal loading a little, and the algorithm moves only the bits that change. This makes it fit for tracking a slowly changing DSL line.
  • Efficient is the same as optimal. For increasing costs, a loading is MA-optimal for its own number of bits if and only if it is efficient. This gives a cheap test of any loading.
  • Monotone power. The power never rises in the swap phase.
  • Integer arithmetic. With the costs scaled by a common factor, all tests are comparisons of powers of two times fixed numbers per subcarrier, and the bit counts are small integers.

Variants and improvements

  • Steps of β\beta bits. Move β\beta bits at a time, with costs ei(b+β)−ei(b)e_i(b + \beta) - e_i(b), for constellations of even size only.
  • Margin-adaptive with a fixed power. To maximize a common margin for a fixed BB and PP, run the MA form and scale the power to PP; the margin is P/E∗(B)P/E^*(B).
  • Bit swapping in DSL. DSL modems change the bits and gains of a few tones during operation, without a restart. The swap step of this algorithm is the natural rule for choosing the tones.
  • Chow-Cioffi-Bingham. A faster method with real-valued rates and a margin; its result can serve as the start here.
  • Table costs. Any cost table with increasing increments works. Without that condition, efficient loadings need not be optimal.

When to use it

Use it when a good start is available: after a small change of the channel, after rounding water-filling, or after a fast heuristic such as Chow-Cioffi-Bingham. For a single loading from nothing, the Hughes-Hartogs rule is simpler and as fast. Both need costs whose increments increase.

Pitfalls

  • Swapping within one subcarrier. With increasing costs the largest last cost and the smallest next cost are never on the same subcarrier; an implementation that finds them on the same one has a bug in its heaps.
  • Stale heap entries. With lazy deletion, an entry must be checked against the current bit count of its subcarrier before use.
  • Ties and stopping. The swap test must be a strict inequality. With ≥\ge, equal costs swap forever.
  • Order of the phases. In the RA form, tightening before the swap phase can stop with too few bits, because the swaps lower the power afterwards and leave room for more. Swap first, then tighten.
  • Floating point. Repeated additions and subtractions of the power drift; recompute it from the bits at the end if exact values matter.

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.

levin_campello_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/levin-campello-algorithm/. The authors are listed in prov/XEKW7B.jsonl.

"""Levin-Campello bit loading.

Subcarrier i has the gain g[i]. With the SNR gap Gamma, bit b + 1 on it
costs the power Gamma * 2**b / g[i]. The algorithm starts from any loading
and first makes it efficient: while the most expensive loaded bit costs more
than the cheapest unloaded bit, it moves that bit. Then it tightens the
loading: in the margin-adaptive (MA) form it removes the most expensive bits
or adds the cheapest bits until the total is B; in the rate-adaptive (RA)
form it removes bits while the power exceeds P and adds bits while the next
one fits. Two heaps with lazy deletion give the most expensive loaded bit and
the cheapest unloaded bit in O(log) time per move.

Ties are broken by the subcarrier index: the loaded bit with the largest
(cost, index) leaves first and the unloaded bit with the smallest
(cost, index) enters first. The arithmetic works with int, float or
fractions.Fraction values.
"""

import heapq

INF = float("inf")


class Loading:
    """The bits, bit count, total power and two lazy heaps of one loading."""

    def __init__(self, gains, bits, gap=1, b_max=None):
        self.g, self.b, self.gap, self.b_max = gains, list(bits), gap, b_max
        self.count = sum(self.b)
        self.power = sum(gap * (2**b - 1) / g for g, b in zip(gains, self.b))
        self.lasts = []  # entries (-cost, -i, bits) for the last loaded bit of i
        self.nexts = []  # entries (cost, i, bits) for the next bit of i
        for i in range(len(gains)):
            self._push(i)

    def _push(self, i):
        b = self.b[i]
        if b > 0:
            heapq.heappush(self.lasts, (-(self.gap * 2 ** (b - 1) / self.g[i]), -i, b))
        if self.b_max is None or b < self.b_max:
            heapq.heappush(self.nexts, (self.gap * 2**b / self.g[i], i, b))

    def max_last(self):
        """(cost, i) of the most expensive loaded bit, or (-inf, -1) if none."""
        while self.lasts and self.lasts[0][2] != self.b[-self.lasts[0][1]]:
            heapq.heappop(self.lasts)
        if not self.lasts:
            return -INF, -1
        return -self.lasts[0][0], -self.lasts[0][1]

    def min_next(self):
        """(cost, i) of the cheapest unloaded bit, or (inf, -1) if none."""
        while self.nexts and self.nexts[0][2] != self.b[self.nexts[0][1]]:
            heapq.heappop(self.nexts)
        if not self.nexts:
            return INF, -1
        return self.nexts[0][0], self.nexts[0][1]

    def remove_bit(self, i, cost):
        self.b[i], self.count, self.power = self.b[i] - 1, self.count - 1, self.power - cost
        self._push(i)

    def add_bit(self, i, cost):
        self.b[i], self.count, self.power = self.b[i] + 1, self.count + 1, self.power + cost
        self._push(i)


def levin_campello(gains, start, target_bits=None, budget=None, gap=1, b_max=None):
    """Optimal loading reached from the start loading.

    Give exactly one of target_bits (MA form) and budget (RA form).
    Returns (bits, total_power, number_of_swaps).
    """
    if (target_bits is None) == (budget is None):
        raise ValueError("give exactly one of target_bits and budget")
    if not gains or any(not g > 0 for g in gains) or len(start) != len(gains):
        raise ValueError("need positive gains and a start loading of the same length")
    if any(b < 0 or (b_max is not None and b > b_max) for b in start):
        raise ValueError("the start loading must lie in [0, b_max]")
    if budget is not None and budget < 0:
        raise ValueError("the budget must not be negative")
    if target_bits is not None and (target_bits < 0 or (b_max is not None and target_bits > b_max * len(gains))):
        raise ValueError("the target must lie in [0, N * b_max]")
    ma = target_bits is not None
    s = Loading(gains, start, gap, b_max)  # @line L1
    swaps = 0
    while True:
        (cl, m), (cn, n) = s.max_last(), s.min_next()
        if not cl > cn:  # @line L2
            break
        s.remove_bit(m, cl)  # @line L3
        s.add_bit(n, cn)
        swaps += 1
    while (s.count > target_bits) if ma else (s.power > budget):  # @line L4
        cl, m = s.max_last()
        s.remove_bit(m, cl)  # @line L5
    while True:
        cn, n = s.min_next()
        if n < 0 or ((s.count >= target_bits) if ma else (s.power + cn > budget)):  # @line L6
            break
        s.add_bit(n, cn)  # @line L7
    return s.b, s.power, swaps  # @line L8
test_levin_campello_algorithm.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/levin-campello-algorithm/. The authors are listed in prov/XEKW7B.jsonl.

import heapq
import itertools
import math
import random
from fractions import Fraction as F

import pytest

from levin_campello_algorithm import levin_campello

PAGE_GAINS = [F(20), F(9), F(5), F(3, 2)]


def power_of(gains, bits, gap=1):
    return sum(gap * (2**b - 1) / g for g, b in zip(gains, bits))


def greedy(gains, target, gap=1, b_max=None):
    """Plain greedy loading, ties to the lowest index; the reference optimum."""
    bits = [0] * len(gains)
    heap = [(gap / g, i) for i, g in enumerate(gains)]
    heapq.heapify(heap)
    for _ in range(target):
        _, i = heapq.heappop(heap)
        bits[i] += 1
        if b_max is None or bits[i] < b_max:
            heapq.heappush(heap, (gap * 2 ** bits[i] / gains[i], i))
    return bits


def brute(gains, b_max, gap, target=None, budget=None):
    best = None
    for b in itertools.product(range(b_max + 1), repeat=len(gains)):
        e = power_of(gains, b, gap)
        if target is not None and sum(b) == target:
            key = (0, e)
        elif budget is not None and e <= budget:
            key = (-sum(b), e)
        else:
            continue
        if best is None or key < best:
            best = key
    return best


def test_page_example_ma() -> None:
    bits, e, swaps = levin_campello(PAGE_GAINS, [2, 2, 2, 2], target_bits=8)
    assert bits == [4, 2, 2, 0] and e == F(101, 60) and swaps == 2


def test_page_example_ra() -> None:
    assert levin_campello(PAGE_GAINS, [3, 2, 1, 0], budget=2) == ([4, 2, 2, 0], F(101, 60), 0)
    assert levin_campello(PAGE_GAINS, [2, 2, 2, 2], budget=2) == ([4, 2, 2, 0], F(101, 60), 2)
    assert levin_campello(PAGE_GAINS, [6, 6, 6, 6], budget=2)[:2] == ([4, 2, 2, 0], F(101, 60))


def test_ma_matches_brute_force_from_any_start() -> None:
    rng = random.Random(31)
    for _ in range(120):
        n = rng.randint(1, 4)
        gains = [F(rng.randint(1, 60), rng.randint(1, 6)) for _ in range(n)]
        b_max = rng.randint(1, 6)
        target = rng.randint(0, n * b_max)
        start = [rng.randint(0, b_max) for _ in range(n)]
        bits, e, _ = levin_campello(gains, start, target_bits=target, b_max=b_max)
        assert sum(bits) == target and min(bits) >= 0 and max(bits) <= b_max
        assert e == power_of(gains, bits)
        assert (0, e) == brute(gains, b_max, 1, target=target)


def test_ra_matches_brute_force_from_any_start() -> None:
    rng = random.Random(32)
    for _ in range(120):
        n = rng.randint(1, 4)
        gains = [F(rng.randint(1, 60), rng.randint(1, 6)) for _ in range(n)]
        b_max = rng.randint(1, 6)
        gap = F(rng.randint(1, 9))
        budget = F(rng.randint(0, 400), 10)
        start = [rng.randint(0, b_max) for _ in range(n)]
        bits, e, _ = levin_campello(gains, start, budget=budget, gap=gap, b_max=b_max)
        assert e == power_of(gains, bits, gap) and e <= budget
        assert (-sum(bits), e) == brute(gains, b_max, gap, budget=budget)


def test_swaps_are_half_the_distance_to_the_optimum() -> None:
    rng = random.Random(33)
    for _ in range(200):
        n = rng.randint(2, 40)
        gains = [rng.uniform(0.1, 100) for _ in range(n)]
        start = [rng.randint(0, 8) for _ in range(n)]
        target = sum(start)
        best = greedy(gains, target)
        bits, e, swaps = levin_campello(gains, start, target_bits=target)
        assert bits == best
        assert 2 * swaps == sum(abs(a - b) for a, b in zip(start, best))
        assert abs(e - power_of(gains, best)) < 1e-9 * (1 + e)


def test_ties_never_need_more_swaps() -> None:
    rng = random.Random(34)
    for _ in range(200):
        n = rng.randint(2, 6)
        gains = [F(rng.choice([1, 2, 4, 8])) for _ in range(n)]
        start = [rng.randint(0, 5) for _ in range(n)]
        best = greedy(gains, sum(start))
        bits, e, swaps = levin_campello(gains, start, target_bits=sum(start))
        assert e == power_of(gains, best)
        assert 2 * swaps <= sum(abs(a - b) for a, b in zip(start, best))


def test_start_near_water_filling() -> None:
    rng = random.Random(35)
    n, budget, gap = 256, 300.0, 10 ** (9.8 / 10)
    gains = [rng.expovariate(1 / 1000) + 1 for _ in range(n)]
    nu = [gap / g for g in gains]
    lo, hi = 0.0, max(nu) + budget
    for _ in range(200):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if sum(max(0.0, mid - v) for v in nu) < budget else (lo, mid)
    start = [max(0, math.floor(math.log2(lo / v))) if lo > v else 0 for v in nu]
    bits, e, swaps = levin_campello(gains, start, budget=budget, gap=gap)
    ref = greedy(gains, sum(bits), gap)
    assert abs(e - power_of(gains, ref, gap)) < 1e-9 * e
    assert e <= budget
    assert power_of(gains, greedy(gains, sum(bits) + 1, gap), gap) > budget
    assert sum(bits) - sum(start) < n


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        levin_campello([1, 2], [0, 0])
    with pytest.raises(ValueError):
        levin_campello([1, 2], [0], target_bits=1)
    with pytest.raises(ValueError):
        levin_campello([1, 0], [0, 0], target_bits=1)
    with pytest.raises(ValueError):
        levin_campello([1, 2], [0, 5], target_bits=1, b_max=3)
    with pytest.raises(ValueError):
        levin_campello([1, 2], [0, 0], target_bits=7, b_max=3)
    with pytest.raises(ValueError):
        levin_campello([1, 2], [0, 0], budget=-1)
    assert levin_campello([1, 2], [3, 3], target_bits=0) == ([0, 0], 0, 0)

History

Jorge Campello studied optimal discrete loading for multicarrier systems in "Optimal discrete bit loading for multicarrier modulation systems" at ISIT 1998, and in "Practical bit loading for DMT" at ICC 1999. He defined efficient and tight loadings and gave an algorithm that starts from any loading and reaches one that is both, which is optimal. Howard Levin, in "A complete and optimal data allocation method for practical discrete multitone systems" at GLOBECOM 2001, gave an optimal allocation method for practical DMT systems. The joined name, Levin-Campello, is used in DSL texts for this family of algorithms. The optimality theory is the same as that of marginal allocation in Fox's 1966 paper.

References

  1. Jorge Campello, Practical bit loading for DMT, IEEE International Conference on Communications (ICC), 1999, pages 801 to 805, the efficiency (EF) condition, the E-tight and B-tight conditions, and the procedure that moves a start loading to an optimal one
  2. Howard E. Levin, A complete and optimal data allocation method for practical discrete multitone systems, IEEE Global Telecommunications Conference (GLOBECOM), 2001, pages 369 to 374, an optimal discrete allocation method for DMT that starts from any allocation
  3. Bennett Fox, Discrete optimization via marginal analysis, Management Science 13(3), 1966, pages 210 to 216, marginal allocation for separable convex costs, the optimality theory behind both greedy and exchange forms

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
  • a scene preset for the example