Algorithm Search⌘K

Algorithmresearch

Coded slotted ALOHA

Also called irregular repetition slotted ALOHA, IRSA.

Users send several copies of a packet in random slots, and the receiver removes collisions by iterative interference cancellation.

Time
Θ(K + M + E) worst · average · best
Space
Θ(M + E) extra
Where
E = the number of copies sent; K = the number of active users; M = the number of slots in a frame
Properties
randomizedframe synchronouslinear timeorder independent
Origin
Enrico Casini, Riccardo De Gaudenzi, Oscar del Rio Herrero, 2007

Coded slotted ALOHA is a random access scheme for many users who send short packets without coordination. Time is cut into frames of MM slots. Each of the KK active users sends dd copies of its packet in dd slots chosen at random, where dd is drawn from a degree distribution Λ\Lambda. Each copy carries pointers to the slots of the other copies. The receiver decodes every slot that holds a single copy, then subtracts the other copies of the packets it has decoded. This can leave new slots with a single copy, and the process repeats. In plain slotted ALOHA, a slot with two packets is lost, and the throughput is at most 1/e≈0.3681/e \approx 0.368 packets per slot. With well chosen distributions, coded slotted ALOHA resolves almost all packets at loads up to about 0.90.9 packets per slot in long frames. The decoder is the peeling decoder of an LDPC code on the binary erasure channel, and its analysis is the same. This page is about a scheme on the collision channel. Unsourced random access is a problem on the Gaussian channel, in which all users share one codebook and the receiver must output only the list of messages; coded slotted ALOHA is one building block of schemes for it.

In plain words

Each user shouts its message several times at random moments in a frame. Often two users shout at the same moment, and both are lost at that moment. But if one copy of a message gets through clearly at some other moment, the listener now knows that message and where its other copies were. The listener removes those copies from the moments where they collided. A collision of two then becomes a clean single message, and the chain goes on. Extra copies cost energy, but they turn most collisions into packets that can be recovered.

The problem

A frame has MM slots and KK active users, each with one packet. The load is G=K/MG = K/M packets per slot. Users do not coordinate, and the receiver does not know in advance which users are active. The model is the collision channel with perfect cancellation:

  • A slot with one copy is decoded correctly, and a check code tells the receiver that it succeeded.
  • A slot with two or more copies gives nothing by itself.
  • When a packet is known, the receiver can rebuild each of its copies and subtract them exactly. The pointers in the packet header tell it where the copies are.

The goal is to resolve as many packets as possible. The measures are the packet loss rate PLP_L, the fraction of the KK packets that are not resolved, and the throughput T=G(1−PL)T = G(1 - P_L) in packets per slot. This is a form of the medium access control problem for many short, uncoordinated transmissions, such as satellite return links and machine-type traffic.

The algorithm

The users are 0,…,K−10, \ldots, K - 1 and the slots are 0,…,M−10, \ldots, M - 1. N(u)N(u) is the set of slots of user uu, and C[s]C[s] is the set of users whose copies in slot ss are not yet cancelled.

  1. CODED-SLOTTED-ALOHA(K, M, Λ)
  2. ▷ transmitter of each user u
  3. 1d ← a degree drawn with Pr(d) = Λ_d
  4. 2N(u) ← d distinct slots drawn uniformly from 0, …, M - 1; send one copy in each
  5. ▷ receiver, at the end of the frame
  6. 3for each user u and each slot s ∈ N(u) do add u to C[s]
  7. 4Q ← a queue of the slots s with |C[s]| = 1
  8. 5while Q is not empty do
  9. 6s ← take a slot from Q
  10. 7if |C[s]| ≠ 1 then continue
  11. 8u ← the only user in C[s]; decode its packet from slot s
  12. 9append u to the resolved list D
  13. 10for each slot t ∈ N(u) do
  14. 11remove u from C[t] and subtract its copy from slot t
  15. 12if |C[t]| = 1 then
  16. 13add t to Q
  17. 14return D

A real receiver does not know C[s]C[s]. It tries to decode each slot and keeps the result only if the check code passes, which in the model happens exactly when ∣C[s]∣=1|C[s]| = 1. Line L8 then reads the pointers from the header, which gives N(u)N(u) for line L10. The implementation works on the graph directly: it is given N(u)N(u) for each user and returns the order in which the users are resolved.

The users and slots form a bipartite graph, with an edge for each copy. It is the Tanner graph of a code: each user is a variable node of degree dd, a repetition code, and each slot is a check node. Lines L5 to L13 are the peeling decoder of that code on the erasure channel.

Example

Take M=6M = 6 slots and K=6K = 6 users, so G=1G = 1, with these slots:

user 0 1 2 3 4 5
N(u)N(u) 0, 1 1, 2 2, 3 3 4, 5 4, 5

So C[0]={0}C[0] = \{0\}, C[1]={0,1}C[1] = \{0, 1\}, C[2]={1,2}C[2] = \{1, 2\}, C[3]={2,3}C[3] = \{2, 3\}, C[4]=C[5]={4,5}C[4] = C[5] = \{4, 5\}. Line L4 puts slot 0 in the queue, the only clean slot.

step slot taken user resolved slots cleaned (line L13)
1 0 0 1
2 1 1 2
3 2 2 3
4 3 3 none

The decoder returns D=[0,1,2,3]D = [0, 1, 2, 3]. Users 4 and 5 used the same two slots, so each of those slots holds two unknown copies, and nothing can separate them. Here PL=2/6P_L = 2/6 and T=4/6T = 4/6. Without cancellation, only slot 0 is clean, and the throughput is 1/61/6.

Correctness

A stopping set is a set SS of users such that every slot of a user in SS holds at least two users of SS. In the example, {4,5}\{4, 5\} is a stopping set. The union of two stopping sets is a stopping set, so a largest one, S∗S^*, exists.

Theorem: the decoder stops with exactly the users of S∗S^* unresolved, whatever order line L6 uses. When it stops, no slot is left with a single uncancelled copy, so the unresolved users form a stopping set. Conversely, the first user of any stopping set to be resolved would need a slot with no other member of the set, which a stopping set does not have. In the collision channel, no other receiver can do better, because each slot of a user in S∗S^* has a second unknown copy. Every resolved packet is correct, since its slot holds only its own copy once the known copies are subtracted. The proof, with the queue invariant, is in the proof file below.

Proof: The iterative cancellation decoder of coded slotted ALOHA resolves exactly the users outside the largest stopping set, in any order, in linear timefull

The notation is that of the page. A frame is a bipartite graph between the users u=1,…,Ku = 1, \ldots, K and the slots s=1,…,Ms = 1, \ldots, M, with an edge for each copy, EE edges in all; user uu has its copies in the set N(u)N(u) of distinct slots. The channel is the collision channel with perfect cancellation: a slot whose copies all belong to known users, except one, gives the packet of that one user after the known copies are subtracted, and a slot with two or more unknown copies gives nothing. During the run, DD is the set of resolved users (line L9), and the residual of a slot ss is r(s)={u∉D:s∈N(u)}r(s) = \{u \notin D : s \in N(u)\}, the users of ss whose copy has not been cancelled. Lines L10 and L11 keep the stored set of slot ss equal to r(s)r(s).

A stopping set is a set SS of users such that every slot used by a user of SS holds at least two users of SS. The empty set is a stopping set, and the union of two stopping sets is a stopping set, because each slot of a user in S1∪S2S_1 \cup S_2 holds two users of S1S_1 or two users of S2S_2. So there is a unique largest stopping set S∗S^*, the union of all of them.

Lemma 1 (soundness). Every user added to DD at line L9 is decoded correctly under the channel model.

Proof. User uu is added when a slot ss has r(s)={u}r(s) = \{u\} (lines L7 and L8). Every other copy in ss belongs to a user already in DD, whose packet is known, so it can be rebuilt and subtracted. What remains is the copy of uu alone. □\square

Lemma 2 (queue invariant). At each test of line L5, every slot ss with ∣r(s)∣=1|r(s)| = 1 is in the queue.

Proof. It holds after line L4. Residuals only shrink, at line L11. A slot whose residual drops to size 1 is pushed at line L13. A slot that is popped at line L6 with ∣r(s)∣=1|r(s)| = 1 has its only user uu resolved, and s∈N(u)s \in N(u), so line L11 empties r(s)r(s) in the same pass. A slot popped with ∣r(s)∣≠1|r(s)| \ne 1 is not of size 1 at that moment, and it can reach size 1 later only through line L13, which pushes it again. □\square

Lemma 3 (termination and cost). The loop runs at most MM times, each user is resolved at most once, and the total work is O(K+M+E)O(K + M + E).

Proof. The size of a residual only decreases, so it becomes equal to 1 at most once; a slot enters the queue at line L4 if it starts at size 1, or at line L13 when it drops to size 1, and not both. So there are at most MM pushes and MM pops. Once uu is resolved, it leaves the residual of each of its slots (line L11), so it can never again be the only member of a residual, and it is resolved once. Line L3 does EE insertions. Lines L10 to L13 run once per edge of a resolved user, so at most EE times in total. Each set operation is O(1)O(1) expected with hashing, or O(1)O(1) worst case with counters and a sum of user identifiers per slot, which recovers the last user of a slot as the sum. □\square

Theorem. When the decoder stops, the set of unresolved users is U∖D=S∗U \setminus D = S^*, the largest stopping set. In particular the resolved set does not depend on the order in which line L6 takes the slots from the queue.

Proof. Let F=U∖DF = U \setminus D at the end.

First, FF is a stopping set. The queue is empty at the end, so by Lemma 2 no slot has a residual of size 1. Take u∈Fu \in F and a slot s∈N(u)s \in N(u). User uu is not in DD, so u∈r(s)u \in r(s), and ∣r(s)∣≥1|r(s)| \ge 1, hence ∣r(s)∣≥2|r(s)| \ge 2. Every user of r(s)r(s) is unresolved, so it lies in FF. So ss holds at least two users of FF.

Second, every stopping set SS lies inside FF. Suppose not, and let uu be the first user of SS that line L9 resolves. At that moment some slot s∈N(u)s \in N(u) has r(s)={u}r(s) = \{u\}. Since SS is a stopping set, ss holds another user v∈Sv \in S with v≠uv \ne u. User vv is not yet resolved, because uu is the first of SS, so v∈r(s)v \in r(s). This contradicts r(s)={u}r(s) = \{u\}.

So FF is a stopping set that contains every stopping set, which is S∗S^*. The set S∗S^* depends only on the graph, so the result does not depend on the queue order. □\square

Remark (no decoder does better in the model). In the collision channel, a user of S∗S^* has no slot that is clean even after every user outside S∗S^* is cancelled, because each of its slots holds a second unknown copy from S∗S^*. A slot with two unknown copies gives nothing in this model, so no receiver, however complex, can recover any user of S∗S^*. The decoder therefore resolves every user that the model allows. A receiver that can decode two overlapping packets (capture, or multiuser detection in a slot) works in a different model.

What is not proved here. The asymptotic threshold of a degree distribution comes from density evolution (Paolini, Liva and Chiani 2015, Corollary 3.1), which tracks the probability that an edge is still unresolved when KK and MM grow with K/M=GK/M = G fixed and the graph is locally a tree. The tests check the recursion against the published thresholds; this file proves only the finite-frame statements above.

Complexity

Time. Line L3 makes E=∑u∣N(u)∣E = \sum_u |N(u)| insertions. A slot enters the queue at most once, because its set only shrinks and reaches size 1 only once, so the loop runs at most MM times. Lines L10 to L13 run once for each copy of a resolved user, at most EE times in total. So the decoder costs Θ(K+M+E)\Theta(K + M + E) word operations. With mean degree dˉ=∑ddΛd\bar d = \sum_d d \Lambda_d, EE is about dˉK\bar d K. Each operation on C[s]C[s] is O(1)O(1) with a counter and the sum of the identifiers of the users still in the slot: when the counter is 1, the sum is the remaining user.

Space. Θ(M+E)\Theta(M + E) for the slot sets and the lists N(u)N(u). A real receiver also stores the MM received slot signals for the frame.

Properties

  • Density evolution threshold (theorem). Let KK and MM grow with G=K/MG = K/M fixed. Let pp be the probability that a copy is still unresolved after an iteration. Paolini, Liva and Chiani (Corollary 3.1) give the recursion p←1−exp⁡(−G∑ddΛdpd−1)p \leftarrow 1 - \exp(-G \sum_d d \Lambda_d p^{d-1}), from p=1p = 1. The threshold G∗G^* is the largest load at which pp goes to 0. Below G∗G^*, almost all packets are resolved in long frames. The implementation finds G∗G^* by bisection, with these results:
distribution Λ(x)\Lambda(x) mean degree G∗G^* (computed) load bound
x2x^2 (two copies, as in CRDSA) 2 0.5 (exact) 0.7968
x3x^3 3 0.8185 0.9405
x4x^4 4 0.7723 0.9802
x5x^5 5 0.7018 0.9930
0.5x2+0.28x3+0.22x80.5x^2 + 0.28x^3 + 0.22x^8 (Liva 2011) 3.6 0.9386 0.9695
0.554016x2+0.261312x3+0.184672x60.554016x^2 + 0.261312x^3 + 0.184672x^6 (Paolini et al., Table I) 3 0.8792 0.9405

The values agree with the published thresholds 0.5, 0.938 and 0.8792 within 10−310^{-3} (checked in the tests). For x2x^2 the recursion is p←1−e−2Gpp \leftarrow 1 - e^{-2Gp}. Since 1−e−z<z1 - e^{-z} < z for z>0z > 0, pp falls to 0 when 2G≤12G \le 1, and a fixed point p>0p > 0 exists when 2G>12G > 1, so G∗=1/2G^* = 1/2 exactly. Near G=1/2G = 1/2 the recursion converges very slowly, so the bisection with 20000 iterations stops at 0.4996.

  • Load bound (theorem). With rate R=1/dˉR = 1/\bar d, one packet for dˉ\bar d copies, every distribution has G∗≤GRG^* \le G_R, the positive root of G=1−e−G/RG = 1 - e^{-G/R} (Paolini et al., Theorem 4.1). For R=1/3R = 1/3 this gives 0.9405. To reach loads near 1, the mean degree must grow.
  • Stability (closed form). Near p=0p = 0, the recursion multiplies pp by 2Λ2G2 \Lambda_2 G. So G∗≤1/(2Λ2)G^* \le 1/(2\Lambda_2). Users of degree 2 help the decoder start, but too many of them stop it before the end. For the distribution of Liva, this bound is 1.
  • Throughput tends to 1 (theorem). Narayanan and Pfister showed that the soliton distribution, Λd=1/(d(d−1))\Lambda_d = 1/(d(d-1)) for d≥2d \ge 2 with a truncation, gives G∗G^* as close to 1 as wanted, at the cost of a mean degree that grows like the logarithm of the largest degree.
  • Error floor in finite frames (measurement and heuristic). For Liva's distribution with M=200M = 200 and 2000 frames at each load (one generator with seed 7, the loads in turn), PLP_L was 0.0010 at G=0.3G = 0.3, 0.0020 at G=0.4G = 0.4 and 0.0025 at G=0.5G = 0.5. The floor comes from small stopping sets. The smallest is two users of degree 2 on the same two slots, with probability about Λ2⋅(K−1)Λ2/(M2)\Lambda_2 \cdot (K - 1)\Lambda_2 / \binom{M}{2} for a given user, which is 0.00120.0012 at G=0.5G = 0.5. This is about half of the measured floor; larger stopping sets give the rest.
  • Finite frames lose part of the threshold (measurement). With M=200M = 200, K=GMK = GM and 100 frames for each point (a new generator with seed 1 for each distribution, the loads in turn), PLP_L was:
distribution G=0.4G = 0.4 G=0.5G = 0.5 G=0.6G = 0.6 G=0.7G = 0.7 G=0.8G = 0.8
x2x^2 0.016 0.030 0.109 0.263 0.40
Liva 2011 0.0011 0.0022 0.0025 0.0076 0.042
Paolini et al., R=1/3R = 1/3 0.0005 0.0022 0.0053 0.0215 0.085

At G=0.8G = 0.8, Liva's distribution gives T=0.766T = 0.766 packets per slot, about twice the peak of slotted ALOHA. A new generator with seed 1 and one copy per user (Λ=x\Lambda = x) at G=0.4G = 0.4 gave PL=0.3291P_L = 0.3291, against the closed form 1−(1−1/M)K−1=0.32701 - (1 - 1/M)^{K-1} = 0.3270.

  • Energy cost (closed form). A user sends dˉ\bar d copies, so it uses dˉ\bar d times the energy of slotted ALOHA for each packet: 3.6 times, or 5.6 dB, for Liva's distribution.

Variants and improvements

  • CRDSA. The first scheme, by Casini, De Gaudenzi and del Rio Herrero, sends exactly two copies, Λ=x2\Lambda = x^2. Its threshold is 0.5.
  • A random number of copies. Liva drew dd from an optimized distribution, which is the scheme on this page. It is the special case of the general scheme below in which every local code is a repetition code.
  • Coded slotted ALOHA with local codes. Paolini, Liva and Chiani split each packet into kk segments and encode them with a short (n,k)(n, k) code instead of repetition. A slot node then resolves a segment, and a user node resolves the packet when any kk of its nn segments are known. This gives better thresholds at a given rate.
  • Frameless ALOHA. Users send in each slot with a small probability, and the receiver ends the frame when enough packets are resolved, as in a rateless code.
  • Capture and multipacket reception. If the receiver can decode the strongest of two colliding copies, or two copies at once with successive interference cancellation, more slots start the peeling, and loads above 1 become possible.
  • Unsourced random access. When every user sends from the same codebook and the receiver needs only the list of messages, coded slotted ALOHA becomes one building block. Each slot then carries a short multiuser code. See unsourced random access.

When to use it

Use coded slotted ALOHA when many devices send short, rare packets and a handshake for each packet would cost more than the data: satellite return links (it is in the DVB-RCS2 standard, as CRDSA), sensor networks and machine-type traffic. The receiver must store a whole frame and cancel signals well, and the users must agree on the frame boundaries. When the traffic is steady, scheduled access such as TDMA or OFDMA wastes less energy. When devices are few and can listen before they send, CSMA/CA is simpler.

Pitfalls

  • Reading the threshold as a frame result. G∗G^* holds only as MM grows. With M=200M = 200, Liva's distribution loses about 4 percent of the packets at G=0.8G = 0.8, below its threshold of 0.94.
  • Ignoring the error floor. A PLP_L near 10−310^{-3} at low load comes from small stopping sets, not from the load, and more iterations do not remove it. Avoid many users of degree 2, or add an outer code.
  • Assuming perfect cancellation. Each copy passes through its own channel. The receiver must estimate the gain and phase of each copy before it subtracts it, or residual interference builds up over the iterations.
  • Sending two copies in the same slot. Line L2 draws distinct slots. Two copies in one slot cannot help, and a user can then form a stopping set alone.
  • Forgetting the energy cost. For the same energy per packet, each copy of a user with dˉ\bar d copies has dˉ\bar d times less energy. Compare schemes at equal energy, not at equal power per slot.

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)
coded_slotted_aloha.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coded-slotted-aloha/. The authors are listed in prov/KAWTQF.jsonl.

"""Coded slotted ALOHA: repetition of packets in random slots and iterative interference cancellation.

Model (the collision channel of Casini et al. 2007, Liva 2011 and Paolini et al. 2015):
- A frame has M slots and K active users. User u draws a degree d from the distribution
  Lambda (a dict {d: Lambda_d}) and sends d copies of its packet in d distinct slots,
  chosen uniformly at random.
- A slot with exactly one copy is decoded. A slot with two or more copies is a collision
  and gives nothing by itself. Every copy carries pointers to the slots of its twins,
  so a decoded packet lets the receiver cancel all its other copies perfectly.

A frame is given as user_slots: a list with, for each user, the list of its slots.
The decoder works on the bipartite graph of users and slots and costs O(K + M + E)
word operations for E copies in total (word-RAM model).

The file also has the density evolution recursion of Paolini, Liva and Chiani 2015
(Corollary 3.1) for the asymptotic threshold, and the bound of their Theorem 4.1.
"""

import math
import random
from collections import deque


def transmit(rng: random.Random, k: int, m: int, dist: dict) -> list[list[int]]:
    """Draw the slots of k users in a frame of m slots, with degree distribution dist."""
    if m <= 0 or k < 0:
        raise ValueError("need m > 0 and k >= 0")
    if any(d < 1 or d > m for d in dist) or abs(sum(dist.values()) - 1.0) > 1e-9:
        raise ValueError("dist must be a probability distribution on degrees 1..m")
    degrees = sorted(dist)
    weights = [dist[d] for d in degrees]
    frame = []
    for _ in range(k):
        d = rng.choices(degrees, weights)[0]  # @line L1
        frame.append(sorted(rng.sample(range(m), d)))  # @line L2
    return frame


def decode(user_slots: list[list[int]], m: int, rng: random.Random | None = None) -> list[int]:
    """Iterative interference cancellation (peeling). Returns the resolved users in decoding order.

    With rng given, the next singleton slot is taken at random instead of first in, first out.
    The set of resolved users does not depend on this choice (see proofs/correctness.md).
    """
    slots = [set() for _ in range(m)]
    for u, ss in enumerate(user_slots):
        if len(set(ss)) != len(ss):
            raise ValueError("a user sends at most one copy per slot")
        for s in ss:
            slots[s].add(u)  # @line L3
    queue = deque(s for s in range(m) if len(slots[s]) == 1)  # @line L4
    resolved = []
    while queue:  # @line L5
        if rng is None:
            s = queue.popleft()  # @line L6
        else:
            i = rng.randrange(len(queue))
            queue[i], queue[-1] = queue[-1], queue[i]
            s = queue.pop()  # @line L6
        if len(slots[s]) != 1:  # @line L7
            continue
        (u,) = slots[s]  # @line L8
        resolved.append(u)  # @line L9
        for t in user_slots[u]:  # @line L10
            slots[t].discard(u)  # @line L11
            if len(slots[t]) == 1:  # @line L12
                queue.append(t)  # @line L13
    return resolved  # @line L14


def unresolved_brute_force(user_slots: list[list[int]], m: int) -> set[int]:
    """The largest stopping set, by search over all subsets of users (small K only).

    A set S of users is a stopping set if every slot used by a user of S holds at least
    two users of S. The union of two stopping sets is a stopping set, so a largest one exists.
    """
    k = len(user_slots)
    best = set()
    for mask in range(1 << k):
        count = [0] * m
        members = [u for u in range(k) if mask >> u & 1]
        for u in members:
            for s in user_slots[u]:
                count[s] += 1
        if all(count[s] >= 2 for u in members for s in user_slots[u]) and len(members) > len(best):
            best = set(members)
    return best


def rate(dist: dict) -> float:
    """The rate R = 1 / Lambda'(1) of the repetition code: one packet over the mean number of copies."""
    return 1.0 / sum(d * p for d, p in dist.items())


def de_step(dist: dict, g: float, p: float) -> float:
    """One step of density evolution: p <- 1 - exp(-G sum_d d Lambda_d p^(d-1))."""
    return 1.0 - math.exp(-g * sum(d * lam * p ** (d - 1) for d, lam in dist.items()))


def de_converges(dist: dict, g: float, iters: int = 20000, tol: float = 1e-9) -> bool:
    """True if density evolution from p = 1 goes to 0 at the load G = g."""
    p = 1.0
    for _ in range(iters):
        q = de_step(dist, g, p)
        if q < tol:
            return True
        if abs(q - p) < 1e-15:
            return False
        p = q
    return False


def threshold(dist: dict, tol: float = 1e-5) -> float:
    """The asymptotic threshold G* = sup of the loads at which density evolution goes to 0."""
    lo, hi = 0.0, 1.0
    while hi - lo > tol:
        mid = 0.5 * (lo + hi)
        if de_converges(dist, mid):
            lo = mid
        else:
            hi = mid
    return lo


def load_bound(r: float, tol: float = 1e-12) -> float:
    """The unique positive root G of G = 1 - exp(-G / R), for 0 < R < 1 (Paolini et al. 2015, Theorem 4.1)."""
    if not 0.0 < r < 1.0:
        raise ValueError("need 0 < R < 1")
    lo, hi = 1e-9, 1.0
    while hi - lo > tol:
        mid = 0.5 * (lo + hi)
        if 1.0 - math.exp(-mid / r) > mid:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)
test_coded_slotted_aloha.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coded-slotted-aloha/. The authors are listed in prov/KAWTQF.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from cbb import wilson
from coded_slotted_aloha import (
    de_converges,
    decode,
    load_bound,
    rate,
    threshold,
    transmit,
    unresolved_brute_force,
)

CRDSA = {2: 1.0}
REG3 = {3: 1.0}
LIVA_LAMBDA3 = {2: 0.5, 3: 0.28, 8: 0.22}  # Liva 2011, Section IV-B
PAOLINI_R13 = {2: 0.554016, 3: 0.261312, 6: 0.184672}  # Paolini, Liva and Chiani 2015, Table I


def random_dist(rng, m):
    degrees = sorted(rng.sample(range(1, min(m, 4) + 1), rng.randint(1, min(m, 4))))
    w = [rng.random() + 0.05 for _ in degrees]
    s = sum(w)
    return {d: x / s for d, x in zip(degrees, w)}


def test_decode_matches_largest_stopping_set():
    rng = random.Random(11)
    for _ in range(150):
        m = rng.randint(1, 8)
        k = rng.randint(0, 9)
        frame = transmit(rng, k, m, random_dist(rng, m))
        got = decode(frame, m)
        assert len(got) == len(set(got))
        assert set(got) == set(range(k)) - unresolved_brute_force(frame, m)


def test_resolved_set_does_not_depend_on_order():
    rng = random.Random(12)
    for _ in range(60):
        m = rng.randint(2, 30)
        k = rng.randint(1, 40)
        frame = transmit(rng, k, m, random_dist(rng, m))
        ref = set(decode(frame, m))
        for seed in range(4):
            assert set(decode(frame, m, random.Random(seed))) == ref


def test_decoding_order_is_valid():
    # Each resolved user must have a slot that is clean once the earlier users are cancelled.
    rng = random.Random(13)
    for _ in range(60):
        m = rng.randint(2, 20)
        k = rng.randint(1, 25)
        frame = transmit(rng, k, m, random_dist(rng, m))
        done = set()
        for u in decode(frame, m):
            assert any(
                all(v == u or v in done for v in range(k) if s in frame[v]) for s in frame[u]
            )
            done.add(u)


def test_hand_example():
    # Four users, four slots: users 0 and 1 collide in both their slots (a stopping set).
    frame = [[0, 1], [0, 1], [1, 2], [2, 3]]
    assert decode(frame, 4) == [3, 2]
    assert unresolved_brute_force(frame, 4) == {0, 1}
    # Peeling chain: slot 0 holds only user 0; cancelling it cleans slot 1 for user 1, and so on.
    frame = [[0, 1], [1, 2], [2, 3], [3]]
    assert decode(frame, 4) == [0, 1, 2, 3]


def test_page_example():
    # The example of the page: M = 6, K = 6; users 4 and 5 form a stopping set.
    frame = [[0, 1], [1, 2], [2, 3], [3], [4, 5], [4, 5]]
    assert decode(frame, 6) == [0, 1, 2, 3]
    assert unresolved_brute_force(frame, 6) == {4, 5}
    # Without cancellation only slot 0 is clean.
    clean = [s for s in range(6) if sum(s in f for f in frame) == 1]
    assert clean == [0]


def test_slotted_aloha_degree_one_closed_form():
    # Degree 1 is slotted ALOHA: a user succeeds iff no other user picks its slot,
    # with probability (1 - 1/M)^(K - 1). n = 30000 user trials, about 11000 failures expected.
    rng = random.Random(14)
    k, m, frames = 10, 20, 3000
    ok = sum(len(decode(transmit(rng, k, m, {1: 1.0}), m)) for _ in range(frames))
    lo, hi = wilson(ok, k * frames)
    assert lo <= (1 - 1 / m) ** (k - 1) <= hi


def test_loss_rate_matches_exact_enumeration():
    # K = 3 users of degree 2 in M = 4 slots: enumerate all 6^3 frames with the brute-force
    # stopping set, then simulate n = 3 * 20000 user trials and check the Wilson interval.
    k, m = 3, 4
    pairs = list(itertools.combinations(range(m), 2))
    lost = sum(len(unresolved_brute_force([list(p) for p in f], m)) for f in itertools.product(pairs, repeat=k))
    exact = Fraction(lost, k * len(pairs) ** k)
    rng = random.Random(15)
    frames = 20000
    sim = sum(k - len(decode(transmit(rng, k, m, CRDSA), m)) for _ in range(frames))
    lo, hi = wilson(sim, k * frames)
    assert sim >= 100
    assert lo <= float(exact) <= hi


@pytest.mark.parametrize(
    "dist, expected, tol",
    [
        (CRDSA, 0.5, 1e-3),  # Liva 2011: CRDSA threshold 0.5
        (LIVA_LAMBDA3, 0.938, 1e-3),  # Liva 2011, Section IV-B
        (PAOLINI_R13, 0.8792, 1e-3),  # Paolini et al. 2015, Table I, R = 1/3
        ({4: 1.0}, 0.772, 1e-3),  # Liva 2011, 4-regular
    ],
)
def test_density_evolution_thresholds(dist, expected, tol):
    g = threshold(dist, tol=1e-4)
    assert abs(g - expected) < tol
    assert g <= load_bound(rate(dist)) + 1e-9
    if 2 in dist:
        assert g <= 1 / (2 * dist[2]) + 1e-3  # stability bound


def test_regular_three_threshold_and_bound():
    g = threshold(REG3, tol=1e-4)
    assert 0.817 < g < 0.820
    assert de_converges(REG3, 0.80)
    assert not de_converges(REG3, 0.83)


@pytest.mark.parametrize(
    "r, expected",
    [(1 / 3, 0.9405), (2 / 5, 0.8926), (1 / 2, 0.7968), (3 / 5, 0.6758)],
)
def test_load_bound_values(r, expected):
    # Paolini et al. 2015, Theorem 4.1 and Table I
    assert abs(load_bound(r) - expected) < 1e-4


def test_finite_frame_below_threshold():
    # Liva's distribution at G = 0.5 with M = 200 slots: almost every packet is resolved.
    rng = random.Random(16)
    m, k, frames = 200, 100, 30
    lost = sum(k - len(decode(transmit(rng, k, m, LIVA_LAMBDA3), m)) for _ in range(frames))
    assert lost / (k * frames) < 0.02


def test_input_checks():
    with pytest.raises(ValueError):
        decode([[1, 1]], 3)
    with pytest.raises(ValueError):
        transmit(random.Random(0), 2, 3, {4: 1.0})
    with pytest.raises(ValueError):
        load_bound(1.0)

History

Abramson's ALOHA system of 1970 and the slotted version of Roberts in 1972 lost every collided packet. In 2007, Casini, De Gaudenzi and del Rio Herrero proposed contention resolution diversity slotted ALOHA (CRDSA) for satellite networks. Each packet was sent twice, with pointers to its twin, and the receiver cancelled the copies of decoded packets iteratively. In 2011, Liva saw that the process is the erasure decoding of a code on a graph. He let the number of copies vary, optimized its distribution with density evolution, and obtained thresholds above 0.9. In 2012, Narayanan and Pfister showed that the soliton distribution brings the throughput arbitrarily close to 1. In 2015, Paolini, Liva and Chiani replaced repetition with general local codes and gave an upper bound on the load for each rate. Later work used the scheme as an outer code for unsourced random access, and studied frameless versions, capture and fading channels.

References

  1. Enrico Casini, Riccardo De Gaudenzi and Oscar del Rio Herrero, Contention resolution diversity slotted ALOHA (CRDSA): an enhanced random access scheme for satellite access packet networks, IEEE Transactions on Wireless Communications 6(4), 2007, pp. 1408 to 1419 (two copies of each packet per frame, pointers to the twin copy and iterative cancellation of the copies of decoded packets)
  2. Gianluigi Liva, Graph-based analysis and optimization of contention resolution diversity slotted ALOHA, IEEE Transactions on Communications 59(2), 2011, pp. 477 to 487 (irregular numbers of copies, the bipartite graph of users and slots, the analysis by density evolution and optimized distributions such as 0.5x^2 + 0.28x^3 + 0.22x^8 with threshold 0.938)
  3. Enrico Paolini, Gianluigi Liva and Marco Chiani, Coded slotted ALOHA, a graph-based method for uncoordinated multiple access, IEEE Transactions on Information Theory 61(12), 2015, pp. 6815 to 6832 (density evolution in Corollary 3.1, the upper bound on the load for a given rate in Theorem 4.1 and the distributions of Table I)
  4. Krishna R. Narayanan and Henry D. Pfister, Iterative collision resolution for slotted ALOHA, an optimal uncoordinated transmission policy, 7th International Symposium on Turbo Codes and Iterative Information Processing, Gothenburg, 2012, pp. 136 to 139 (the soliton distribution of the number of copies and the proof that the throughput tends to 1 packet per slot)

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.average
  • a full proof of time.best
  • 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