Algorithm Search⌘K

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
Properties
continuous ratesdeterministicneeds csitoptimal
Origin
Claude E. Shannon, 1949

Water-filling power allocation divides a total power PP over NN parallel Gaussian channels so that the sum of their rates is as large as possible. Channel ii has the noise level νi>0\nu_i > 0, its noise power divided by its power gain. The best power is pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i), where the water level μ\mu is the one number that makes the powers add up to PP. So the strong channels get more power, and channels whose noise level is above μ\mu 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 ν1,…,νN>0\nu_1, \ldots, \nu_N > 0 and a total power P>0P > 0. For a channel yi=hixi+wiy_i = h_i x_i + w_i with wi∼CN(0,N0,i)w_i \sim \mathcal{CN}(0, N_{0,i}), the noise level is νi=N0,i/∣hi∣2\nu_i = N_{0,i}/|h_i|^2, the noise power referred to the input. With the power pi=E∣xi∣2p_i = E|x_i|^2 and Gaussian inputs, channel ii carries log⁡2(1+pi/νi)\log_2(1 + p_i/\nu_i) bits per complex channel use, since its SNR is pi∣hi∣2/N0,ip_i |h_i|^2 / N_{0,i}. The output is the power vector that solves

max⁡p≥0  ∑i=1Nlog⁡2 ⁣(1+piνi)subject to∑i=1Npi≤P.\max_{p \ge 0} \; \sum_{i=1}^{N} \log_2\!\left(1 + \frac{p_i}{\nu_i}\right) \quad \text{subject to} \quad \sum_{i=1}^{N} p_i \le P.

For OFDM, ii is the subcarrier and hih_i is the DFT of the channel taps at bin ii. For a MIMO channel with transmitter knowledge, νi=N0/σi2\nu_i = N_0/\sigma_i^2 for the singular values σi\sigma_i of HH.

The algorithm

  1. WATER-FILL(ν[1..N], P) ▷ ν_i > 0, P > 0
  2. 1s ← the levels ν sorted so that s[1] ≤ s[2] ≤ .. ≤ s[N]
  3. 2S ← 0, k ← 0 ▷ S = s[1] + .. + s[k]
  4. 3while k < N and k · s[k+1] < P + S do ▷ is s[k+1] below the water?
  5. 4S ← S + s[k+1], k ← k + 1
  6. 5μ ← (P + S) / k ▷ the water level
  7. 6p_i ← max(0, μ - ν_i) for i = 1 .. N
  8. 7return (p, μ)

If the first kk channels are used and the water stands at s[k+1]s[k+1], they hold k s[k+1]−Sk\, s[k+1] - S units of power. So the test of line L3 asks whether the power PP is enough to raise the water to the next step. When the answer is no, the active set is the first kk channels, and line L5 spreads PP over them so that each one reaches the same level. The first test, with k=0k = 0, is 0<P0 < P, so at least one channel is active.

Example

Take the noise levels ν=(1,2,4)\nu = (1, 2, 4) and P=3P = 3.

kk s[k+1]s[k+1] k⋅s[k+1]k \cdot s[k+1] P+SP + S test of L3
0 1 0 3 true, S=1S = 1
1 2 2 4 true, S=3S = 3
2 4 8 6 false

So two channels are active and μ=(3+3)/2=3\mu = (3 + 3)/2 = 3. The powers are p=(2,1,0)p = (2, 1, 0): 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 log⁡23+log⁡21.5=2.1699\log_2 3 + \log_2 1.5 = 2.1699 bits per channel use. Equal power, p=(1,1,1)p = (1, 1, 1), gives log⁡22+log⁡21.5+log⁡21.25=1.9069\log_2 2 + \log_2 1.5 + \log_2 1.25 = 1.9069 bits.

The level depends on PP. With the same channels, P=0.5P = 0.5 gives μ=1.5\mu = 1.5 and puts all the power on the best channel. P=10P = 10 gives μ=17/3\mu = 17/3, all three channels active, and the powers (4.667,3.667,1.667)(4.667, 3.667, 1.667) for 4.5075 bits. As PP grows, the differences νi\nu_i become small next to μ\mu, and water-filling approaches equal power.

A second case: ν=(0.5,1,1.5,3)\nu = (0.5, 1, 1.5, 3) and P=2P = 2. The loop stops at k=3k = 3, because 3⋅3=93 \cdot 3 = 9 is not less than 2+3=52 + 3 = 5. Then μ=5/3\mu = 5/3, the powers are (7/6,2/3,1/6,0)(7/6, 2/3, 1/6, 0), and the sum rate is 2.6259 bits.

Correctness

Claim. WATER-FILL returns the unique optimal power vector of the problem above, and μ\mu is the unique solution of ∑imax⁡(0,μ−νi)=P\sum_i \max(0, \mu - \nu_i) = P.

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 νi+pi=μ\nu_i + p_i = \mu on each channel with pi>0p_i > 0, and that νi≥μ\nu_i \ge \mu on each channel with pi=0p_i = 0. That is pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i). The function f(t)=∑imax⁡(0,t−νi)f(t) = \sum_i \max(0, t - \nu_i) is continuous and strictly increasing for t≥s[1]t \ge s[1], so exactly one μ\mu gives f(μ)=Pf(\mu) = P. For sorted levels, f(s[k+1])=k s[k+1]−Sf(s[k+1]) = k\, s[k+1] - S, so the test of line L3 is f(s[k+1])<Pf(s[k+1]) < P, which holds exactly when s[k+1]<μs[k+1] < \mu. The loop therefore stops with kk equal to the number of levels below μ\mu, and line L5 solves f(μ)=Pf(\mu) = P 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 ν1,…,νN>0\nu_1, \ldots, \nu_N > 0 and the power is P>0P > 0. The problem is

max⁡p  R(p)=∑i=1Nlog⁡2 ⁣(1+piνi)subject to∑i=1Npi≤P,pi≥0.(1)\max_{p} \; R(p) = \sum_{i=1}^{N} \log_2\!\left(1 + \frac{p_i}{\nu_i}\right) \quad \text{subject to} \quad \sum_{i=1}^N p_i \le P, \quad p_i \ge 0. \tag{1}

Lemma 1 (existence and uniqueness). Problem (1) has exactly one optimal point.

Proof. The feasible set is closed, bounded and not empty, and RR is continuous on it, so a maximum exists. Each term log⁡2(1+pi/νi)\log_2(1 + p_i/\nu_i) is strictly concave in pip_i on pi>−νip_i > -\nu_i, so RR is strictly concave. If p≠qp \ne q were both optimal, the midpoint would be feasible, because the set is convex, and would give R((p+q)/2)>(R(p)+R(q))/2=R(p)R((p+q)/2) > (R(p) + R(q))/2 = R(p), a contradiction. □\square

Lemma 2 (KKT form). A feasible pp is optimal if and only if there is a μ>0\mu > 0 with pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i) for every ii and ∑ipi=P\sum_i p_i = P.

Proof. The objective is concave and differentiable on a neighborhood of the feasible set, the constraints are affine, and the point pi=P/(2N)p_i = P/(2N) satisfies all of them strictly. So Slater's condition holds, and the KKT conditions are necessary and sufficient for optimality. With the multiplier λ≥0\lambda \ge 0 for the sum constraint and κi≥0\kappa_i \ge 0 for pi≥0p_i \ge 0, they read

1(νi+pi)ln⁡2=λ−κi,κipi=0,λ(∑ipi−P)=0.\frac{1}{(\nu_i + p_i)\ln 2} = \lambda - \kappa_i, \qquad \kappa_i p_i = 0, \qquad \lambda\Big(\sum_i p_i - P\Big) = 0.

The left side is positive, so λ>κi≥0\lambda > \kappa_i \ge 0, and then the sum constraint holds with equality. Put μ=1/(λln⁡2)>0\mu = 1/(\lambda \ln 2) > 0. If pi>0p_i > 0, then κi=0\kappa_i = 0 and νi+pi=μ\nu_i + p_i = \mu, so pi=μ−νi>0p_i = \mu - \nu_i > 0. If pi=0p_i = 0, then 1/(νiln⁡2)=λ−κi≤λ1/(\nu_i \ln 2) = \lambda - \kappa_i \le \lambda, so νi≥μ\nu_i \ge \mu and max⁡(0,μ−νi)=0=pi\max(0, \mu - \nu_i) = 0 = p_i. In both cases pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i).

Conversely, let pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i) with ∑pi=P\sum p_i = P and μ>0\mu > 0. Set λ=1/(μln⁡2)\lambda = 1/(\mu \ln 2), κi=0\kappa_i = 0 where νi<μ\nu_i < \mu, and κi=λ−1/(νiln⁡2)≥0\kappa_i = \lambda - 1/(\nu_i \ln 2) \ge 0 where νi≥μ\nu_i \ge \mu. Then all KKT conditions hold, so pp is optimal. □\square

Lemma 3 (the water level). Let f(t)=∑imax⁡(0,t−νi)f(t) = \sum_i \max(0, t - \nu_i) and let s[1]≤⋯≤s[N]s[1] \le \cdots \le s[N] be the sorted levels. Then f(s[1])=0f(s[1]) = 0, ff is continuous, and ff is strictly increasing on [s[1],∞)[s[1], \infty) with f(t)→∞f(t) \to \infty. So there is exactly one μ\mu with f(μ)=Pf(\mu) = P, and μ>s[1]\mu > s[1].

Proof. Each term is continuous and nondecreasing, and the term of s[1]s[1] equals t−s[1]t - s[1], which is strictly increasing and unbounded. At t=s[1]t = s[1] every term is 0. The intermediate value theorem gives a solution of f(μ)=Pf(\mu) = P in (s[1],s[1]+P](s[1], s[1] + P], and strict monotonicity makes it unique. □\square

By Lemmas 1 to 3, the unique optimum is pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i) with the μ\mu of Lemma 3. It remains to show that WATER-FILL computes this μ\mu.

Lemma 4 (the test of line L3). For 0≤k<N0 \le k < N, let Sk=s[1]+⋯+s[k]S_k = s[1] + \cdots + s[k]. Then f(s[k+1])=k s[k+1]−Skf(s[k+1]) = k\, s[k+1] - S_k, and the test k s[k+1]<P+Skk\, s[k+1] < P + S_k holds if and only if s[k+1]<μs[k+1] < \mu.

Proof. For j≤kj \le k, s[j]≤s[k+1]s[j] \le s[k+1], so the term is s[k+1]−s[j]s[k+1] - s[j]. For j>kj > k, s[j]≥s[k+1]s[j] \ge s[k+1], so the term is 0. Summing gives the formula. The test is therefore f(s[k+1])<P=f(μ)f(s[k+1]) < P = f(\mu). Since s[k+1]≥s[1]s[k+1] \ge s[1] and ff is strictly increasing on [s[1],∞)[s[1], \infty), this holds if and only if s[k+1]<μs[k+1] < \mu. □\square

Theorem. WATER-FILL returns the unique optimal powers of (1) and the water level μ\mu.

Proof. Let k∗=∣{j:s[j]<μ}∣k^* = |\{j : s[j] < \mu\}|. By Lemma 3, s[1]<μs[1] < \mu, so k∗≥1k^* \ge 1. Because the list is sorted, s[j]<μs[j] < \mu exactly for j≤k∗j \le k^*. Invariant of the loop: at the start of each test, S=SkS = S_k and k≤k∗k \le k^*. It holds at the start with k=0k = 0. If k<k∗k < k^*, then s[k+1]<μs[k+1] < \mu, and by Lemma 4 the test is true, so the body runs and keeps the invariant with k+1≤k∗k + 1 \le k^*. If k=k∗<Nk = k^* < N, then s[k+1]≥μs[k+1] \ge \mu, and the test is false. If k=Nk = N, the loop stops by its first condition. So the loop stops with k=k∗k = k^* after k∗k^* iterations. Then

P=f(μ)=∑j≤k∗(μ−s[j])=k∗μ−Sk∗,P = f(\mu) = \sum_{j \le k^*} (\mu - s[j]) = k^* \mu - S_{k^*},

so μ=(P+S)/k\mu = (P + S)/k, which is line L5. Line L6 forms pi=max⁡(0,μ−νi)p_i = \max(0, \mu - \nu_i), the optimum by Lemmas 1 and 2. □\square

Remark (termination and cost). The loop variable kk grows by 1 in each iteration and is at most NN, so the loop stops after at most NN iterations of constant work. The sort of line L1 costs O(Nlog⁡N)O(N \log N) comparisons, and lines L5 and L6 cost O(N)O(N).

Remark (the rate). At the optimum, the active channels have 1+pi/νi=μ/νi1 + p_i/\nu_i = \mu/\nu_i, so R=∑j≤k∗log⁡2(μ/s[j])R = \sum_{j \le k^*} \log_2(\mu/s[j]). For ν=(1,2,4)\nu = (1, 2, 4) and P=3P = 3 this is log⁡23+log⁡21.5\log_2 3 + \log_2 1.5.

Complexity

In the real RAM, line L1 sorts in O(Nlog⁡N)O(N \log N) time. The loop of lines L3 and L4 runs at most NN times with O(1)O(1) work each, and line L6 takes O(N)O(N). So the time is O(Nlog⁡N)O(N \log N) in the worst case, and the extra space is O(N)O(N) for the sorted copy. If the levels arrive sorted, the time is O(N)O(N). 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 O(N)O(N) worst-case time. A bisection on μ\mu costs O(N)O(N) per step and needs about log⁡2(P/ϵ)\log_2(P/\epsilon) steps for the accuracy ϵ\epsilon; 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 νi+pi=μ\nu_i + p_i = \mu. In the dual view, μ=1/(λln⁡2)\mu = 1/(\lambda \ln 2), where λ\lambda 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 P≤s[2]−s[1]P \le s[2] - s[1], all the power goes to the best channel. As P→∞P \to \infty, every channel becomes active and pi−P/N→νˉ−νip_i - P/N \to \bar\nu - \nu_i, where νˉ\bar\nu is the mean noise level; the rate gain over equal power tends to 0.
  • Rate. The sum rate is ∑i≤klog⁡2(μ/ν(i))\sum_{i \le k} \log_2(\mu / \nu_{(i)}) 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 log⁡2M\log_2 M, and the best allocation is different (see Variants).

Variants and improvements

  • Water-filling with a gap. With a practical code, channel ii carries about log⁡2(1+pi/(Γνi))\log_2(1 + p_i/(\Gamma \nu_i)) bits, where Γ\Gamma is the SNR gap. This is water-filling on the levels Γνi\Gamma \nu_i.
  • 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 ∑iwilog⁡2(1+pi/νi)\sum_i w_i \log_2(1 + p_i/\nu_i) gives pi=max⁡(0,wiμ−νi)p_i = \max(0, w_i \mu - \nu_i), a water level that differs per channel.
  • Peak limits per channel. With pi≤cip_i \le c_i, as under a spectral mask, the answer is pi=min⁡(ci,max⁡(0,μ−νi))p_i = \min(c_i, \max(0, \mu - \nu_i)), and μ\mu 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 γ\gamma is max⁡(0,1/γ0−1/γ)\max(0, 1/\gamma_0 - 1/\gamma) 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 νi=N0,i/∣hi∣2\nu_i = N_{0,i}/|h_i|^2, not the gain. Passing ∣hi∣2|h_i|^2 gives the most power to the worst channel.
  • dB values. The formula works on linear values. Convert νi\nu_i and PP from dB first.
  • The wrong active set. Spreading PP 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 μ\mu.
  • Ties. Equal noise levels are in or out together. The strict test << in line L3 keeps a channel whose level equals μ\mu out, which is correct, because its power would be 0.
  • Stale channel knowledge. The allocation is only as good as the estimates of νi\nu_i. 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 ln⁡\ln. The allocation is the same, but the rate differs by the factor ln⁡2\ln 2.

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.

water_filling_power_allocation.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

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