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.
- Solves
- Bit loading
- 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
- Model
- Word RAM
- Properties
- deterministicgreedyincrementalneeds csitoptimal
- Evidence
- Proof sketchCode in 1 languages
- 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 ; in the rate-adaptive form it does the same until the power fits the budget 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 has the gain , and with the gap bit on it costs , so bits cost . Each subcarrier carries at most bits. For a loading , the last cost of subcarrier is (if ) and its next cost is (if ). The margin-adaptive (MA) form asks for at the least power; the rate-adaptive (RA) form asks for the most bits with power at most . 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 bits; it is E-tight if its power is at most and adding the cheapest next bit would exceed .
The algorithm
LEVIN-CAMPELLO(g[1..N], Γ, b_max, b[1..N], B or P) ▷ b is any start loading- 1
E ← Σ_i Γ(2^(b_i) - 1)/g_i; build a max-heap of last costs and a min-heap of next costs - 2
while the largest last cost (at m) > the smallest next cost (at n) do ▷ make it efficient - 3
b_m ← b_m - 1, b_n ← b_n + 1, update E and both heaps - 4
while Σ_i b_i > B (MA) or E > P (RA) do ▷ tighten from above - 5
remove the bit with the largest last cost, update E and both heaps - 6
while Σ_i b_i < B (MA) or E + the smallest next cost ≤ P (RA) do ▷ tighten from below - 7
add the bit with the smallest next cost, update E and both heaps - 8
return (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 , , the MA target , and the flat start with power .
| 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 is the optimum that the greedy method also finds. The distance from the start to the optimum is , and each swap closed 2 of it.
For the RA form with , start from the rounded-down water-filling rates , with power . This start is already efficient (largest last cost , smallest next cost ). Line L7 adds a bit to carrier 1 for , then one to carrier 3 for , reaching ; the next bit would cost and exceed 2, so the result is again .
Correctness
Claim. From any start, the MA form returns a loading with bits and the least power, and the RA form returns the most bits within 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 smallest of all, which is the least power for 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 to the target or to the largest with . 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 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 has the next-bit costs for , where or . They are positive and strictly increasing in . A loading with is the choice of the prefix of each list, and its power is the sum of the chosen costs. Let be the set of all pairs with cost , and let be the chosen pairs. For , the last cost of is ; for , the next cost of is .
Let be the least power of a loading with bits. Since each list is increasing, the cheapest elements of form a prefix of each list, so is the sum of the smallest costs in . Since all costs are positive, 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 or ).
Lemma 1. In any loading, the largest cost in is the largest last cost, and the smallest cost in is the smallest next cost.
Proof. In list the chosen part is a prefix and the list is increasing, so its largest chosen cost is and its smallest unchosen cost is . Take the maximum and the minimum over .
Lemma 2 (efficient means optimal). An efficient loading with bits has the power .
Proof. By Lemma 1, every chosen cost is at most every unchosen cost. Sort the costs of in increasing order. Then the chosen costs are values that are each at most every other value, so as a multiset they are the smallest values, and their sum is .
Lemma 3 (the swap phase). In each pass of lines L2 and L3 with at the largest last cost and at the smallest next cost : (a) ; (b) the bit count does not change and the power falls by ; (c) the phase stops, and it stops at an efficient loading.
Proof. (a) If , then , which is false. (b) Line L3 removes the chosen element of cost and adds the unchosen element of cost . Since , the next cost of is not changed by the removal, so the new loading is a prefix of each list again. (c) The count is fixed, and each subcarrier has at most bits, so there are finitely many loadings with 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.
Lemma 4 (the number of swaps). Order totally by , 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 be the loading whose chosen set is the first elements in this order. Then the swap phase makes at most swaps, where is the start.
Proof. As in Lemma 1, the largest chosen element in this order is the largest last element , and the smallest unchosen element is the smallest next element . Suppose a swap happens, so the cost of exceeds the cost of , and comes after in the order. If , then every chosen element, which comes no later than , lies in , because is an initial segment; then , since both have elements, and , being unchosen, comes after every element of , including . This contradicts the order of and . So . In the same way, if , then every unchosen element comes no earlier than and lies outside , so and again , a contradiction. So . The swap removes and adds , so it lowers by exactly 2. The size of the symmetric difference is at the start and is never negative, which gives the bound.
When all costs are different, the phase stops only at , so the bound is met with equality.
Lemma 5 (tightening keeps efficiency). Let be efficient with bits. Removing a bit at the largest last cost gives an efficient loading with bits. Adding a bit at the smallest next cost gives an efficient loading with bits.
Proof. Removal: let be the largest last cost, at subcarrier . After the removal, the next cost of is , and the other next costs are at least by efficiency, so the smallest next cost is . The last costs are now the old ones except at , where the new last cost is or absent; all are at most . So the loading is efficient. Addition: the same argument with the roles of last and next costs exchanged; the new last cost of is , the old last costs are at most , the new next cost of is , and the other next costs are at least .
Theorem 1 (margin-adaptive form). For a target with and any start , the algorithm returns a loading with bits and the power .
Proof. By Lemma 3, after line L3 the loading is efficient with bits. If , lines L4 and L5 remove bits; if , lines L6 and L7 add bits, and a next bit exists at each step because . By Lemma 5 the loading stays efficient, so by Lemma 2 its power at the end is .
Theorem 2 (rate-adaptive form). For a budget and any start, the algorithm returns a loading with bits and the power , 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 bits and power (Lemmas 3 and 2). Lines L4 and L5 remove bits while the power exceeds ; by Lemma 5 the powers are , and since the loop stops at the largest with . Lines L6 and L7 add a bit while , where is the smallest next cost; by Lemmas 5 and 2 the sum equals . So the loop stops at the first with , or when no next bit exists. Since is increasing, the set is an interval that starts at 0, and in both phases the loop stops at its largest element, . Any loading within the budget with bits has , so .
Remark (cost). With a max-heap of last costs and a min-heap of next costs, each move of a bit costs heap work (with lazy deletion, for moves). Building the heaps costs . The total time is , where is the number of swaps plus the number of tightening steps.
Complexity
Line L1 takes 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 entries for moves, so each operation costs , and the time is with extra space; indexed heaps with a decrease-key operation bring the space to and each step to . 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 . From rounded-down water-filling, the RA form adds fewer than bits, because the integer optimum is less than 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 bits. Move bits at a time, with costs , for constellations of even size only.
- Margin-adaptive with a fixed power. To maximize a common margin for a fixed and , run the MA form and scale the power to ; the margin is .
- 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XEKW7B Edit this page History Report an error Markdown