Algorithmcore
Water-filling power allocation
Also called water-pouring algorithm.
Splits a power budget over parallel Gaussian channels as p_i = max(0, mu - nu_i), filling up to a common water level mu above each noise level. This maximizes the sum rate.
- Time
- O(N log N) worst
- Space
- O(N) extra
- Where
- N = the number of parallel channels
- Model
- Real RAM
- Properties
- continuous ratesdeterministicneeds csitoptimal
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Claude E. Shannon, 1949
Water-filling power allocation divides a total power over parallel Gaussian channels so that the sum of their rates is as large as possible. Channel has the noise level , its noise power divided by its power gain. The best power is , where the water level is the one number that makes the powers add up to . So the strong channels get more power, and channels whose noise level is above get none. The optimality is a direct consequence of the KKT conditions. The same allocation gives the capacity of an OFDM link with a known channel, of a MIMO channel over its singular values (see SVD precoding and MIMO capacity), and of a fading channel over time. With integer bits per channel the problem is bit loading, and the SNR gap turns the capacity formula into a rule for real constellations.
In plain words
Picture a tank whose floor has steps of different heights, one step for each channel. The height of a step is the noise of that channel. Pour a fixed amount of water into the tank. The water settles at one flat level. Deep steps, the quiet channels, hold a lot of water. High steps, the noisy channels, hold a little. A step that sticks out above the water holds none.
The water is the power. Each channel gets the amount of water above its step. This split gives the largest total data rate, because the next small unit of power always does the most good where the water is lowest above the floor, and pouring makes all the used channels equal in that sense.
The problem
The input is a list of noise levels and a total power . For a channel with , the noise level is , the noise power referred to the input. With the power and Gaussian inputs, channel carries bits per complex channel use, since its SNR is . The output is the power vector that solves
For OFDM, is the subcarrier and is the DFT of the channel taps at bin . For a MIMO channel with transmitter knowledge, for the singular values of .
The algorithm
WATER-FILL(ν[1..N], P) ▷ ν_i > 0, P > 0- 1
s ← the levels ν sorted so that s[1] ≤ s[2] ≤ .. ≤ s[N] - 2
S ← 0, k ← 0 ▷ S = s[1] + .. + s[k] - 3
while k < N and k · s[k+1] < P + S do ▷ is s[k+1] below the water? - 4
S ← S + s[k+1], k ← k + 1 - 5
μ ← (P + S) / k ▷ the water level - 6
p_i ← max(0, μ - ν_i) for i = 1 .. N - 7
return (p, μ)
If the first channels are used and the water stands at , they hold units of power. So the test of line L3 asks whether the power is enough to raise the water to the next step. When the answer is no, the active set is the first channels, and line L5 spreads over them so that each one reaches the same level. The first test, with , is , so at least one channel is active.
Example
Take the noise levels and .
| test of L3 | ||||
|---|---|---|---|---|
| 0 | 1 | 0 | 3 | true, |
| 1 | 2 | 2 | 4 | true, |
| 2 | 4 | 8 | 6 | false |
So two channels are active and . The powers are : the water stands 2 above the first step and 1 above the second, and the third step, at 4, is dry. The sum rate is bits per channel use. Equal power, , gives bits.
The level depends on . With the same channels, gives and puts all the power on the best channel. gives , all three channels active, and the powers for 4.5075 bits. As grows, the differences become small next to , and water-filling approaches equal power.
A second case: and . The loop stops at , because is not less than . Then , the powers are , and the sum rate is 2.6259 bits.
Correctness
Claim. WATER-FILL returns the unique optimal power vector of the problem above, and is the unique solution of .
Key steps. The objective is a sum of strictly concave functions and the constraints are linear, so the KKT conditions are necessary and sufficient, and the optimum is unique. They say that the power constraint holds with equality, that on each channel with , and that on each channel with . That is . The function is continuous and strictly increasing for , so exactly one gives . For sorted levels, , so the test of line L3 is , which holds exactly when . The loop therefore stops with equal to the number of levels below , and line L5 solves on that set. The full proof is in the proofs folder.
Proof: Water-filling is the unique optimal power allocation, and WATER-FILL finds its water levelfull
The levels are and the power is . The problem is
Lemma 1 (existence and uniqueness). Problem (1) has exactly one optimal point.
Proof. The feasible set is closed, bounded and not empty, and is continuous on it, so a maximum exists. Each term is strictly concave in on , so is strictly concave. If were both optimal, the midpoint would be feasible, because the set is convex, and would give , a contradiction.
Lemma 2 (KKT form). A feasible is optimal if and only if there is a with for every and .
Proof. The objective is concave and differentiable on a neighborhood of the feasible set, the constraints are affine, and the point satisfies all of them strictly. So Slater's condition holds, and the KKT conditions are necessary and sufficient for optimality. With the multiplier for the sum constraint and for , they read
The left side is positive, so , and then the sum constraint holds with equality. Put . If , then and , so . If , then , so and . In both cases .
Conversely, let with and . Set , where , and where . Then all KKT conditions hold, so is optimal.
Lemma 3 (the water level). Let and let be the sorted levels. Then , is continuous, and is strictly increasing on with . So there is exactly one with , and .
Proof. Each term is continuous and nondecreasing, and the term of equals , which is strictly increasing and unbounded. At every term is 0. The intermediate value theorem gives a solution of in , and strict monotonicity makes it unique.
By Lemmas 1 to 3, the unique optimum is with the of Lemma 3. It remains to show that WATER-FILL computes this .
Lemma 4 (the test of line L3). For , let . Then , and the test holds if and only if .
Proof. For , , so the term is . For , , so the term is 0. Summing gives the formula. The test is therefore . Since and is strictly increasing on , this holds if and only if .
Theorem. WATER-FILL returns the unique optimal powers of (1) and the water level .
Proof. Let . By Lemma 3, , so . Because the list is sorted, exactly for . Invariant of the loop: at the start of each test, and . It holds at the start with . If , then , and by Lemma 4 the test is true, so the body runs and keeps the invariant with . If , then , and the test is false. If , the loop stops by its first condition. So the loop stops with after iterations. Then
so , which is line L5. Line L6 forms , the optimum by Lemmas 1 and 2.
Remark (termination and cost). The loop variable grows by 1 in each iteration and is at most , so the loop stops after at most iterations of constant work. The sort of line L1 costs comparisons, and lines L5 and L6 cost .
Remark (the rate). At the optimum, the active channels have , so . For and this is .
Complexity
In the real RAM, line L1 sorts in time. The loop of lines L3 and L4 runs at most times with work each, and line L6 takes . So the time is in the worst case, and the extra space is for the sorted copy. If the levels arrive sorted, the time is . Without the sort, a search for the active count by repeated median selection, as in the linear-time algorithm for the fractional knapsack problem, also runs in worst-case time. A bisection on costs per step and needs about steps for the accuracy ; it is simple and is the usual choice when the constraint has extra terms.
Properties
- One water level. All active channels end at the same total . In the dual view, , where is the Lagrange multiplier of the power constraint, the rate gained per unit of extra power.
- Monotone in the channel. A channel with a lower noise level never gets less power than a channel with a higher one.
- Low and high power. For , all the power goes to the best channel. As , every channel becomes active and , where is the mean noise level; the rate gain over equal power tends to 0.
- Rate. The sum rate is over the active channels.
- Gaussian inputs. The rate formula and so the optimality assume Gaussian codebooks. With a fixed constellation such as QAM, the rate of each channel saturates at , and the best allocation is different (see Variants).
Variants and improvements
- Water-filling with a gap. With a practical code, channel carries about bits, where is the SNR gap. This is water-filling on the levels .
- Integer bits. Rounding the water-filling rates gives a good start for bit loading, and the Hughes-Hartogs and Levin-Campello algorithms find the best integer loading.
- Weighted sum rate. Maximizing gives , a water level that differs per channel.
- Peak limits per channel. With , as under a spectral mask, the answer is , and is found by the same search.
- Water-filling over time. For a fading channel with the gain known at both ends and an average power limit, the power at the SNR is times the average power (Goldsmith and Varaiya 1997). Truncated channel inversion and adaptive modulation are the practical forms.
- Finite constellations. Lozano, Tulino and Verdú (2006) gave the best allocation for arbitrary input distributions, called mercury/water-filling. It puts less power on strong channels whose constellation is already saturated.
- Many users. Iterative water-filling lets each user water-fill against the interference of the others; for the Gaussian vector multiple-access channel it converges to the sum capacity (Yu, Rhee, Boyd and Cioffi 2004).
- Reverse water-filling. The rate-distortion function of parallel Gaussian sources has the dual form, with a water level on the variances.
When to use it
Use water-filling when the transmitter knows the gain of each parallel channel, as in DSL modems, OFDM with channel feedback, and MIMO with transmitter knowledge, and when the codes are good enough that the gap model holds. At high SNR the gain over equal power is small, and many systems use equal power on the active channels. When the rates must be integers, use water-filling for the start and a bit loading algorithm for the end.
Pitfalls
- Gains in place of noise levels. The input is the noise-to-gain ratio , not the gain. Passing gives the most power to the worst channel.
- dB values. The formula works on linear values. Convert and from dB first.
- The wrong active set. Spreading over all channels and then clipping negative powers to zero breaks the power constraint. The active set must be found first, as in line L3, or by a search on .
- Ties. Equal noise levels are in or out together. The strict test in line L3 keeps a channel whose level equals out, which is correct, because its power would be 0.
- Stale channel knowledge. The allocation is only as good as the estimates of . A channel that is weaker than the transmitter believes gets too much rate and causes errors; a margin, or the outer loop of link adaptation, protects against this.
- Nats and bits. Some texts use . The allocation is the same, but the rate differs by the factor .
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/water-filling-power-allocation/. The authors are listed in prov/1Y9CA5.jsonl.
"""Water-filling power allocation over N parallel Gaussian channels.
Channel i has the noise level nu[i] > 0, the noise power divided by the power
gain of the channel. With the power p[i] it carries log2(1 + p[i] / nu[i])
bits per channel use. The allocation that maximizes the sum of the rates under
sum(p) = P is p[i] = max(0, mu - nu[i]), where the water level mu makes the
powers add up to P. The function sorts the levels once and finds the number
of active channels with one pass, so it costs O(N log N).
"""
import math
def water_filling(nu: list[float], power: float) -> tuple[list[float], float]:
"""The powers p[i] = max(0, mu - nu[i]) with sum P, and the water level mu."""
if not nu or any(not v > 0 for v in nu):
raise ValueError("need at least one channel and positive noise levels")
if power < 0:
raise ValueError("the total power must not be negative")
if power == 0:
return [0.0] * len(nu), min(nu)
s = sorted(nu) # @line L1
total, k = 0.0, 0 # @line L2
while k < len(s) and k * s[k] < power + total: # @line L3
total, k = total + s[k], k + 1 # @line L4
mu = (power + total) / k # @line L5
p = [max(0.0, mu - v) for v in nu] # @line L6
return p, mu # @line L7
def sum_rate(nu: list[float], p: list[float]) -> float:
"""The sum over i of log2(1 + p[i] / nu[i]), in bits per channel use."""
return sum(math.log2(1 + pi / v) for pi, v in zip(p, nu))
def water_level_by_bisection(nu: list[float], power: float, iters: int = 200) -> float:
"""A second method: bisection on mu for sum(max(0, mu - nu[i])) = P."""
lo, hi = min(nu), max(nu) + power
for _ in range(iters):
mid = (lo + hi) / 2
if sum(max(0.0, mid - v) for v in nu) < power:
lo = mid
else:
hi = mid
return (lo + hi) / 2
def noise_levels(gains: list[complex], n0: list[float] | float, gap: float = 1.0) -> list[float]:
"""nu[i] = gap * N0[i] / |h[i]|^2 for channel gains h[i] and noise densities N0[i]."""
if not isinstance(n0, list):
n0 = [n0] * len(gains)
return [gap * w / abs(h) ** 2 for h, w in zip(gains, n0)]
test_water_filling_power_allocation.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/water-filling-power-allocation/. The authors are listed in prov/1Y9CA5.jsonl.
import itertools
import math
import random
import pytest
from water_filling_power_allocation import noise_levels, sum_rate, water_filling, water_level_by_bisection
def test_check_value() -> None:
p, mu = water_filling([1, 2, 4], 3)
assert abs(mu - 3) < 1e-12
assert all(abs(a - b) < 1e-12 for a, b in zip(p, [2, 1, 0]))
assert abs(sum_rate([1, 2, 4], p) - (math.log2(3) + math.log2(1.5))) < 1e-12
assert abs(sum_rate([1, 2, 4], p) - 2.169925) < 1e-6
def test_second_example_on_the_page() -> None:
p, mu = water_filling([0.5, 1, 1.5, 3], 2)
assert abs(mu - 5 / 3) < 1e-12
assert abs(p[3]) == 0
assert abs(sum_rate([0.5, 1, 1.5, 3], p) - 2.625934) < 1e-6
p, mu = water_filling([1, 2, 4], 10)
assert abs(mu - 17 / 3) < 1e-12 and min(p) > 0
p, mu = water_filling([1, 2, 4], 0.5)
assert abs(mu - 1.5) < 1e-12 and p[1] == 0 and p[2] == 0
def kkt_ok(nu, power, p, mu, tol=1e-9):
if abs(sum(p) - power) > tol or min(p) < 0:
return False
for v, pi in zip(nu, p):
if pi > 0 and abs(v + pi - mu) > tol:
return False
if pi == 0 and v < mu - tol:
return False
return True
def test_kkt_and_power_on_random_channels() -> None:
rng = random.Random(11)
for _ in range(300):
n = rng.randint(1, 64)
nu = [rng.expovariate(1.0) + 1e-3 for _ in range(n)]
power = rng.uniform(0.01, 20)
p, mu = water_filling(nu, power)
assert kkt_ok(nu, power, p, mu)
assert abs(mu - water_level_by_bisection(nu, power)) < 1e-9
def test_order_and_ties() -> None:
nu = [2.0, 0.5, 2.0, 7.0, 0.5]
p, mu = water_filling(nu, 4)
assert kkt_ok(nu, 4, p, mu)
assert p[0] == p[2] and p[1] == p[4]
rng = random.Random(3)
for _ in range(20):
perm = list(range(5))
rng.shuffle(perm)
q, mu2 = water_filling([nu[i] for i in perm], 4)
assert abs(mu2 - mu) < 1e-12
assert all(abs(q[j] - p[perm[j]]) < 1e-12 for j in range(5))
def test_against_grid_search() -> None:
rng = random.Random(5)
for n in (2, 3):
for _ in range(6):
nu = [rng.uniform(0.1, 3) for _ in range(n)]
power = rng.uniform(0.5, 4)
p, _ = water_filling(nu, power)
best = sum_rate(nu, p)
steps = 120
grid = 0.0
for c in itertools.product(range(steps + 1), repeat=n - 1):
if sum(c) > steps:
continue
q = [power * x / steps for x in c] + [power * (steps - sum(c)) / steps]
grid = max(grid, sum_rate(nu, q))
assert grid <= best + 1e-12
assert best - grid < 1e-3
def test_random_feasible_moves_do_not_help() -> None:
rng = random.Random(8)
nu = [rng.uniform(0.1, 2) for _ in range(16)]
p, _ = water_filling(nu, 5)
best = sum_rate(nu, p)
for _ in range(2000):
i, j = rng.sample(range(16), 2)
d = rng.uniform(0, p[i]) if p[i] > 0 else 0.0
q = list(p)
q[i] -= d
q[j] += d
assert sum_rate(nu, q) <= best + 1e-12
def test_gap_and_noise_levels() -> None:
nu = noise_levels([1 + 1j, 0.5j, 2], 0.5, gap=2.0)
assert all(abs(a - b) < 1e-12 for a, b in zip(nu, [0.5, 4.0, 0.25]))
p, _ = water_filling(nu, 1)
assert p[1] == 0
def test_bad_input() -> None:
with pytest.raises(ValueError):
water_filling([], 1)
with pytest.raises(ValueError):
water_filling([1, 0], 1)
with pytest.raises(ValueError):
water_filling([1], -1)
assert water_filling([3, 1], 0) == ([0.0, 0.0], 1)
History
Shannon's 1949 paper found the best signal spectrum for a channel with noise that is not white: the signal power plus the noise power is constant over the band that is used, and no power goes where the noise is above that level. The parallel channel form, with the picture of water poured over an uneven floor, became standard in information theory texts, and Cover and Thomas give it for parallel Gaussian channels and for colored noise. In the late 1980s and 1990s it became an engineering tool for multicarrier modems, where the transmitter learns the SNR of each subcarrier and loads it, and later for MIMO with feedback.
References
- Thomas M. Cover and Joy A. Thomas, Elements of Information Theory, second edition, Wiley, 2006, Section 9.4 (parallel Gaussian channels, the water-filling solution) and Section 9.5 (channels with colored Gaussian noise)
- David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Chapter 5 (water-filling over the subcarriers of a frequency-selective channel, and over time for a fading channel with transmitter side information)
- Andrea Goldsmith, Wireless Communications, Cambridge University Press, 2005, Chapter 4 (capacity of fading channels with side information at the transmitter and of frequency-selective channels)
- Claude E. Shannon, Communication in the presence of noise, Proceedings of the IRE 37(1), 1949, pages 10 to 21, the capacity of a band with noise of arbitrary spectrum and the best distribution of the signal power
Where this leads
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 1Y9CA5 Edit this page History Report an error Markdown