Algorithm Search⌘K

Algorithmcore

Max-rate scheduling

Also called max C/I scheduling, maximum throughput scheduling.

Gives each resource to the user with the highest instantaneous rate, which maximizes throughput but ignores fairness.

Time
O(T K N) worst
Space
O(K) extra
Where
K = the number of users; N = the number of resources per slot; T = the number of slots
Properties
deterministicnot fairgreedymaximizes total rateneeds channel state
Origin
Raymond Knopp, Pierre A. Humblet, 1995

Max-rate scheduling, also called max C/I scheduling, is the rule that gives each resource (a time slot, a subcarrier or a resource block) to the user who can get the highest rate on it at that moment. The rate comes from the channel quality that each user reports. Because the total rate of a slot is a sum over its resources, and each term is as large as it can be, the rule gets the largest total throughput of any scheduler that gives each resource to one user, in every slot and so over any horizon. The gain over a fixed turn grows with the number of users, because some user is usually near a peak of its fading; this is multiuser diversity. The cost is fairness: a user whose channel is weaker on average, for example because it is far from the base station, is almost never the best and may get nothing. Proportional fair scheduling keeps most of the gain and serves every user.

In plain words

Several users share one radio channel, and each user's signal changes from moment to moment. Before each short time slot, every user tells the base station how fast it could receive right now. The base station gives the slot to the user with the highest speed. If two users are equally fast, it picks the one with the lower number. This sends the most data in total, because each slot is used at its best speed. But a user with a weak signal most of the time almost never wins, so it waits for a very long time or gets nothing. That is why real systems mix this rule with some form of fairness.

The problem

There are KK users and, in each of TT slots, NN resources. In slot tt, user kk can get the rate rk,n(t)≥0r_{k,n}(t) \ge 0 on resource nn, in bits per slot. The rates are known at the start of the slot, from channel reports and the adaptive modulation table. A schedule gives each resource of each slot to one user at(n)∈{1,…,K}a_t(n) \in \{1, \ldots, K\}; user kk is then served

Sk=∑t=1T∑n:at(n)=krk,n(t).S_k = \sum_{t=1}^{T} \sum_{n : a_t(n) = k} r_{k,n}(t).

The problem asks for the schedule with the largest total ∑kSk\sum_k S_k, using in slot tt only the rates known at slot tt.

The algorithm

  1. MAX-RATE(r)
  2. 1for t ← 1 to T do
  3. 2for n ← 1 to N do
  4. 3k* ← the smallest k with r_{k,n}(t) = max_j r_{j,n}(t)
  5. 4give resource n of slot t to user k*
  6. 5S_{k*} ← S_{k*} + r_{k*,n}(t)
  7. 6return the assignment and S

Line L3 is one pass over the users. The tie rule makes the result deterministic; any user in the set of best users gives the same total.

Example

Three users and six slots with one resource each. User 3 is far from the base station. The rates, in bit/s/Hz:

slot 1 2 3 4 5 6
user 1 2.1 3.4 1.2 4.0 2.5 0.8
user 2 3.0 1.1 2.6 2.2 3.3 2.9
user 3 0.9 1.0 1.9 0.7 1.2 1.5

Max-rate scheduling serves the bold entries: users 2,1,2,1,2,22, 1, 2, 1, 2, 2, for a total of 19.219.2. User 1 gets 7.47.4, user 2 gets 11.811.8, and user 3 gets 00. Round robin in the order 1,2,3,1,2,31, 2, 3, 1, 2, 3 gets 2.1+1.1+1.9+4.0+3.3+1.5=13.92.1 + 1.1 + 1.9 + 4.0 + 3.3 + 1.5 = 13.9, which is 28%28\% less, but it serves user 3 with 3.43.4.

Who wins how often. Let the users' channel gains be independent and Rayleigh faded, so each gain is exponential, with means m1,…,mKm_1, \ldots, m_K. With λk=1/mk\lambda_k = 1/m_k, user ii is the best with probability

Pr⁡[i wins]=∫0∞λie−λix∏j≠i(1−e−λjx) dx=∑S⊆{j≠i}(−1)∣S∣λiλi+∑j∈Sλj,\Pr[i \text{ wins}] = \int_0^\infty \lambda_i e^{-\lambda_i x} \prod_{j \ne i} \big(1 - e^{-\lambda_j x}\big)\, dx = \sum_{S \subseteq \{j \ne i\}} (-1)^{|S|} \frac{\lambda_i}{\lambda_i + \sum_{j \in S} \lambda_j},

by inclusion-exclusion. For means 1,2,41, 2, 4 (the users are 3 dB apart), the shares of slots are 11/105=10.5%11/105 = 10.5\%, 30/105=28.6%30/105 = 28.6\% and 64/105=61.0%64/105 = 61.0\%. With equal means each user wins 1/K1/K of the slots, and max-rate scheduling is then fair in the long run.

Throughput. With KK users of equal mean SNR γˉ\bar\gamma and i.i.d. Rayleigh fading, the mean rate is E[log⁡2(1+γˉX)]\mathbb E[\log_2(1 + \bar\gamma X)] with XX the largest of KK unit exponentials. At γˉ=10\bar\gamma = 10 dB it is 2.9072.907, 3.6593.659, 4.2434.243, 4.6874.687, 5.0345.034 and 5.5525.552 bit/s/Hz for K=1,2,4,8,16,64K = 1, 2, 4, 8, 16, 64, and E[X]=1+1/2+⋯+1/K\mathbb E[X] = 1 + 1/2 + \cdots + 1/K.

Correctness

Claim. In each slot, the assignment of lines L2 to L4 has the largest total rate of all KNK^N assignments, and of those with the largest total it is the first in lexicographic order. Over TT slots, the schedule has the largest total ∑kSk\sum_k S_k among all schedules.

Key steps. The total of slot tt is ∑nra(n),n(t)\sum_n r_{a(n), n}(t), a sum of NN terms, where the term of resource nn depends only on a(n)a(n). So the sum is largest exactly when each term is largest, that is, when each a(n)a(n) is a best user for resource nn, and line L3 picks one. Among these assignments, the one with the smallest index in each place is the first in lexicographic order. The total over the horizon is the sum of the slot totals, and the choice in one slot does not change the rates of another, so the largest total is the sum of the per-slot largest totals. The share and mean-rate formulas follow from the tail Pr⁡[X>x]=1−(1−e−x)K\Pr[X > x] = 1 - (1 - e^{-x})^K. The full proof is in the proofs folder.

Proof: Max-rate scheduling has the largest total rate in every slot, and the share and mean-rate formulas holdfull

The users k=1,…,Kk = 1, \ldots, K, resources n=1,…,Nn = 1, \ldots, N, slots t=1,…,Tt = 1, \ldots, T and rates rk,n(t)≥0r_{k,n}(t) \ge 0 are as on the page. An assignment of slot tt is a map a:{1,…,N}→{1,…,K}a : \{1, \ldots, N\} \to \{1, \ldots, K\}, and its total is Vt(a)=∑nra(n),n(t)V_t(a) = \sum_n r_{a(n), n}(t). Let Mn(t)=max⁡krk,n(t)M_n(t) = \max_k r_{k,n}(t) and Bn(t)={k:rk,n(t)=Mn(t)}B_n(t) = \{k : r_{k,n}(t) = M_n(t)\}, the set of best users of resource nn.

Part 1: optimality

Lemma 1 (the optimal assignments). An assignment aa of slot tt maximizes VtV_t if and only if a(n)∈Bn(t)a(n) \in B_n(t) for every nn. The largest value is ∑nMn(t)\sum_n M_n(t).

Proof. For every aa, Vt(a)=∑nMn(t)−∑n(Mn(t)−ra(n),n(t))V_t(a) = \sum_n M_n(t) - \sum_n \big(M_n(t) - r_{a(n),n}(t)\big), and each term Mn(t)−ra(n),n(t)M_n(t) - r_{a(n),n}(t) is ≥0\ge 0, with equality exactly when a(n)∈Bn(t)a(n) \in B_n(t). So Vt(a)≤∑nMn(t)V_t(a) \le \sum_n M_n(t), and equality holds exactly when every term is 00. Assignments with a(n)∈Bn(t)a(n) \in B_n(t) for all nn exist, since each Bn(t)B_n(t) is a nonempty subset of a finite set. □\square

Theorem 1 (one slot). Lines L2 to L4 return the assignment a∗a^* with a∗(n)=min⁡Bn(t)a^*(n) = \min B_n(t). It maximizes VtV_t, and among all maximizers it is the first in the lexicographic order of (a(1),…,a(N))(a(1), \ldots, a(N)).

Proof. Line L3 scans k=1,…,Kk = 1, \ldots, K and keeps the current best index, replacing it only when a later rate is strictly larger. After the scan the kept index has rate Mn(t)M_n(t), and no smaller index has rate Mn(t)M_n(t), since the first index that reaches Mn(t)M_n(t) is never replaced. So a∗(n)=min⁡Bn(t)a^*(n) = \min B_n(t), and by Lemma 1, a∗a^* is a maximizer. Let a≠a∗a \ne a^* be another maximizer and n0n_0 the first place where they differ. By Lemma 1, a(n0)∈Bn0(t)a(n_0) \in B_{n_0}(t), so a(n0)>min⁡Bn0(t)=a∗(n0)a(n_0) > \min B_{n_0}(t) = a^*(n_0), and a∗a^* comes first in lexicographic order. □\square

Theorem 2 (the horizon). Let the rates of every slot be fixed in advance or revealed at the start of the slot, and let them not depend on the earlier choices. Then the schedule of the algorithm has the largest total ∑kSk=∑tVt(at)\sum_k S_k = \sum_t V_t(a_t) of all schedules, and the largest value is ∑t∑nMn(t)\sum_t \sum_n M_n(t).

Proof. Every served bit of user kk is counted in exactly one slot and one resource, so ∑kSk=∑tVt(at)\sum_k S_k = \sum_t V_t(a_t), where line L5 adds rat(n),n(t)r_{a_t(n), n}(t) to Sat(n)S_{a_t(n)} once for each (t,n)(t, n). For any schedule, by Lemma 1, ∑tVt(at)≤∑t∑nMn(t)\sum_t V_t(a_t) \le \sum_t \sum_n M_n(t). The algorithm reaches Vt(at∗)=∑nMn(t)V_t(a^*_t) = \sum_n M_n(t) in every slot by Theorem 1, so it reaches the bound. Since the bound does not depend on the choices, no schedule, including one that knows the future rates, does better. □\square

Part 2: the formulas of the example

Lemma 3 (share of slots). Let X1,…,XKX_1, \ldots, X_K be independent, with XkX_k exponential of rate λk>0\lambda_k > 0 (mean 1/λk1/\lambda_k). Then

Pr⁡[Xi>Xj for all j≠i]=∑S⊆{j≠i}(−1)∣S∣λiλi+∑j∈Sλj.\Pr[X_i > X_j \text{ for all } j \ne i] = \sum_{S \subseteq \{j \ne i\}} (-1)^{|S|} \frac{\lambda_i}{\lambda_i + \sum_{j \in S} \lambda_j}.

Proof. Condition on Xi=xX_i = x. By independence, the probability that all others are below xx is ∏j≠i(1−e−λjx)\prod_{j \ne i} (1 - e^{-\lambda_j x}), so the probability is ∫0∞λie−λix∏j≠i(1−e−λjx) dx\int_0^\infty \lambda_i e^{-\lambda_i x} \prod_{j \ne i} (1 - e^{-\lambda_j x})\, dx. Expanding the product gives ∑S(−1)∣S∣e−x∑j∈Sλj\sum_S (-1)^{|S|} e^{-x \sum_{j \in S} \lambda_j}, a finite sum, so the integral can be taken term by term: ∫0∞λie−(λi+ΛS)x dx=λi/(λi+ΛS)\int_0^\infty \lambda_i e^{-(\lambda_i + \Lambda_S) x}\, dx = \lambda_i / (\lambda_i + \Lambda_S) with ΛS=∑j∈Sλj\Lambda_S = \sum_{j \in S} \lambda_j. Ties have probability 00, since the laws are continuous, so the tie rule does not change the share. □\square

With equal rates, the KK events "user ii wins" have the same probability by symmetry, and they partition the sample space up to ties of probability 00, so each has probability 1/K1/K. For two users, the formula gives 1−λ0/(λ0+λ1)=λ1/(λ0+λ1)=m0/(m0+m1)1 - \lambda_0 / (\lambda_0 + \lambda_1) = \lambda_1 / (\lambda_0 + \lambda_1) = m_0 / (m_0 + m_1).

Lemma 4 (expectations of the largest gain). Let X=max⁡kXkX = \max_k X_k for KK independent unit exponentials, and let hh be continuously differentiable on [0,∞)[0, \infty) with h′(x)≥0h'(x) \ge 0 and h′(x)≤c(1+x)mh'(x) \le c(1 + x)^m for some c,mc, m. Then

E[h(X)]=h(0)+∫0∞h′(x)(1−(1−e−x)K) dx.\mathbb E[h(X)] = h(0) + \int_0^\infty h'(x) \big(1 - (1 - e^{-x})^K\big)\, dx.

Proof. Pr⁡[X≤x]=∏kPr⁡[Xk≤x]=(1−e−x)K\Pr[X \le x] = \prod_k \Pr[X_k \le x] = (1 - e^{-x})^K, so Pr⁡[X>x]=1−(1−e−x)K≤Ke−x\Pr[X > x] = 1 - (1 - e^{-x})^K \le K e^{-x} by the union bound. Write h(X)−h(0)=∫0∞h′(x)1[X>x] dxh(X) - h(0) = \int_0^\infty h'(x) \mathbf 1[X > x]\, dx. The integrand is nonnegative, so by Tonelli's theorem the expectation and the integral can be swapped, which gives the formula. It is finite because h′(x)Ke−xh'(x) K e^{-x} is integrable. □\square

Corollary 5 (E[X]=HK\mathbb E[X] = H_K). With h(x)=xh(x) = x, E[X]=∫0∞(1−(1−e−x)K) dx\mathbb E[X] = \int_0^\infty (1 - (1 - e^{-x})^K)\, dx. Put u=1−e−xu = 1 - e^{-x}, so dx=du/(1−u)dx = du / (1 - u), and the integral is ∫01(1−uK)/(1−u) du=∫01∑j=0K−1uj du=∑j=1K1/j=HK\int_0^1 (1 - u^K)/(1 - u)\, du = \int_0^1 \sum_{j=0}^{K-1} u^j\, du = \sum_{j=1}^{K} 1/j = H_K. □\square

Corollary 6 (mean rate). With h(x)=log⁡2(1+γx)h(x) = \log_2(1 + \gamma x) and γ>0\gamma > 0, h′(x)=γ/((1+γx)ln⁡2)h'(x) = \gamma / ((1 + \gamma x) \ln 2), which is bounded, so Lemma 4 applies. The substitution y=ln⁡(1+γx)y = \ln(1 + \gamma x), dy=γ dx/(1+γx)dy = \gamma\, dx / (1 + \gamma x), gives

E[log⁡2(1+γX)]=1ln⁡2∫0∞Pr⁡[X>ey−1γ] dy.\mathbb E[\log_2(1 + \gamma X)] = \frac{1}{\ln 2} \int_0^\infty \Pr\Big[X > \frac{e^y - 1}{\gamma}\Big]\, dy.

The code evaluates this integral by Simpson's rule on [0,ln⁡(1+γ(45+ln⁡K))][0, \ln(1 + \gamma (45 + \ln K))]. Past the upper end, Pr⁡[X>x]≤Ke−x≤e−45\Pr[X > x] \le K e^{-x} \le e^{-45}, and the integrand decays like Kexp⁡(−(ey−1)/γ)K \exp(-(e^y - 1)/\gamma), so the cut-off error is far below the test tolerance. Expanding 1−(1−e−x)K=∑m=1K(−1)m+1(Km)e−mx1 - (1 - e^{-x})^K = \sum_{m=1}^{K} (-1)^{m+1} \binom{K}{m} e^{-m x} and using ∫0∞e−mxγ/(1+γx) dx=em/γE1(m/γ)\int_0^\infty e^{-m x} \gamma / (1 + \gamma x)\, dx = e^{m/\gamma} E_1(m/\gamma) gives the closed form

E[log⁡2(1+γX)]=1ln⁡2∑m=1K(−1)m+1(Km)em/γE1(m/γ),\mathbb E[\log_2(1 + \gamma X)] = \frac{1}{\ln 2} \sum_{m=1}^{K} (-1)^{m+1} \binom{K}{m} e^{m/\gamma} E_1(m/\gamma),

which the tests use for small KK. For K=1K = 1 and γ=1\gamma = 1 it is e E1(1)/ln⁡2=0.596347…/ln⁡2e\, E_1(1) / \ln 2 = 0.596347\ldots / \ln 2. □\square

Complexity

In the real RAM, line L3 costs O(K)O(K) comparisons, so one slot costs O(KN)O(K N) and TT slots cost O(TKN)O(T K N). The extra space is the KK totals SkS_k. The real cost is the feedback: each user must report a rate for each resource in each slot, KNK N numbers per slot, which systems cut by reporting only the best few resources or a coarse summary.

Properties

  • Throughput optimal. It has the largest total rate in every slot, for any rates, among schedules that give each resource to one user.
  • Not fair. A user whose rates are always below another user's is never served. Shares depend on the mean channel as well as on its changes.
  • Memoryless. The choice uses only the current rates, not what users got before.
  • Greedy and exact. The greedy choice is exact here because the total is separable over resources and the rates are fixed. When rates depend on power shared across resources, or on interference between cells, the problem is no longer separable.
  • Gain from many users. With i.i.d. fading, the mean rate grows like log⁡2log⁡K\log_2 \log K with the number of users.

Variants and improvements

  • Proportional fair. Serve the user with the largest rk,n(t)/Rˉk(t)r_{k,n}(t) / \bar R_k(t), where Rˉk\bar R_k is the user's average served rate; this maximizes ∑klog⁡Rˉk\sum_k \log \bar R_k in the long run.
  • Weighted max-rate. Serve the user with the largest wkrk,n(t)w_k r_{k,n}(t). With wkw_k equal to queue lengths, this is the max-weight rule of wireless link scheduling, which keeps all queues stable whenever any rule can.
  • Max-min. Serve the user with the smallest served total; this is max-min fairness and gives up most of the gain.
  • Across frequency. In OFDMA, give each subcarrier to its best user, then spread the power over the subcarriers by water-filling; for the sum rate under a total power limit this is optimal.
  • With queues. Serving a user with an empty buffer wastes the slot; practical forms use min⁡(rk,n(t),qk)\min(r_{k,n}(t), q_k) in place of the rate.

When to use it

Use it when the total throughput is all that matters and the users have similar mean channels, for example in a benchmark for other schedulers or for best-effort traffic among users at similar distances. Its throughput is the upper bound that fair schedulers are compared with. Do not use it alone when users have different mean channels or delay needs.

Pitfalls

  • Starvation. A far user can wait forever, as user 3 in the example; this is starvation, and it also hurts protocols such as TCP that time out.
  • Stale reports. If the channel changes between the report and the slot, the "best" user may be in a fade. The gain falls when the delay approaches the coherence time.
  • Bad reports. A user who reports a higher rate than it can receive wins slots and then fails to decode; schedulers depend on honest and calibrated reports.
  • Comparing rates, not SNRs. With different modulation tables or code limits, the user with the best SNR is not always the user with the best rate. Compare the rates that each user can actually decode.

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.

cbb.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Complex baseband tools for the communications pages.

Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.

Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
  with variance var / 2 each, so E|w|^2 = var.
"""

import cmath
import math
import random


# ---------------------------------------------------------------- vectors and matrices


def zeros(rows: int, cols: int | None = None) -> list:
    """A zero vector of length rows, or a rows by cols zero matrix."""
    if cols is None:
        return [0j] * rows
    return [[0j] * cols for _ in range(rows)]


def eye(n: int) -> list[list[complex]]:
    """The n by n identity matrix."""
    return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]


def add(a: list, b: list) -> list:
    """Elementwise a + b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [add(r, s) for r, s in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a: list, b: list) -> list:
    """Elementwise a - b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [sub(r, s) for r, s in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c: complex, a: list) -> list:
    """The scalar c times a vector or a matrix."""
    if a and isinstance(a[0], list):
        return [scale(c, r) for r in a]
    return [c * x for x in a]


def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
    """The matrix product a b."""
    if not a or not b or len(a[0]) != len(b):
        raise ValueError("inner dimensions differ")
    cols = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]


def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
    """The matrix times vector product a x."""
    if a and len(a[0]) != len(x):
        raise ValueError("inner dimensions differ")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def herm(a: list) -> list:
    """The conjugate transpose of a matrix. A vector gives its conjugate."""
    if a and isinstance(a[0], list):
        return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
    return [complex(x).conjugate() for x in a]


def dot(x: list[complex], y: list[complex]) -> complex:
    """The inner product x^H y = sum of conj(x_i) y_i."""
    if len(x) != len(y):
        raise ValueError("lengths differ")
    return sum(complex(p).conjugate() * q for p, q in zip(x, y))


def norm2(x: list) -> float:
    """The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
    if x and isinstance(x[0], list):
        return sum(norm2(r) for r in x)
    return sum(abs(v) ** 2 for v in x)


# ---------------------------------------------------------------- linear systems


def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
    """LU factorization with partial pivoting. Returns (lu, perm, sign)."""
    n = len(a)
    if any(len(r) != n for r in a):
        raise ValueError("matrix is not square")
    m = [[complex(v) for v in r] for r in a]
    perm = list(range(n))
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if abs(m[p][k]) == 0.0:
            raise ValueError("matrix is singular")
        if p != k:
            m[k], m[p] = m[p], m[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        for i in range(k + 1, n):
            f = m[i][k] / m[k][k]
            m[i][k] = f
            if f != 0:
                rk, ri = m[k], m[i]
                for c in range(k + 1, n):
                    ri[c] -= f * rk[c]
    return m, perm, sign


def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
    n = len(lu)
    y = [complex(b[perm[i]]) for i in range(n)]
    for i in range(n):
        for c in range(i):
            y[i] -= lu[i][c] * y[c]
    for i in range(n - 1, -1, -1):
        for c in range(i + 1, n):
            y[i] -= lu[i][c] * y[c]
        y[i] /= lu[i][i]
    return y


def solve(a: list[list[complex]], b: list) -> list:
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector, or a matrix whose columns are right-hand sides.
    Raises ValueError if a is singular.
    """
    lu, perm, _ = _lu(a)
    if b and isinstance(b[0], list):
        cols = [list(c) for c in zip(*b)]
        xs = [_lu_solve(lu, perm, c) for c in cols]
        return [list(r) for r in zip(*xs)]
    if len(b) != len(a):
        raise ValueError("lengths differ")
    return _lu_solve(lu, perm, b)


def inv(a: list[list[complex]]) -> list[list[complex]]:
    """The inverse of a square matrix."""
    return solve(a, eye(len(a)))


def det(a: list[list[complex]]) -> complex:
    """The determinant of a square matrix (0 for a singular matrix)."""
    try:
        lu, _, sign = _lu(a)
    except ValueError as e:
        if "singular" in str(e):
            return 0j
        raise
    d = complex(sign)
    for i in range(len(lu)):
        d *= lu[i][i]
    return d


def cholesky(a: list[list[complex]]) -> list[list[complex]]:
    """The lower triangular L with a = L L^H, for a Hermitian positive definite a.

    Raises ValueError if a is not positive definite (to rounding).
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for k in range(i + 1):
            s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
            if i == k:
                if s.real <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = complex(math.sqrt(s.real))
            else:
                low[i][k] = s / low[k][k].real
    return low


# ---------------------------------------------------------------- convolution and the DFT


def conv(a: list[complex], b: list[complex]) -> list[complex]:
    """Linear convolution, of length len(a) + len(b) - 1."""
    if not a or not b:
        return []
    out = [0j] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[i + k] += x * y
    return out


def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
    """Circular convolution of length n (default: the longer length).

    Both inputs are padded with zeros to length n, or must not be longer than n.
    """
    if n is None:
        n = max(len(a), len(b))
    if len(a) > n or len(b) > n:
        raise ValueError("input longer than n")
    out = [0j] * n
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[(i + k) % n] += x * y
    return out


def _twiddles(n: int, sign: int) -> list[complex]:
    return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]


def dft(x: list[complex]) -> list[complex]:
    """X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
    n = len(x)
    w = _twiddles(n, -1)
    return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]


def idft(xf: list[complex]) -> list[complex]:
    """x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
    n = len(xf)
    w = _twiddles(n, 1)
    return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]


def udft(x: list[complex]) -> list[complex]:
    """The unitary DFT: dft(x) / sqrt(N)."""
    s = 1.0 / math.sqrt(len(x)) if x else 1.0
    return [v * s for v in dft(x)]


def uidft(xf: list[complex]) -> list[complex]:
    """The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
    s = math.sqrt(len(xf)) if xf else 1.0
    return [v * s for v in idft(xf)]


# ---------------------------------------------------------------- Q function and dB


def qfunc(x: float) -> float:
    """Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def qinv(p: float) -> float:
    """The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    lo, hi = -40.0, 40.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if qfunc(mid) > p:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-15 * max(1.0, abs(mid)):
            break
    return 0.5 * (lo + hi)


def db(x: float) -> float:
    """10 log10(x), for a ratio of powers or energies."""
    return 10.0 * math.log10(x)


def undb(d: float) -> float:
    """10^(d / 10), the inverse of db."""
    return 10.0 ** (d / 10.0)


# ---------------------------------------------------------------- noise and statistics


def cn(rng: random.Random, var: float) -> complex:
    """One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
    s = math.sqrt(var / 2.0)
    return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))


def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
    """x plus independent CN(0, n0) noise on each sample."""
    return [v + cn(rng, n0) for v in x]


def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
    """The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
    if n <= 0 or not 0 <= k <= n:
        raise ValueError("need 0 <= k <= n and n > 0")
    p = k / n
    z2 = z * z
    den = 1.0 + z2 / n
    mid = (p + z2 / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
    return max(0.0, mid - half), min(1.0, mid + half)
max_rate_scheduling.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/max-rate-scheduling/. The authors are listed in prov/ZZJV41.jsonl.

"""Max-rate (max C/I) scheduling.

In each time slot t the scheduler knows the rate r[t][k][n] >= 0 that user k
would get on resource n (a slot, a subcarrier or a resource block). It gives
each resource to a user with the largest rate, breaking ties toward the
smallest user index, and adds that rate to the user's served total. This
maximizes the total served rate in every slot, and so over any horizon,
among all schedulers that give each resource to one user.

The module also has the analysis tools of the page: the probability that
user i has the strongest of K independent Rayleigh-faded channels, and the
mean rate E[log2(1 + snr X)] of the best of K users, X the largest of K
independent Exp(1) gains.
"""

import itertools
import math


def max_rate_slot(rates: list[list[float]]) -> list[int]:
    """Assign each resource of one slot. rates[k][n] is the rate of user k on resource n.

    Returns a list with the chosen user of each resource (the smallest index on ties).
    """
    if not rates or not rates[0]:
        raise ValueError("need at least one user and one resource")
    k_users, n_res = len(rates), len(rates[0])
    if any(len(r) != n_res for r in rates):
        raise ValueError("every user needs a rate on every resource")
    choice = []
    for n in range(n_res):  # @line L2
        best = 0
        for k in range(1, k_users):  # @line L3
            if rates[k][n] > rates[best][n]:
                best = k
        choice.append(best)  # @line L4
    return choice


def max_rate_schedule(slots: list[list[list[float]]]) -> tuple[list[list[int]], list[float]]:
    """Run the scheduler over slots[t][k][n]. Return the choices per slot and the total served per user."""
    if not slots:
        return [], []
    served = [0.0] * len(slots[0])
    choices = []
    for rates in slots:  # @line L1
        choice = max_rate_slot(rates)
        for n, k in enumerate(choice):
            served[k] += rates[k][n]  # @line L5
        choices.append(choice)
    return choices, served  # @line L6


def slot_total(rates: list[list[float]], choice: list[int]) -> float:
    """The total rate of one slot under an assignment choice[n] of users to resources."""
    return sum(rates[k][n] for n, k in enumerate(choice))


def brute_force_slot(rates: list[list[float]]) -> tuple[float, list[int]]:
    """The best total over all K^N assignments of one slot, and the first assignment that reaches it."""
    k_users, n_res = len(rates), len(rates[0])
    best_total, best_choice = -math.inf, []
    for choice in itertools.product(range(k_users), repeat=n_res):
        total = slot_total(rates, list(choice))
        if total > best_total:
            best_total, best_choice = total, list(choice)
    return best_total, best_choice


def win_probability(means: list[float], i: int) -> float:
    """P(user i has the largest gain) for independent exponential gains with the given means.

    With rates lam_j = 1 / means[j], P = integral of lam_i e^(-lam_i x) prod_{j != i} (1 - e^(-lam_j x)) dx,
    and expanding the product gives the sum over subsets S of the other users of
    (-1)^|S| lam_i / (lam_i + sum_{j in S} lam_j).
    """
    if any(m <= 0 for m in means):
        raise ValueError("means must be positive")
    lam = [1.0 / m for m in means]
    others = [lam[j] for j in range(len(lam)) if j != i]
    total = 0.0
    for size in range(len(others) + 1):
        for subset in itertools.combinations(others, size):
            total += (-1) ** size * lam[i] / (lam[i] + sum(subset))
    return total


def max_tail(k: int, x: float) -> float:
    """P(X > x) = 1 - (1 - e^(-x))^k for X the largest of k independent Exp(1) gains."""
    if x <= 0.0:
        return 1.0
    return -math.expm1(k * math.log1p(-math.exp(-x)))


def _simpson(f, a: float, b: float, steps: int) -> float:
    if steps % 2:
        steps += 1
    h = (b - a) / steps
    total = f(a) + f(b)
    for s in range(1, steps):
        total += (4.0 if s % 2 else 2.0) * f(a + s * h)
    return total * h / 3.0


def expected_of_max(k: int, dh, steps: int = 20000) -> float:
    """E[h(X)] - h(0) for X the largest of k independent Exp(1) gains, given the derivative dh of h.

    Uses E[h(X)] = h(0) + integral over x >= 0 of h'(x) P(X > x) dx, by Simpson's
    rule on [0, 45 + ln k]; past that point P(X > x) is below k e^(-45 - ln k) = e^(-45).
    dh must be smooth on the scale of the step.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    return _simpson(lambda x: dh(x) * max_tail(k, x), 0.0, 45.0 + math.log(k), steps)


def expected_max_rate(k: int, snr: float, steps: int = 4000) -> float:
    """E[log2(1 + snr X)] in bit/s/Hz for X the largest of k independent Exp(1) gains (Rayleigh fading).

    With y = ln(1 + snr x), E = (1 / ln 2) integral over y >= 0 of P(X > (e^y - 1) / snr) dy,
    a smooth integrand for every snr.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    if snr <= 0:
        raise ValueError("snr must be positive")
    top = math.log1p(snr * (45.0 + math.log(k)))
    return _simpson(lambda y: max_tail(k, math.expm1(y) / snr), 0.0, top, steps) / math.log(2.0)


def harmonic(k: int) -> float:
    """H_k = 1 + 1/2 + ... + 1/k, the mean of the largest of k independent Exp(1) gains."""
    return sum(1.0 / j for j in range(1, k + 1))
test_max_rate_scheduling.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/max-rate-scheduling/. The authors are listed in prov/ZZJV41.jsonl.

import math
import random

import pytest

from cbb import undb, wilson
from max_rate_scheduling import (
    brute_force_slot,
    expected_max_rate,
    expected_of_max,
    harmonic,
    max_rate_schedule,
    max_rate_slot,
    slot_total,
    win_probability,
)

# The page example: 3 users, 6 slots, one resource per slot. PAGE[t][k][0] is the rate of user k in slot t.
TABLE = [
    [2.1, 3.4, 1.2, 4.0, 2.5, 0.8],
    [3.0, 1.1, 2.6, 2.2, 3.3, 2.9],
    [0.9, 1.0, 1.9, 0.7, 1.2, 1.5],
]
PAGE = [[[TABLE[k][t]] for k in range(3)] for t in range(6)]


def e1(z: float) -> float:
    """The exponential integral E1(z) = integral from z to infinity of e^(-u) / u du, by its power series."""
    s, term = 0.0, 1.0
    for n in range(1, 200):
        term *= -z / n
        s += term / n
        if abs(term) < 1e-18:
            break
    return -0.5772156649015329 - math.log(z) - s


def closed_form_rate(k: int, snr: float) -> float:
    """E[log2(1 + snr X)] = (1 / ln 2) sum_m (-1)^(m+1) C(k, m) e^(m / snr) E1(m / snr), fine for small k."""
    return sum((-1) ** (m + 1) * math.comb(k, m) * math.exp(m / snr) * e1(m / snr) for m in range(1, k + 1)) / math.log(2.0)


def test_page_example() -> None:
    choices, served = max_rate_schedule(PAGE)
    assert [c[0] for c in choices] == [1, 0, 1, 0, 1, 1]
    assert served == pytest.approx([7.4, 11.8, 0.0], abs=1e-12)
    assert sum(served) == pytest.approx(19.2, abs=1e-12)
    round_robin = sum(TABLE[t % 3][t] for t in range(6))
    assert round_robin == pytest.approx(13.9, abs=1e-12)


def test_ties_go_to_the_smallest_index() -> None:
    assert max_rate_slot([[1.0, 2.0], [1.0, 2.0], [0.5, 2.0]]) == [0, 0]
    assert max_rate_slot([[0.0], [0.0]]) == [0]
    assert max_rate_slot([[1.0, 0.0], [3.0, 0.0], [3.0, 5.0]]) == [1, 2]


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        max_rate_slot([])
    with pytest.raises(ValueError):
        max_rate_slot([[1.0, 2.0], [1.0]])


def test_equals_brute_force() -> None:
    rng = random.Random(41)
    for _ in range(300):
        k, n = rng.randint(1, 4), rng.randint(1, 4)
        rates = [[rng.choice([0.0, 0.5, 1.0, 1.5, rng.random() * 3]) for _ in range(n)] for _ in range(k)]
        best, first = brute_force_slot(rates)
        choice = max_rate_slot(rates)
        assert slot_total(rates, choice) == pytest.approx(best, abs=1e-12)
        # itertools.product runs in lexicographic order, so the first best assignment is the smallest-index one
        assert choice == first


def test_beats_every_other_scheduler_over_time() -> None:
    rng = random.Random(7)
    slots = [[[rng.expovariate(1.0) for _ in range(3)] for _ in range(4)] for _ in range(200)]
    _, served = max_rate_schedule(slots)
    for _ in range(50):
        other = sum(slot_total(r, [rng.randrange(4) for _ in range(3)]) for r in slots)
        assert other <= sum(served) + 1e-9


def test_win_probability_closed_form() -> None:
    for k in range(1, 7):
        for i in range(k):
            assert win_probability([1.0] * k, i) == pytest.approx(1.0 / k, abs=1e-12)
    means = [1.0, 2.0, 4.0]
    p = [win_probability(means, i) for i in range(3)]
    assert sum(p) == pytest.approx(1.0, abs=1e-12)
    # two users: P(user 0 wins) = m0 / (m0 + m1)
    assert win_probability([1.0, 3.0], 0) == pytest.approx(0.25, abs=1e-12)
    assert p == pytest.approx([11 / 105, 30 / 105, 64 / 105], abs=1e-12)


def test_win_probability_by_simulation() -> None:
    rng = random.Random(2024)
    means = [1.0, 2.0, 4.0]
    trials = 20000
    wins = [0, 0, 0]
    for _ in range(trials):
        g = [[rng.expovariate(1.0 / m)] for m in means]
        wins[max_rate_slot(g)[0]] += 1
    for i in range(3):
        lo, hi = wilson(wins[i], trials)
        assert lo <= win_probability(means, i) <= hi


def test_mean_of_the_best_gain_is_harmonic() -> None:
    for k in (1, 2, 3, 8, 16, 64):
        assert expected_of_max(k, lambda x: 1.0) == pytest.approx(harmonic(k), abs=1e-9)


def test_rate_against_closed_forms() -> None:
    # e E1(1) = 0.596347362323194 nats for one user at snr = 1
    assert expected_max_rate(1, 1.0) == pytest.approx(0.596347362323194 / math.log(2.0), abs=1e-9)
    for snr in (1.0, 10.0):
        for k in (1, 2, 3, 4):
            assert expected_max_rate(k, snr) == pytest.approx(closed_form_rate(k, snr), abs=1e-8)


def test_page_rate_table() -> None:
    snr = undb(10.0)
    table = {1: 2.9065, 2: 3.6586, 4: 4.2427, 8: 4.6865, 16: 5.0340, 64: 5.5520}
    prev = 0.0
    for k, v in table.items():
        c = expected_max_rate(k, snr)
        assert c == pytest.approx(v, abs=6e-5)
        assert c > prev
        prev = c


def test_rate_by_simulation() -> None:
    rng = random.Random(99)
    snr, k, trials = 10.0, 8, 20000
    xs = [math.log2(1 + snr * max(rng.expovariate(1.0) for _ in range(k))) for _ in range(trials)]
    mean = sum(xs) / trials
    var = sum((x - mean) ** 2 for x in xs) / (trials - 1)
    assert abs(mean - expected_max_rate(k, snr)) <= 4.5 * math.sqrt(var / trials)

History

Knopp and Humblet (1995) showed that the sum capacity of the fading uplink, with power control, is reached when at each time only the user with the strongest channel sends. The name "max C/I", for carrier to interference ratio, comes from the studies of the high data rate cellular systems of the late 1990s and 2000s, such as CDMA2000 EV-DO and HSDPA, where it was the throughput benchmark. Deployed systems mostly used proportional fair scheduling, because max C/I left users at the cell edge without service; Viswanath, Tse and Laroia (2002) analyzed proportional fair scheduling and showed how to keep the gain when the channel changes slowly.

References

  1. Raymond Knopp and Pierre A. Humblet, Information capacity and power control in single-cell multiuser communications, Proceedings of the IEEE International Conference on Communications (ICC), 1995, pages 331 to 335, the result that, for the fading uplink with power control, the sum capacity is reached by letting only the user with the best channel send at each time
  2. Pramod Viswanath, David N. C. Tse and Rajiv Laroia, Opportunistic beamforming using dumb antennas, IEEE Transactions on Information Theory 48(6), 2002, pages 1277 to 1294, the comparison of serving the best user with the proportional fair scheduler when the users have unequal mean channels
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Chapter 6, the sections on multiuser diversity and its system aspects (fairness and delay, channel prediction and feedback)

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