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 cells can hold nonzero states, and with a primitive polynomial it goes through all of them before it repeats, so the output has the longest possible period . 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 form is at shift and 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 consecutive bits, so it is pseudorandom in the sense of correlation, not in the sense of cryptography.
Definition
Let be a polynomial over GF(2), with . A binary sequence satisfies the linear recurrence of if
The start state fixes the whole sequence. The sequence is periodic, because the state can take at most values and the map from one state to the next is invertible (the constant term lets us recover from the next state). The zero state gives the zero sequence, so a nonzero start gives a period of at most .
A maximal-length sequence of degree is a nonzero sequence that satisfies the recurrence of some of degree and has period exactly . This happens if and only if is a primitive polynomial: is irreducible and its roots have multiplicative order in GF() (Golomb, the chapter on linear shift register sequences). Then every nonzero start state gives an m-sequence, and the nonzero start states give the cyclic shifts of one sequence.
The form maps bit to and bit to : . The periodic correlation of two sequences and of period at shift is
and the periodic autocorrelation is . The mapping turns XOR into a product: .
The procedure below generates one period and its autocorrelation. It uses word operations per output bit, or if the taps are packed into one machine word, so one period costs in the word RAM model in this plain form, and the full autocorrelation costs by direct sums.
M-SEQUENCE(f, state) ▷ f primitive of degree n, state ≠ 0, N = 2^n - 1- 1
s[0 .. n-1] ← state for k ← 0 to N - n - 1 do- 2
b ← XOR of s[k + i] over the exponents i < n of f - 3
s[k + n] ← b - 4
a[k] ← 1 - 2 s[k] for k = 0, ..., N - 1 ▷ the ±1 form - 5
C(t) ← Σ_k a[k] a[(k + t) mod N] for t = 0, ..., N - 1 return s, C
Properties. Let be an m-sequence of degree and period . Golomb lists the first three as his randomness postulates, and m-sequences satisfy all of them:
- Balance. One period holds ones and zeros. In form, .
- Runs. A run is a maximal block of equal bits, read cyclically. One period has runs. For there are runs of ones and runs of zeros of length . There is one run of zeros and one run of ones.
- Two-level autocorrelation. and for .
- Window property. Each nonzero -tuple appears exactly once as a window in one period. The zero -tuple never appears.
- Shift and add. For , the sum is again a shift of the same sequence, for some that depends on .
Property 3 follows from properties 5 and 1. For , , so , which is the number of zeros minus the number of ones in a period: . Property 5 holds because the sum of two solutions of a linear recurrence is a solution, its start state is nonzero when (by property 4), and every nonzero solution is a shift of .
Two consequences follow. The DFT of one period of has and for , since the DFT of the autocorrelation 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 shifts of one period together with the zero word are the codewords of the simplex code of length and dimension , the dual of the Hamming code; every nonzero codeword has weight . The number of distinct m-sequences of degree , up to shifts, equals the number of primitive polynomials of degree , which is with Euler's function .
Examples and non-examples
Degree 3. Take , so the recurrence is . From the state :
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 1 | 0 | 1 | 1 | |
| window | 100 | 001 | 010 | 101 | 011 | 111 | 110 |
| -1 | +1 | +1 | -1 | +1 | -1 | -1 |
Then , , and the sequence repeats with period . The windows list all seven nonzero triples once. There are four ones and three zeros. The periodic autocorrelation at shifts to is . At shift , for example, the products are , with sum . Shift and add: for is , which is , the sequence shifted by .
Degree 4. from the state gives , of period , with eight ones and seven zeros. Its runs are two runs of length of each bit, one run of length of each bit, one run of three zeros and one run of four ones, as property 2 says. The autocorrelation is at shift and at the other shifts.
Degree 5. from gives the period of length . Degree 5 has primitive polynomials, so there are six different m-sequences of period 31. Two of them, from and , form the preferred pair behind the Gold sequences of period 31.
Non-example: a reducible polynomial. gives period from the state , not . The register splits its nonzero states into several shorter cycles.
Non-example: irreducible but not primitive. is irreducible over GF(2), but its roots are fifth roots of unity, so the period is from every nonzero state. Irreducibility is not enough.
Non-example: a random sequence. A sequence of fair coin flips has a periodic autocorrelation whose off-peak values spread around with a standard deviation near . Small values like at every shift are what make the m-sequence useful for code acquisition: a correlator sees a peak of against a floor of exactly .
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 at shifts to is , with a peak sidelobe of , while the Barker code of length 7 has sidelobes of magnitude at most .
Related definitions
- 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 holds every -tuple once, including the zero tuple. Inserting one extra zero into the run of zeros of an m-sequence gives a de Bruijn sequence of length .
- 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 sequence of odd length , every correlation value is odd, so 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 , 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 09SJJW Edit this page History Report an error Markdown