Algorithm Search⌘K

Algorithmcore

Rake receiver

Also called RAKE combiner.

Despreads each resolvable path of a spread-spectrum signal at its own delay, weights each finger output by the conjugate path gain and adds. It is the matched filter to the multipath pulse.

Time
Θ(L N) worst
Space
Θ(1) extra
Where
L = the number of fingers; N = the number of chips per symbol
Properties
deterministicexact ml with cyclic prefixmaximal ratio weightsneeds channel estimate
Origin
Robert Price, Paul E. Green Jr., 1958

A rake receiver demodulates a direct-sequence spread-spectrum signal that arrives over several paths with different delays. Each path that is more than about one chip away from the others can be separated by despreading at its own delay. The receiver has one finger for each such path: the finger correlates the received chips with the code shifted by the path delay. A combiner then multiplies each finger output by the conjugate of the path gain and adds them. The result is the matched filter to the whole received pulse, so the receiver collects the energy of all paths instead of treating the late paths as interference. This is the multipath counterpart of maximal ratio combining: MRC combines antennas, and the rake combines delays. Price and Green described it in 1958.

In plain words

A radio signal bounces off buildings and hills, so the receiver hears several copies of it, each a little late and each with its own strength.

A spread-spectrum signal is a long pattern of fast pulses. If the receiver lines up its copy of the pattern with one echo, it hears that echo clearly and the other echoes mostly cancel out, because the pattern does not match itself at other timings.

So the receiver uses several "fingers", one for each strong echo, each lined up with its own echo. Each finger gives a value. The receiver turns each value so that all of them point the same way, gives more weight to the strong echoes and less to the weak ones, and adds them up. The echoes, which would otherwise be a nuisance, now all help.

The problem

One symbol bb is sent with a code c∈CNc \in \mathbb{C}^N of NN chips and unit energy, ∑n∣c[n]∣2=1\sum_n |c[n]|^2 = 1. The channel has LL resolvable paths with known integer delays d1,…,dLd_1, \ldots, d_L (in chips) and known complex gains h1,…,hLh_1, \ldots, h_L. With a cyclic prefix, so that there is no interference from the previous symbol, the received block is

r[n]=Es b∑l=1Lhl c[(n−dl) mod N]+w[n],n=0,…,N−1,r[n] = \sqrt{E_s}\, b \sum_{l=1}^{L} h_l\, c[(n - d_l) \bmod N] + w[n], \qquad n = 0, \ldots, N - 1,

with independent noise w[n]∼CN(0,N0)w[n] \sim \mathcal{CN}(0, N_0). The task is to form the statistic for detecting bb that keeps all the information in rr about bb, and to decide bb. On a real link the delays and gains come from a channel estimate, for example from a pilot channel, and a searcher picks the delays with the most energy.

The algorithm

  1. RAKE(r, c, (d_1, h_1), …, (d_L, h_L))
  2. 1y ← 0
  3. 2for l ← 1 to L do
  4. 3z_l ← Σ_{n=0}^{N-1} conj(c[(n - d_l) mod N]) · r[n] ▷ finger l: despread at delay d_l
  5. 4y ← y + conj(h_l) · z_l ▷ maximal ratio weight
  6. 5return y ▷ for BPSK, decide b̂ = sign(Re y)

Write TdcT^d c for the code delayed by dd chips. Each finger output is zl=Es b∑mRlmhm+ulz_l = \sqrt{E_s}\, b \sum_m R_{lm} h_m + u_l, where Rlm=⟨Tdlc,Tdmc⟩R_{lm} = \langle T^{d_l} c, T^{d_m} c\rangle is the periodic autocorrelation of the code at the shift dm−dld_m - d_l. A good spreading code has Rll=1R_{ll} = 1 and ∣Rlm∣|R_{lm}| small for l≠ml \ne m, so each finger sees mainly its own path. The output is

y=⟨g,r⟩,g=∑lhl Tdlc,y = \langle g, r\rangle, \qquad g = \sum_l h_l\, T^{d_l} c,

the correlation of rr with the received pulse gg. Its signal part is Es b ∥g∥2\sqrt{E_s}\, b\, \|g\|^2 with ∥g∥2=hHRh\|g\|^2 = h^H R h, and for BPSK the error probability is Q(2Es hHRh/N0)Q(\sqrt{2 E_s\, h^H R h / N_0}).

Example

Take the m-sequence code 10010111001011 of length N=7N = 7, as chips (−1,1,1,−1,1,−1,−1)/7(-1, 1, 1, -1, 1, -1, -1)/\sqrt 7. Its periodic autocorrelation is 11 at shift 00 and −1/7-1/7 elsewhere. The channel has two paths at delays 00 and 22 with gains h=(0.8,0.6)h = (0.8, 0.6), and b=+1b = +1, Es=1E_s = 1, no noise.

  • The received chips, times 7\sqrt 7, are (−1.4,0.2,0.2,−0.2,1.4,−1.4,−0.2)(-1.4, 0.2, 0.2, -0.2, 1.4, -1.4, -0.2).
  • Finger 1 (delay 0) gives z1=0.8+0.6⋅(−1/7)=0.7143z_1 = 0.8 + 0.6 \cdot (-1/7) = 0.7143.
  • Finger 2 (delay 2) gives z2=0.6+0.8⋅(−1/7)=0.4857z_2 = 0.6 + 0.8 \cdot (-1/7) = 0.4857.
  • The combiner gives y=0.8⋅0.7143+0.6⋅0.4857=0.8629y = 0.8 \cdot 0.7143 + 0.6 \cdot 0.4857 = 0.8629, which is hHRh=1−0.96/7h^H R h = 1 - 0.96/7.

With noise at Es/N0=6E_s/N_0 = 6 dB, the rake gives Pb=0.0044P_b = 0.0044. A single finger on the strong path has output SNR (0.8−0.6/7)2=0.5102(0.8 - 0.6/7)^2 = 0.5102 times Es/N0E_s/N_0 and Pb=0.0219P_b = 0.0219, five times worse.

If the second path has the gain 0.6j0.6j instead, the cross terms are imaginary and drop out of hHRhh^H R h, which becomes ∣0.8∣2+∣0.6∣2=1|0.8|^2 + |0.6|^2 = 1. The rake then gives Pb=0.0024P_b = 0.0024, the same as a single path of unit energy, and the single finger gives 0.01160.0116.

Correctness

The loop computes y=∑lhl‾ zly = \sum_l \overline{h_l}\, z_l, and since the inner product is conjugate-linear in its first argument this equals ⟨g,r⟩\langle g, r\rangle. Expanding ∥r−Esbg∥2\|r - \sqrt{E_s} b g\|^2 shows that the Gaussian likelihood depends on rr only through ⟨g,r⟩\langle g, r\rangle, so yy is a sufficient statistic, and for BPSK the sign of Re⁡y\operatorname{Re} y is the maximum likelihood decision. The noise in yy is CN(0,N0∥g∥2)\mathcal{CN}(0, N_0 \|g\|^2), which gives Pb=Q(2Es∥g∥2/N0)P_b = Q(\sqrt{2 E_s \|g\|^2/N_0}). For any other weights aa, the output SNR is Es∣aHRh∣2/(N0 aHRa)E_s |a^H R h|^2 / (N_0\, a^H R a), and the Cauchy-Schwarz inequality in the inner product defined by RR shows that a=ha = h is best. The full proof is in the proofs folder.

Proof: The rake output is the matched filter to the received pulse, and its weights maximize the output SNRfull

The model is one symbol bb of a direct-sequence signal with a cyclic prefix. The code is c∈CNc \in \mathbb{C}^N with ∥c∥2=1\|c\|^2 = 1. Write TdcT^d c for the code delayed by dd chips cyclically, (Tdc)[n]=c[(n−d) mod N](T^d c)[n] = c[(n - d) \bmod N]. The channel has LL paths with distinct delays d1,…,dLd_1, \ldots, d_L and known gains h1,…,hLh_1, \ldots, h_L. The received block is

r=Es b g+w,g=∑l=1Lhl Tdlc,w∼CN(0,N0IN).r = \sqrt{E_s}\, b\, g + w, \qquad g = \sum_{l=1}^{L} h_l\, T^{d_l} c, \qquad w \sim \mathcal{CN}(0, N_0 I_N).

The finger outputs are zl=⟨Tdlc,r⟩=∑nc[(n−dl) mod N]‾ r[n]z_l = \langle T^{d_l} c, r \rangle = \sum_n \overline{c[(n - d_l) \bmod N]}\, r[n], and the rake returns y=∑lhl‾ zly = \sum_l \overline{h_l}\, z_l (lines L1 to L5). Let RR be the L×LL \times L matrix with Rlm=⟨Tdlc,Tdmc⟩R_{lm} = \langle T^{d_l} c, T^{d_m} c \rangle, the periodic autocorrelation of the code at the shift dm−dld_m - d_l. It is Hermitian and positive semidefinite, with Rll=1R_{ll} = 1. We assume that it is positive definite, which holds when the shifted codes are linearly independent; for an m-sequence, R=(1+1/N)I−(1/N)11TR = (1 + 1/N) I - (1/N) \mathbf{1}\mathbf{1}^T, whose eigenvalues are 1+1/N1 + 1/N and (1+1/N)−L/N>0(1 + 1/N) - L/N > 0 for L≤NL \le N.

Lemma 1 (the loop computes the defined sum). After the loop, y=∑lhl‾zly = \sum_l \overline{h_l} z_l.

Proof. L1 sets y=0y = 0. The loop visits each finger once (L2). At finger ll, L3 computes zlz_l by its definition and L4 adds hl‾zl\overline{h_l} z_l. By induction on the number of fingers visited, after kk fingers yy is the sum over those kk fingers. After all LL, it is the full sum, which L5 returns. □\square

Lemma 2 (matched filter). y=⟨g,r⟩y = \langle g, r \rangle.

Proof. The inner product ⟨u,v⟩=∑nu[n]‾ v[n]\langle u, v \rangle = \sum_n \overline{u[n]}\, v[n] is conjugate-linear in uu. So

⟨g,r⟩=⟨∑lhlTdlc, r⟩=∑lhl‾ ⟨Tdlc,r⟩=∑lhl‾ zl=y.□\langle g, r \rangle = \Big\langle \sum_l h_l T^{d_l} c, \ r \Big\rangle = \sum_l \overline{h_l}\, \langle T^{d_l} c, r \rangle = \sum_l \overline{h_l}\, z_l = y. \quad \square

Lemma 3 (the statistic is sufficient). Given rr, the likelihood of a symbol value bb depends on rr only through ⟨g,r⟩\langle g, r \rangle. For BPSK with b∈{+1,−1}b \in \{+1, -1\} and equal priors, the maximum likelihood decision is the sign of Re⁡y\operatorname{Re} y.

Proof. The density of rr given bb is (πN0)−Nexp⁡(−∥r−Esbg∥2/N0)(\pi N_0)^{-N} \exp(-\|r - \sqrt{E_s} b g\|^2 / N_0). Expand the norm:

∥r−Esbg∥2=∥r∥2−2Es Re⁡(b‾ ⟨g,r⟩)+Es∣b∣2∥g∥2.\|r - \sqrt{E_s} b g\|^2 = \|r\|^2 - 2\sqrt{E_s}\, \operatorname{Re}\big(\overline{b}\, \langle g, r\rangle\big) + E_s |b|^2 \|g\|^2.

The first term does not depend on bb, and the others depend on rr only through ⟨g,r⟩=y\langle g, r\rangle = y. For b=±1b = \pm 1, ∣b∣2=1|b|^2 = 1, so the likelihood is larger for b=+1b = +1 exactly when Re⁡y>0\operatorname{Re} y > 0. □\square

Lemma 4 (output statistics). ∥g∥2=hHRh\|g\|^2 = h^H R h, and y=Es b ∥g∥2+vy = \sqrt{E_s}\, b\, \|g\|^2 + v with v∼CN(0,N0∥g∥2)v \sim \mathcal{CN}(0, N_0 \|g\|^2). For BPSK, the error probability of the decision in Lemma 3 is

Pb=Q(2Es hHRh/N0).P_b = Q\Big(\sqrt{2 E_s\, h^H R h / N_0}\Big).

Proof. ∥g∥2=∑l,mhl‾hm⟨Tdlc,Tdmc⟩=hHRh\|g\|^2 = \sum_{l,m} \overline{h_l} h_m \langle T^{d_l} c, T^{d_m} c\rangle = h^H R h. By Lemma 2, y=Esb⟨g,g⟩+⟨g,w⟩y = \sqrt{E_s} b \langle g, g\rangle + \langle g, w\rangle. The term v=⟨g,w⟩v = \langle g, w \rangle is a fixed linear combination of independent CN(0,N0)\mathcal{CN}(0, N_0) samples, so it is circularly symmetric Gaussian with variance N0∥g∥2N_0 \|g\|^2; its real part has variance N0∥g∥2/2N_0 \|g\|^2 / 2. Given b=+1b = +1, an error occurs when Re⁡v<−Es∥g∥2\operatorname{Re} v < -\sqrt{E_s} \|g\|^2, with probability Q(Es∥g∥2/N0∥g∥2/2)=Q(2Es∥g∥2/N0)Q\big(\sqrt{E_s} \|g\|^2 / \sqrt{N_0 \|g\|^2/2}\big) = Q\big(\sqrt{2 E_s \|g\|^2 / N_0}\big). The case b=−1b = -1 is symmetric. □\square

Lemma 5 (maximal ratio weights are best). For any nonzero weights a∈CLa \in \mathbb{C}^L, the combiner ya=∑lal‾zly_a = \sum_l \overline{a_l} z_l has output SNR

SNR(a)=Es ∣aHRh∣2N0 aHRa  ≤  Es hHRhN0,\mathrm{SNR}(a) = \frac{E_s\, |a^H R h|^2}{N_0\, a^H R a} \;\le\; \frac{E_s\, h^H R h}{N_0},

with equality if and only if aa is a nonzero multiple of hh.

Proof. The vector of finger outputs is z=EsbRh+uz = \sqrt{E_s} b R h + u, where ul=⟨Tdlc,w⟩u_l = \langle T^{d_l} c, w\rangle has covariance E[uuH]=N0RE[u u^H] = N_0 R. So ya=aHzy_a = a^H z has signal part Esb aHRh\sqrt{E_s} b\, a^H R h and noise variance N0 aHRaN_0\, a^H R a, which gives the formula for SNR(a)\mathrm{SNR}(a). Since RR is positive definite, ⟨a,h⟩R=aHRh\langle a, h \rangle_R = a^H R h is an inner product, and the Cauchy-Schwarz inequality gives ∣aHRh∣2≤(aHRa)(hHRh)|a^H R h|^2 \le (a^H R a)(h^H R h), with equality exactly when aa and hh are parallel. Dividing by aHRa>0a^H R a > 0 gives the bound. □\square

Theorem. The rake receiver returns y=⟨g,r⟩y = \langle g, r\rangle, the output of the filter matched to the received pulse. The sign of Re⁡y\operatorname{Re} y is the maximum likelihood BPSK decision, with error probability Q(2EshHRh/N0)Q(\sqrt{2 E_s h^H R h / N_0}), and no other choice of finger weights gives a larger output SNR. When the shifted codes are orthogonal (R=IR = I), hHRh=∑l∣hl∣2h^H R h = \sum_l |h_l|^2, the SNR of maximal ratio combining over LL independent branches.

Proof. Lemmas 1 to 5. □\square

Cost. Each finger computes one correlation of NN products (L3) and one multiply-add (L4). The total is Θ(LN)\Theta(L N) operations per symbol and Θ(1)\Theta(1) space beyond the input.

Complexity

In the real RAM model, each finger does NN complex multiply-adds (L3) and one more (L4). The total is Θ(LN)\Theta(L N) per symbol, with Θ(1)\Theta(1) extra space. A matched filter to gg also costs Θ(N)\Theta(N) per symbol once gg is built, but gg costs Θ(LN)\Theta(L N) to form and changes whenever the channel changes. The fingers need only the code, the delays and the gains.

Properties

  • Matched filter to the multipath pulse. The rake output equals ⟨g,r⟩\langle g, r \rangle exactly, so it is optimal for one symbol when there is no interference between symbols.
  • Maximal ratio weights. Weighting finger ll by hl‾\overline{h_l} maximizes the output SNR over all linear combinations of the finger outputs.
  • Orthogonal codes give MRC. If the shifted codes are orthogonal (R=IR = I), the output SNR is ∑l∣hl∣2Es/N0\sum_l |h_l|^2 E_s/N_0, the same as maximal ratio combining of LL antennas. With independent Rayleigh paths this gives a diversity order of LL.
  • Cross terms. With a real code, the term 2Re⁡(hl‾hmRlm)2 \operatorname{Re}(\overline{h_l} h_m R_{lm}) can raise or lower the energy, depending on the phases of the paths. It goes to zero as NN grows for an m-sequence, since Rlm=−1/NR_{lm} = -1/N.
  • Needs the channel. The weights need the gains and the delays. Errors in them lower the SNR but do not change the structure of the receiver.

Variants and improvements

  • Selective and partial rake. Use only the L′<LL' < L strongest paths, or the first L′L' paths, to save hardware. The loss is the energy of the unused paths.
  • Equal gain combining. Co-phase the fingers but give them equal weights. It needs only the phases, not the amplitudes.
  • Generalized rake (G-RAKE). In interference-limited links, weight the fingers by Ru−1hR_u^{-1} h, where RuR_u is the covariance of interference plus noise across fingers, and place extra fingers at delays with no path. It whitens colored interference.
  • Chip-level equalization. In the WCDMA downlink, a linear equalizer before despreading restores the orthogonality of the OVSF codes that multipath destroys. The rake does not restore it.
  • Rake with soft handover. Fingers can be assigned to paths from different base stations that send the same data, so the rake also combines across cells.

When to use it

Use a rake receiver for direct-sequence signals whose delay spread is larger than a chip, so that several paths are resolvable, and whose spreading factor is large enough that the code keeps the fingers apart. This was the case for IS-95 and WCDMA. When the delay spread covers many chips and the spreading factor is small, the interference between symbols and between paths grows, and an equalizer or OFDM with a cyclic prefix is the better choice.

Pitfalls

  • Paths closer than one chip. Two paths less than about one chip apart cannot be separated by despreading. A single finger then sees their sum, which fades like one Rayleigh path; see multipath fading.
  • Ignoring the cross terms. For short codes, RlmR_{lm} is not small, and the SNR is hHRhh^H R h, not ∑l∣hl∣2\sum_l |h_l|^2. Formulas that assume orthogonal paths are then wrong by a visible amount: 0.86290.8629 against 11 in the example.
  • Intersymbol interference. Without a cyclic prefix, a path with delay dd brings dd chips of the previous symbol into the window. For long spreading codes this acts like noise; for short codes and a large delay spread it does not, and the error rate is worse than the formula.
  • Stale channel estimates. On a fast fading channel, weights from old estimates can add the paths with the wrong phases. Track the gains at least as fast as the coherence time of the channel.
  • Finger management. Paths appear and disappear. A searcher must keep looking for new delays, or the fingers end up on weak paths.

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)
rake_receiver.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rake-receiver/. The authors are listed in prov/MRC17X.jsonl.

"""A rake receiver for one direct-sequence symbol on a known multipath channel.

Model (one symbol, with a cyclic prefix so that the delays are cyclic):
    r[n] = sqrt(Es) b sum over l of h[l] c[(n - d[l]) mod N] + w[n],  n = 0, ..., N - 1,
where c is the chip code with sum |c[n]|^2 = 1, b the symbol, h[l] and d[l]
the gain and the delay (in chips) of path l, and w[n] ~ CN(0, N0).

Finger l despreads at delay d[l]:  z[l] = sum over n of conj(c[(n - d[l]) mod N]) r[n].
The combiner forms y = sum over l of conj(h[l]) z[l] (maximal ratio weights).
"""

import math
import random

from cbb import cn, qfunc


def shifted(c: list[complex], d: int) -> list[complex]:
    """The code delayed by d chips, cyclically: (c[(n - d) mod N])_n."""
    n = len(c)
    return [c[(k - d) % n] for k in range(n)]


def rake(r: list[complex], c: list[complex], delays: list[int], gains: list[complex]) -> complex:
    """The rake output y = sum over fingers of conj(h[l]) times the despread value at delay d[l]."""
    if len(delays) != len(gains):
        raise ValueError("one gain per delay")
    n = len(c)
    y = 0j  # @line L1
    for d, h in zip(delays, gains):  # @line L2
        z = sum(c[(k - d) % n].conjugate() * r[k] for k in range(n))  # @line L3
        y += h.conjugate() * z  # @line L4
    return y  # @line L5


def composite(c: list[complex], delays: list[int], gains: list[complex]) -> list[complex]:
    """The received pulse g = sum over l of h[l] times the code delayed by d[l]."""
    n = len(c)
    g = [0j] * n
    for d, h in zip(delays, gains):
        for k, v in enumerate(shifted(c, d)):
            g[k] += h * v
    return g


def code_gram(c: list[complex], delays: list[int]) -> list[list[complex]]:
    """R[l][m] = sum over n of conj(c[n - d[l]]) c[n - d[m]], the correlations of the finger codes."""
    cs = [shifted(c, d) for d in delays]
    return [[sum(x.conjugate() * y for x, y in zip(a, b)) for b in cs] for a in cs]


def energy(c: list[complex], delays: list[int], gains: list[complex]) -> float:
    """||g||^2 = h^H R h, the energy of the received pulse per unit Es."""
    rr = code_gram(c, delays)
    total = 0j
    for i, hi in enumerate(gains):
        for k, hk in enumerate(gains):
            total += hi.conjugate() * rr[i][k] * hk
    return total.real


def output_snr(c: list[complex], delays: list[int], gains: list[complex], weights: list[complex], es: float, n0: float) -> float:
    """Es |a^H R h|^2 / (N0 a^H R a): the SNR at the combiner output for weights a."""
    rr = code_gram(c, delays)
    num = sum(weights[i].conjugate() * rr[i][k] * gains[k] for i in range(len(gains)) for k in range(len(gains)))
    den = sum(weights[i].conjugate() * rr[i][k] * weights[k] for i in range(len(gains)) for k in range(len(gains)))
    return es * abs(num) ** 2 / (n0 * den.real)


def bpsk_error_probability(c: list[complex], delays: list[int], gains: list[complex], es: float, n0: float) -> float:
    """Pb = Q(sqrt(2 Es h^H R h / N0)) for BPSK with the rake receiver."""
    return qfunc(math.sqrt(2.0 * es * energy(c, delays, gains) / n0))


def receive(rng: random.Random, b: complex, c: list[complex], delays: list[int], gains: list[complex], es: float, n0: float) -> list[complex]:
    """One received block of N chips, with noise CN(0, N0) per chip (N0 = 0 for no noise)."""
    g = composite(c, delays, gains)
    a = math.sqrt(es) * b
    if n0 == 0:
        return [a * v for v in g]
    return [a * v + cn(rng, n0) for v in g]


def mseq_code(exps: list[int]) -> list[complex]:
    """One period of an m-sequence as unit-energy chips: bit 0 -> +1/sqrt(N), bit 1 -> -1/sqrt(N)."""
    n = max(exps)
    s = [1] + [0] * (n - 1)
    taps = [i for i in exps if i < n]
    while len(s) < (1 << n) - 1:
        k = len(s) - n
        bit = 0
        for i in taps:
            bit ^= s[k + i]
        s.append(bit)
    scale = 1.0 / math.sqrt(len(s))
    return [complex((1 - 2 * v) * scale) for v in s]
test_rake_receiver.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rake-receiver/. The authors are listed in prov/MRC17X.jsonl.

import math
import random

from cbb import cn, dot, wilson
from rake_receiver import bpsk_error_probability, code_gram, composite, energy, mseq_code, output_snr, rake, receive

C7 = mseq_code([3, 1, 0])
C31 = mseq_code([5, 2, 0])


def test_check_values_length_seven() -> None:
    assert abs(sum(abs(v) ** 2 for v in C7) - 1) < 1e-12
    rr = code_gram(C7, [0, 2])
    assert abs(rr[0][0] - 1) < 1e-12 and abs(rr[0][1] + 1 / 7) < 1e-12
    assert abs(energy(C7, [0, 2], [0.8, 0.6]) - (1 - 0.96 / 7)) < 1e-12
    assert abs(energy(C7, [0, 2], [0.8, 0.6j]) - 1) < 1e-12


def test_rake_is_the_matched_filter_to_the_received_pulse() -> None:
    rng = random.Random(1)
    for _ in range(50):
        n_paths = rng.randint(1, 4)
        delays = rng.sample(range(31), n_paths)
        gains = [cn(rng, 1.0) for _ in range(n_paths)]
        r = [cn(rng, 1.0) for _ in range(31)]
        g = composite(C31, delays, gains)
        assert abs(rake(r, C31, delays, gains) - dot(g, r)) < 1e-9


def test_noiseless_symbols_are_recovered() -> None:
    rng = random.Random(2)
    for _ in range(50):
        delays = rng.sample(range(31), 3)
        gains = [cn(rng, 1.0) for _ in range(3)]
        b = rng.choice((-1, 1))
        r = receive(rng, b, C31, delays, gains, 1.0, 0.0)
        y = rake(r, C31, delays, gains)
        assert abs(y - b * energy(C31, delays, gains)) < 1e-9


def test_maximal_ratio_weights_maximize_the_output_snr() -> None:
    rng = random.Random(3)
    delays = [0, 1, 5]
    gains = [0.9, 0.5 - 0.3j, 0.2j]
    best = output_snr(C7, delays, gains, gains, 1.0, 1.0)
    assert abs(best - energy(C7, delays, gains)) < 1e-12
    for _ in range(500):
        a = [cn(rng, 1.0) for _ in range(3)]
        assert output_snr(C7, delays, gains, a, 1.0, 1.0) <= best + 1e-12
    one_finger = output_snr(C7, delays, gains, [1, 0, 0], 1.0, 1.0)
    assert one_finger < best


def test_bit_error_rate_matches_the_formula() -> None:
    rng = random.Random(4)
    delays, gains = [0, 2], [0.8, 0.6]
    es, n0 = 1.0, 1.0
    pb = bpsk_error_probability(C7, delays, gains, es, n0)
    errors = trials = 0
    while errors < 150:
        b = rng.choice((-1, 1))
        y = rake(receive(rng, b, C7, delays, gains, es, n0), C7, delays, gains)
        trials += 1
        if (1 if y.real >= 0 else -1) != b:
            errors += 1
    lo, hi = wilson(errors, trials)
    assert lo <= pb <= hi


def test_formula_value() -> None:
    pb = bpsk_error_probability(C7, [0, 2], [0.8, 0.6], 1.0, 1.0)
    assert abs(pb - 0.5 * math.erfc(math.sqrt(1 - 0.96 / 7))) < 1e-15

History

Robert Price and Paul Green Jr. described the Rake system in the Proceedings of the IRE in 1958. It sent wideband signals over a multipath HF channel and used a tapped delay line to measure the channel and to weight and add the paths; the name refers to the taps of the delay line, which look like the teeth of a garden rake. With the cellular CDMA systems of the 1990s, IS-95 and later WCDMA, the rake receiver became the standard receiver for direct-sequence signals in mobile phones and base stations.

References

  1. R. Price and P. E. Green, Jr., A communication technique for multipath channels, Proceedings of the IRE 46(3), 1958, pp. 555 to 570 (the Rake system, its tapped delay line and the weighting of the paths by their measured gains)
  2. John G. Proakis and Masoud Salehi, Digital Communications, 5th edition, McGraw-Hill, 2008, The chapter on fading channels (the RAKE demodulator for frequency-selective channels and its error probability)
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, The chapter on diversity (frequency diversity, direct-sequence spread spectrum and the rake receiver)
  4. Andrew J. Viterbi, CDMA, Principles of Spread Spectrum Communication, Addison-Wesley, 1995, The material on multipath diversity reception in a direct-sequence CDMA receiver

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