Algorithm Search⌘K

Definitioncore

Maximal-length sequence

Also called m-sequence, PN sequence, pseudonoise sequence.

The output of a linear feedback shift register with a primitive polynomial of degree n. It has period 2^n - 1, is nearly balanced, and its periodic autocorrelation takes only two values.

A maximal-length sequence, or m-sequence, is the output of a binary linear feedback shift register whose feedback polynomial is primitive. A register of nn cells can hold 2n−12^n - 1 nonzero states, and with a primitive polynomial it goes through all of them before it repeats, so the output has the longest possible period N=2n−1N = 2^n - 1. Three properties make m-sequences the standard spreading code of direct-sequence spread spectrum and the building block of Gold and Kasami sequences: the numbers of ones and zeros in a period differ by one, the runs have a fixed distribution, and the periodic autocorrelation in ±1\pm 1 form is NN at shift 00 and −1-1 at every other shift. These are exact results for every primitive polynomial, not statistics of a random model. The sequence is easy to predict from 2n2n consecutive bits, so it is pseudorandom in the sense of correlation, not in the sense of cryptography.

Definition

Let f(x)=xn+fn−1xn−1+⋯+f1x+1f(x) = x^n + f_{n-1} x^{n-1} + \cdots + f_1 x + 1 be a polynomial over GF(2), with fi∈{0,1}f_i \in \{0, 1\}. A binary sequence s0,s1,s2,…s_0, s_1, s_2, \ldots satisfies the linear recurrence of ff if

sk+n=∑i=0n−1fi sk+i(mod2)for all k≥0,f0=1.s_{k+n} = \sum_{i=0}^{n-1} f_i \, s_{k+i} \pmod 2 \qquad \text{for all } k \ge 0, \quad f_0 = 1.

The start state (s0,…,sn−1)(s_0, \ldots, s_{n-1}) fixes the whole sequence. The sequence is periodic, because the state (sk,…,sk+n−1)(s_k, \ldots, s_{k+n-1}) can take at most 2n2^n values and the map from one state to the next is invertible (the constant term f0=1f_0 = 1 lets us recover sks_k from the next state). The zero state gives the zero sequence, so a nonzero start gives a period of at most 2n−12^n - 1.

A maximal-length sequence of degree nn is a nonzero sequence that satisfies the recurrence of some ff of degree nn and has period exactly N=2n−1N = 2^n - 1. This happens if and only if ff is a primitive polynomial: ff is irreducible and its roots have multiplicative order 2n−12^n - 1 in GF(2n2^n) (Golomb, the chapter on linear shift register sequences). Then every nonzero start state gives an m-sequence, and the 2n−12^n - 1 nonzero start states give the NN cyclic shifts of one sequence.

The ±1\pm 1 form maps bit 00 to +1+1 and bit 11 to −1-1: ak=(−1)sk=1−2ska_k = (-1)^{s_k} = 1 - 2 s_k. The periodic correlation of two ±1\pm 1 sequences aa and bb of period NN at shift tt is

Ca,b(t)=∑k=0N−1ak b(k+t) mod N,C_{a,b}(t) = \sum_{k=0}^{N-1} a_k \, b_{(k+t) \bmod N},

and the periodic autocorrelation is Ca,a(t)C_{a,a}(t). The mapping turns XOR into a product: (−1)s⊕s′=(−1)s(−1)s′(-1)^{s \oplus s'} = (-1)^{s} (-1)^{s'}.

The procedure below generates one period and its autocorrelation. It uses O(n)O(n) word operations per output bit, or O(1)O(1) if the taps are packed into one machine word, so one period costs O(Nn)O(N n) in the word RAM model in this plain form, and the full autocorrelation costs O(N2)O(N^2) by direct sums.

  1. M-SEQUENCE(f, state) ▷ f primitive of degree n, state ≠ 0, N = 2^n - 1
  2. 1s[0 .. n-1] ← state
  3. for k ← 0 to N - n - 1 do
  4. 2b ← XOR of s[k + i] over the exponents i < n of f
  5. 3s[k + n] ← b
  6. 4a[k] ← 1 - 2 s[k] for k = 0, ..., N - 1 ▷ the ±1 form
  7. 5C(t) ← Σ_k a[k] a[(k + t) mod N] for t = 0, ..., N - 1
  8. return s, C

Properties. Let ss be an m-sequence of degree nn and period N=2n−1N = 2^n - 1. Golomb lists the first three as his randomness postulates, and m-sequences satisfy all of them:

  1. Balance. One period holds 2n−12^{n-1} ones and 2n−1−12^{n-1} - 1 zeros. In ±1\pm 1 form, ∑kak=−1\sum_k a_k = -1.
  2. Runs. A run is a maximal block of equal bits, read cyclically. One period has 2n−12^{n-1} runs. For 1≤ℓ≤n−21 \le \ell \le n - 2 there are 2n−ℓ−22^{n-\ell-2} runs of ones and 2n−ℓ−22^{n-\ell-2} runs of zeros of length ℓ\ell. There is one run of n−1n - 1 zeros and one run of nn ones.
  3. Two-level autocorrelation. Ca,a(0)=NC_{a,a}(0) = N and Ca,a(t)=−1C_{a,a}(t) = -1 for t=1,…,N−1t = 1, \ldots, N - 1.
  4. Window property. Each nonzero nn-tuple appears exactly once as a window (sk,…,sk+n−1)(s_k, \ldots, s_{k+n-1}) in one period. The zero nn-tuple never appears.
  5. Shift and add. For t≢0(modN)t \not\equiv 0 \pmod N, the sum sk⊕sk+ts_k \oplus s_{k+t} is again a shift sk+ds_{k+d} of the same sequence, for some dd that depends on tt.

Property 3 follows from properties 5 and 1. For t≠0t \ne 0, akak+t=(−1)sk⊕sk+t=(−1)sk+da_k a_{k+t} = (-1)^{s_k \oplus s_{k+t}} = (-1)^{s_{k+d}}, so Ca,a(t)=∑k(−1)sk+dC_{a,a}(t) = \sum_k (-1)^{s_{k+d}}, which is the number of zeros minus the number of ones in a period: (2n−1−1)−2n−1=−1(2^{n-1} - 1) - 2^{n-1} = -1. Property 5 holds because the sum of two solutions of a linear recurrence is a solution, its start state is nonzero when t≠0t \ne 0 (by property 4), and every nonzero solution is a shift of ss.

Two consequences follow. The DFT of one period of aa has ∣A[0]∣2=1|A[0]|^2 = 1 and ∣A[k]∣2=N+1|A[k]|^2 = N + 1 for k≠0k \ne 0, since the DFT of the autocorrelation (N+1)δt−1(N + 1)\delta_t - 1 is the squared magnitude spectrum. So the periodic sequence has a flat line spectrum except at zero frequency, which is why it looks like white noise to a correlator. Second, the NN shifts of one period together with the zero word are the codewords of the simplex code of length NN and dimension nn, the dual of the Hamming code; every nonzero codeword has weight 2n−12^{n-1}. The number of distinct m-sequences of degree nn, up to shifts, equals the number of primitive polynomials of degree nn, which is φ(2n−1)/n\varphi(2^n - 1)/n with Euler's function φ\varphi.

Examples and non-examples

Degree 3. Take f(x)=x3+x+1f(x) = x^3 + x + 1, so the recurrence is sk+3=sk+1⊕sks_{k+3} = s_{k+1} \oplus s_k. From the state 100100:

kk 0 1 2 3 4 5 6
sks_k 1 0 0 1 0 1 1
window sksk+1sk+2s_k s_{k+1} s_{k+2} 100 001 010 101 011 111 110
aka_k -1 +1 +1 -1 +1 -1 -1

Then s7=s5⊕s4=1=s0s_7 = s_5 \oplus s_4 = 1 = s_0, s8=s6⊕s5=0=s1s_8 = s_6 \oplus s_5 = 0 = s_1, and the sequence 10010111001011 repeats with period 7=23−17 = 2^3 - 1. The windows list all seven nonzero triples once. There are four ones and three zeros. The periodic autocorrelation at shifts 00 to 66 is (7,−1,−1,−1,−1,−1,−1)(7, -1, -1, -1, -1, -1, -1). At shift 11, for example, the products akak+1a_k a_{k+1} are −1,+1,−1,−1,−1,+1,+1-1, +1, -1, -1, -1, +1, +1, with sum −1-1. Shift and add: sk⊕sk+1s_k \oplus s_{k+1} for k=0,…,6k = 0, \ldots, 6 is 10111001011100, which is sk+3s_{k+3}, the sequence shifted by 33.

Degree 4. f(x)=x4+x+1f(x) = x^4 + x + 1 from the state 10001000 gives 100010011010111100010011010111, of period 1515, with eight ones and seven zeros. Its 88 runs are two runs of length 11 of each bit, one run of length 22 of each bit, one run of three zeros and one run of four ones, as property 2 says. The autocorrelation is 1515 at shift 00 and −1-1 at the other 1414 shifts.

Degree 5. f(x)=x5+x2+1f(x) = x^5 + x^2 + 1 from 1000010000 gives the period 10000100101100111110001101110101000010010110011111000110111010 of length 3131. Degree 5 has φ(31)/5=6\varphi(31)/5 = 6 primitive polynomials, so there are six different m-sequences of period 31. Two of them, from x5+x2+1x^5 + x^2 + 1 and x5+x4+x3+x2+1x^5 + x^4 + x^3 + x^2 + 1, form the preferred pair behind the Gold sequences of period 31.

Non-example: a reducible polynomial. x4+x2+1=(x2+x+1)2x^4 + x^2 + 1 = (x^2 + x + 1)^2 gives period 66 from the state 10001000, not 1515. The register splits its nonzero states into several shorter cycles.

Non-example: irreducible but not primitive. x4+x3+x2+x+1x^4 + x^3 + x^2 + x + 1 is irreducible over GF(2), but its roots are fifth roots of unity, so the period is 55 from every nonzero state. Irreducibility is not enough.

Non-example: a random sequence. A sequence of 1515 fair coin flips has a periodic autocorrelation whose off-peak values spread around 00 with a standard deviation near 15\sqrt{15}. Small values like −1-1 at every shift are what make the m-sequence useful for code acquisition: a correlator sees a peak of NN against a floor of exactly −1-1.

Non-example: Barker codes. A Barker code has small aperiodic autocorrelation, which matters for a single radar pulse. An m-sequence is designed for the periodic case. The aperiodic autocorrelation of 10010111001011 at shifts 11 to 66 is (−2,−1,2,−3,0,1)(-2, -1, 2, -3, 0, 1), with a peak sidelobe of 33, while the Barker code of length 7 has sidelobes of magnitude at most 11.

  • Linear feedback shift register is the circuit that runs the recurrence, and primitive polynomial is the condition for the maximal period. Those pages give the algebra; this page gives the correlation properties used in communications.
  • A de Bruijn sequence of order nn holds every nn-tuple once, including the zero tuple. Inserting one extra zero into the run of n−1n - 1 zeros of an m-sequence gives a de Bruijn sequence of length 2n2^n.
  • Gold sequences add two m-sequences of a preferred pair, and Kasami sequences add an m-sequence and a decimation of it. Both give many sequences with low cross-correlation. One m-sequence alone has a perfect two-level autocorrelation, but different m-sequences of the same degree can have large cross-correlation.
  • The Welch bound limits how low the correlations of a family of many sequences can be. For one ±1\pm 1 sequence of odd length NN, every correlation value is odd, so −1-1 is the smallest possible off-peak magnitude, and an m-sequence reaches it at every shift.
  • Zadoff-Chu sequences are complex sequences with an off-peak periodic autocorrelation of exactly 00, which no binary sequence of odd length can have.
  • The Hamming code is the dual of the simplex code formed by the shifts of an m-sequence.

Code

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.

maximal_length_sequence.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-length-sequence/. The authors are listed in prov/09SJJW.jsonl.

"""Maximal-length sequences (m-sequences) from a binary linear recurrence.

A polynomial f(x) = x^n + ... + 1 over GF(2) is given by the list of its
exponents, for example [3, 1, 0] for x^3 + x + 1. The sequence satisfies
the recurrence sum over i of f_i s[k + i] = 0 (mod 2), that is

    s[k + n] = XOR over the exponents i < n of s[k + i].

If f is primitive, every nonzero start state gives a sequence of period
2^n - 1, which is an m-sequence. All arithmetic is on Python integers.
"""


def lfsr_bits(exps: list[int], state: list[int], count: int) -> list[int]:
    """The first count terms s[0], s[1], ... of the recurrence of f, from s[0..n-1] = state."""
    n = max(exps)
    if len(state) != n or 0 not in exps:
        raise ValueError("need n start bits and a polynomial with constant term 1")
    taps = [i for i in exps if i < n]
    s = [b & 1 for b in state]  # @line L1
    while len(s) < count:
        k = len(s) - n
        bit = 0
        for i in taps:  # @line L2
            bit ^= s[k + i]
        s.append(bit)  # @line L3
    return s[:count]


def mseq(exps: list[int], state: list[int] | None = None) -> list[int]:
    """One period (2^n - 1 terms) of the sequence of f, from the start state 1, 0, ..., 0 by default."""
    n = max(exps)
    if state is None:
        state = [1] + [0] * (n - 1)
    return lfsr_bits(exps, state, (1 << n) - 1)


def period(exps: list[int], state: list[int] | None = None) -> int:
    """The least period of the recurrence of f from a start state, found by running the state machine."""
    n = max(exps)
    if state is None:
        state = [1] + [0] * (n - 1)
    taps = [i for i in exps if i < n]
    start = tuple(state)
    cur = list(state)
    for p in range(1, 1 << n):
        bit = 0
        for i in taps:
            bit ^= cur[i]
        cur = cur[1:] + [bit]
        if tuple(cur) == start:
            return p
    return 0


def is_primitive(exps: list[int]) -> bool:
    """True if the recurrence of f has period 2^n - 1 from the state 1, 0, ..., 0 (f has constant term 1)."""
    n = max(exps)
    return 0 in exps and period(exps) == (1 << n) - 1


def to_pm(bits: list[int]) -> list[int]:
    """Map 0 to +1 and 1 to -1."""
    return [1 - 2 * b for b in bits]  # @line L4


def periodic_xcorr(a: list[int], b: list[int], shift: int) -> int:
    """sum over k of a[k] b[(k + shift) mod N], for two +1/-1 sequences of length N."""
    n = len(a)
    if len(b) != n:
        raise ValueError("lengths differ")
    return sum(a[k] * b[(k + shift) % n] for k in range(n))  # @line L5


def autocorrelation(a: list[int]) -> list[int]:
    """The periodic autocorrelation of a +1/-1 sequence at every shift 0, ..., N-1."""
    return [periodic_xcorr(a, a, t) for t in range(len(a))]


def runs(bits: list[int]) -> dict[tuple[int, int], int]:
    """Counts of the runs in one period, read cyclically: (bit, length) -> count."""
    n = len(bits)
    if n == 0 or all(b == bits[0] for b in bits):
        return {(bits[0], n): 1} if bits else {}
    start = next(i for i in range(n) if bits[i] != bits[i - 1])
    out: dict[tuple[int, int], int] = {}
    i = 0
    while i < n:
        b = bits[(start + i) % n]
        j = i
        while j < n and bits[(start + j) % n] == b:
            j += 1
        out[(b, j - i)] = out.get((b, j - i), 0) + 1
        i = j
    return out
test_maximal_length_sequence.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-length-sequence/. The authors are listed in prov/09SJJW.jsonl.

import random

from maximal_length_sequence import autocorrelation, is_primitive, lfsr_bits, mseq, period, periodic_xcorr, runs, to_pm

# One primitive polynomial per degree, as exponent lists.
PRIMITIVE = {
    2: [2, 1, 0],
    3: [3, 1, 0],
    4: [4, 1, 0],
    5: [5, 2, 0],
    6: [6, 1, 0],
    7: [7, 1, 0],
    8: [8, 4, 3, 2, 0],
    9: [9, 4, 0],
    10: [10, 3, 0],
}


def test_check_value_degree_three() -> None:
    s = mseq([3, 1, 0], [1, 0, 0])
    assert s == [1, 0, 0, 1, 0, 1, 1]
    assert autocorrelation(to_pm(s)) == [7, -1, -1, -1, -1, -1, -1]


def test_degree_four_sequence() -> None:
    assert "".join(map(str, mseq([4, 1, 0]))) == "100010011010111"


def test_period_balance_and_two_level_autocorrelation() -> None:
    for n, f in PRIMITIVE.items():
        s = mseq(f)
        big = (1 << n) - 1
        assert len(s) == big
        assert period(f) == big
        assert sum(s) == 1 << (n - 1)  # one more 1 than 0
        assert autocorrelation(to_pm(s)) == [big] + [-1] * (big - 1)


def test_run_property() -> None:
    for n in range(3, 11):
        r = runs(mseq(PRIMITIVE[n]))
        assert sum(r.values()) == 1 << (n - 1)
        for length in range(1, n - 1):
            # 2^(n-length-2) runs of each bit value for 1 <= length <= n-2
            assert r.get((0, length), 0) == 1 << (n - length - 2)
            assert r.get((1, length), 0) == 1 << (n - length - 2)
        assert r.get((0, n - 1), 0) == 1 and r.get((1, n), 0) == 1
        assert r.get((1, n - 1), 0) == 0 and r.get((0, n), 0) == 0


def test_every_nonzero_state_is_a_shift() -> None:
    f = PRIMITIVE[5]
    s = mseq(f)
    seen = set()
    for code in range(1, 32):
        state = [(code >> i) & 1 for i in range(5)]
        t = mseq(f, state)
        shifts = [d for d in range(31) if all(t[k] == s[(k + d) % 31] for k in range(31))]
        assert len(shifts) == 1
        seen.add(shifts[0])
    assert seen == set(range(31))


def test_shift_and_add() -> None:
    for n in (3, 4, 6):
        s = mseq(PRIMITIVE[n])
        big = len(s)
        for t in range(1, big):
            w = [s[k] ^ s[(k + t) % big] for k in range(big)]
            assert sum(1 for d in range(big) if all(w[k] == s[(k + d) % big] for k in range(big))) == 1


def test_primitive_count_by_brute_force() -> None:
    # phi(2^n - 1) / n primitive polynomials of degree n
    expected = {2: 1, 3: 2, 4: 2, 5: 6, 6: 6, 7: 18, 8: 16}
    for n, want in expected.items():
        count = 0
        for mid in range(1 << (n - 1)):
            exps = [n] + [i for i in range(1, n) if (mid >> (i - 1)) & 1] + [0]
            count += is_primitive(exps)
        assert count == want


def test_non_primitive_polynomials() -> None:
    assert period([4, 2, 0]) == 6  # (x^2 + x + 1)^2
    assert period([4, 3, 2, 1, 0]) == 5  # irreducible but not primitive
    assert not is_primitive([4, 3, 2, 1, 0])


def test_xcorr_against_direct_sum() -> None:
    rng = random.Random(7)
    a = [rng.choice((1, -1)) for _ in range(20)]
    b = [rng.choice((1, -1)) for _ in range(20)]
    for t in range(20):
        assert periodic_xcorr(a, b, t) == sum(a[k] * b[(k + t) % 20] for k in range(20))


def test_lfsr_continues_periodically() -> None:
    s = lfsr_bits([5, 2, 0], [1, 0, 0, 0, 0], 93)
    assert s[31:62] == s[:31] and s[62:93] == s[:31]

References

  1. Solomon W. Golomb, Shift Register Sequences, third revised edition, World Scientific, 2017 (first edition Holden-Day, 1967), The chapters on linear shift register sequences (the period of the recurrence of a primitive polynomial) and on the randomness postulates (balance, the run property and the two-level autocorrelation)
  2. Dilip V. Sarwate and Michael B. Pursley, Crosscorrelation properties of pseudorandom and related sequences, Proceedings of the IEEE 68(5), 1980, pp. 593 to 619 (the sections on m-sequences, their periodic autocorrelation and the shift-and-add property)
  3. Raymond L. Pickholtz, Donald L. Schilling and Laurence B. Milstein, Theory of spread-spectrum communications, a tutorial, IEEE Transactions on Communications 30(5), 1982, pp. 855 to 884 (the section on pseudonoise generators and the properties of maximal-length sequences)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/09SJJW/text.yaml