Skip to content

Sequence

rpps.sequence

The sequence resource: bit and chip sequences, config/sequence//.json

One engine for every operator that uses a known sequence: a scrambler XORs one in (rp.code.scram), a spreader multiplies by one (rp.symbol.Spread), a phase scrambler turns symbols by one (rp.symbol.PhaseScramble), a code-phase search looks for one (rp.sync.acquire_code).

rp.sequence.load("lte_gold", c_init=77).bits(100)       a Recurrence: 0/1 bits from any position
rp.sequence.load("gps_ca", prn=1).chips                 a Code: (count, length) of +/-1

A config/sequence//.json is one of:

{"type": "recurrence", "sequences": [...], "skip": 1600}      see rpps.sequence.recurrence
{"type": "chips" | "set" | "gold", ...}                       see rpps.sequence.code
{"type": "word", "word": "0x1ACFFC1D", "bits": 32}          a fixed word (sync marker, access address): rpps.sequence.word
{"type": "zc", "root": 25, "length": 63, "shift": 0}       a Zadoff-Chu sequence: `.symbols` (complex)

Complex sequences are computed: rp.sequence.zadoff_chu(u, N, shift) (rpps.sequence.zc), the CAZAC roots of LTE and NR (PSS, PRACH, SRS, uplink DM-RS); a "zc" definition names one, as a preamble a profile's sync frame step finds. Any value can be a load-time parameter ("params", then {"param": ...} / {"expr": ...}). Chip rates are in "rate" (chips/s).

Modules:

Name Description
code

Chip codes: a set of M chip sequences of N chips each, as +/-1 floats (spreading codes)

lfsr
recurrence

Binary sequences defined the way standards define them: a linear recurrence or a shift register, optionally XOR'd

word

A fixed bit word (a sync marker, an access address, a start-of-frame delimiter), as a sequence definition

zc

Zadoff-Chu sequences: constant amplitude, zero periodic autocorrelation (CAZAC)

Functions:

Name Description
ls

The sequences there are: {type folder: [names]}

init

A sequence from a definition object

load

Load a sequence by name: load("barker11"), load("gps_ca", prn=1). params: values of its "params"

ls

ls()

The sequences there are: {type folder: [names]}

Source code in src/rpps/sequence/__init__.py
def ls():
    """The sequences there are: {type folder: [names]}"""
    return _config.ls("sequence")

init

init(name, obj)

A sequence from a definition object

Source code in src/rpps/sequence/__init__.py
def init(name, obj):
    """A sequence from a definition object"""
    return _config.load_obj("sequence", name, obj)

load

load(name, **params)

Load a sequence by name: load("barker11"), load("gps_ca", prn=1). params: values of its "params"

Source code in src/rpps/sequence/__init__.py
def load(name, **params):
    """Load a sequence by name: `load("barker11")`, `load("gps_ca", prn=1)`. params: values of its "params" """
    return _config.load("sequence", name, params=params)

code

Chip codes: a set of M chip sequences of N chips each, as +/-1 floats (spreading codes)

chips {"base": "sequence", "type": "chips", "chips": [1, -1, ...]} one sequence, written out (Barker) {..., "bits": "10110111000", "one": -1} or as bits; one is the chip a 1 bit becomes (default -1: 0 -> +1) set {"base": "sequence", "type": "set", "sequences": ["1101...", ...], "one": 1} one per symbol value (802.15.4) gold {"base": "sequence", "type": "gold", "length": 1023, "sequences": [component, component], ...} register sequences XOR'd (GPS C/A); a component is the recurrence of rpps.sequence.recurrence ({"length": 10, "taps": [0, 7], "init": 1023}). "select": the component whose output is read at a delay chosen by a parameter, so one definition covers every code of the family: {"component": 1, "stages": {"param": "prn"}, "table": {"1": [2, 6], ...}} XORs the register stages the table lists for that value (stage k, 1 = first, is the output k-1 chips ahead of the last stage, which is the output itself). Any of them may carry "rate": the chip rate in chips/s, and "period": chips per code period (default the length).

Classes:

Name Description
Code

A set of spreading sequences. chips is (count, length) of +/-1; rate the chip rate in chips/s if the definition gives one

Code

Code(name, chips, rate=None)

A set of spreading sequences. chips is (count, length) of +/-1; rate the chip rate in chips/s if the definition gives one

Methods:

Name Description
bits

The chips as 0/1 (one: the chip value that is a 1)

spread

Each symbol times the sequence: (n,) -> (n*length,). index: which sequence (an int, or one per symbol for a set)

despread

Correlate each length-N block with the sequence, normalised by N: (n*length,) -> (n,)

autocorrelation

Periodic autocorrelation of a sequence (integer lags 0..length-1)

crosscorrelation

Periodic cross-correlation of sequences a and b

Attributes:

Name Type Description
count

Sequences in the set (1 for a single code)

length

Chips per sequence

Source code in src/rpps/sequence/code.py
def __init__(self, name, chips, rate=None):
    chips = np.atleast_2d(np.asarray(chips, dtype=np.float64))
    if chips.ndim != 2 or chips.shape[1] == 0 or not np.all(np.abs(chips) == 1):
        raise ValueError("chips must be rows of +1/-1")
    self.name = name
    self.chips = chips
    self.rate = None if rate is None else float(rate)
count property
count

Sequences in the set (1 for a single code)

length property
length

Chips per sequence

bits
bits(one=-1)

The chips as 0/1 (one: the chip value that is a 1)

Source code in src/rpps/sequence/code.py
def bits(self, one=-1):
    """The chips as 0/1 (`one`: the chip value that is a 1)"""
    return (self.chips == one).astype(np.uint8)
spread
spread(symbols, index=0)

Each symbol times the sequence: (n,) -> (n*length,). index: which sequence (an int, or one per symbol for a set)

Source code in src/rpps/sequence/code.py
def spread(self, symbols, index=0):
    """Each symbol times the sequence: (n,) -> (n*length,). index: which sequence (an int, or one per symbol for a set)"""
    symbols = np.asarray(symbols)
    idx = np.broadcast_to(np.asarray(index, dtype=int), symbols.shape)
    return (symbols[:, None] * self.chips[idx]).reshape(-1)
despread
despread(chips, index=0)

Correlate each length-N block with the sequence, normalised by N: (n*length,) -> (n,)

Source code in src/rpps/sequence/code.py
def despread(self, chips, index=0):
    """Correlate each length-N block with the sequence, normalised by N: (n*length,) -> (n,)"""
    x = np.asarray(chips).reshape(-1, self.length)
    return x @ self.chips[index] / self.length
autocorrelation
autocorrelation(index=0)

Periodic autocorrelation of a sequence (integer lags 0..length-1)

Source code in src/rpps/sequence/code.py
def autocorrelation(self, index=0):
    """Periodic autocorrelation of a sequence (integer lags 0..length-1)"""
    c = self.chips[index]
    f = np.fft.fft(c)
    return np.rint(np.fft.ifft(f * np.conj(f)).real).astype(int)
crosscorrelation
crosscorrelation(a, b)

Periodic cross-correlation of sequences a and b

Source code in src/rpps/sequence/code.py
def crosscorrelation(self, a, b):
    """Periodic cross-correlation of sequences a and b"""
    fa, fb = np.fft.fft(self.chips[a]), np.fft.fft(self.chips[b])
    return np.rint(np.fft.ifft(fa * np.conj(fb)).real).astype(int)

lfsr

Classes:

Name Description
LFSR

LFSR

LFSR(seed)

Methods:

Name Description
clone

Independent copy, in its current state

fresh

Independent copy, at the seed

advance

One step of a self-synchronizing (feedthrough) scrambler: bit in, the scrambled or descrambled bit out

Source code in src/rpps/sequence/lfsr.py
7
8
9
def __init__(self, seed):
    self._seed = np.array(seed, copy=True)
    self.lfsr = np.array(seed, copy=True)
clone
clone()

Independent copy, in its current state

Source code in src/rpps/sequence/lfsr.py
def clone(self):
    """Independent copy, in its current state"""
    return copy.deepcopy(self)
fresh
fresh()

Independent copy, at the seed

Source code in src/rpps/sequence/lfsr.py
def fresh(self):
    """Independent copy, at the seed"""
    c = self.clone()
    c.reset()
    return c
advance
advance(bit, descramble=False)

One step of a self-synchronizing (feedthrough) scrambler: bit in, the scrambled or descrambled bit out

The register holds what went through the scrambler, not a free-running keystream: the scrambler feeds its own output back (y[n] = d[n] ^ taps of the past y), the descrambler the bits it receives (d[n] = y[n] ^ the same taps of the past y). Joined mid-stream a descrambler is right after one register length of bits

Source code in src/rpps/sequence/lfsr.py
def advance(self, bit, descramble=False):
    """One step of a self-synchronizing (feedthrough) scrambler: `bit` in, the scrambled or descrambled bit out

    The register holds what went through the scrambler, not a free-running keystream: the scrambler feeds its own output
    back (y[n] = d[n] ^ taps of the past y), the descrambler the bits it receives (d[n] = y[n] ^ the same taps of the past y).
    Joined mid-stream a descrambler is right after one register length of bits"""
    raise NotImplementedError()

recurrence

Binary sequences defined the way standards define them: a linear recurrence or a shift register, optionally XOR'd with a second one (a Gold sequence), from a seed that is often a load-time parameter

{"base": "sequence", "type": "recurrence",
 "sequences": [component, ...],     XOR'd together (two for a Gold sequence)
 "skip": 1600}                      outputs dropped before the first one used (LTE's Nc)

A component is a recurrence s[t+L] = XOR of s[t+j] over taps, output s[t]: {"length": 31, "taps": [0, 3], "init": 1, "init_order": "lsb"} init: the first L outputs, as an integer (lsb: bit i is s[i]; msb: bit L-1-i is s[i]) or a list of bits or a register as drawn (Galois form, as Bluetooth draws its whitening LFSR): {"register": "galois", "length": 7, "taps": [4], "state": [1, 0, 1, 0, 0, 1, 1]} positions 0..L-1; each step outputs position L-1, shifts toward it, feeds the output into position 0 and XORs it into each tap position

Taps here are positions, from 0. A feedthrough scrambler's "poly" (rpps.code.scram) is the polynomial's exponents instead, from 1, the way the standards write it (1 + x^14 + x^17 is [14, 17]): two things, two keys.

Classes:

Name Description
Recurrence

A binary sequence: its components XOR'd, skip outputs dropped first. bits(n, start) are its bits from position

Recurrence

Recurrence(name, components, skip=0)

A binary sequence: its components XOR'd, skip outputs dropped first. bits(n, start) are its bits from position start (0 = the first after skip); the sequence runs on as far as it is asked

Methods:

Name Description
bits

n bits from position start, as 0/1

Source code in src/rpps/sequence/recurrence.py
def __init__(self, name, components, skip=0):
    self.name = name
    self.components = [_component(c) for c in components]
    if not self.components:
        raise ValueError(f"{name}: a sequence needs at least one component")
    self.skip = int(skip)
bits
bits(n, start=0)

n bits from position start, as 0/1

Source code in src/rpps/sequence/recurrence.py
def bits(self, n, start=0):
    """n bits from position `start`, as 0/1"""
    out = np.zeros(start + n, dtype=np.uint8)
    for c in self.components:
        out ^= c.first(self.skip + start + n)[self.skip:]
    return out[start:]

word

A fixed bit word (a sync marker, an access address, a start-of-frame delimiter), as a sequence definition

{"base": "sequence", "type": "word", "word": "0x1ACFFC1D", "bits": 32, "order": "msb"}

bits is the word in the order it is sent: most significant bit first ("msb", the default) or least ("lsb", Bluetooth). A delimiter search (rp.sync.Delimiter) and a marker (rp.code.Marker) name one, so the two agree.

Classes:

Name Description
Word

A known bit word. bits: the bits as sent (bool array); value, n, order as defined

Functions:

Name Description
word_bits

The bits of a word in transmission order: from an int (or hex string) of bits bits, or from a list/array of bits as given

Word

Word(name, word, bits=None, order='msb')

A known bit word. bits: the bits as sent (bool array); value, n, order as defined

Source code in src/rpps/sequence/word.py
def __init__(self, name, word, bits=None, order="msb"):
    if order not in ("msb", "lsb"):
        raise ConfigError(f"word {name}: order is msb or lsb, not {order!r}")
    self.name, self.order = name, order
    self.bits = word_bits(word, bits, order)
    self.n = len(self.bits)
    msb = self.bits[::-1] if order == "lsb" else self.bits
    self.value = int("".join("1" if b else "0" for b in msb), 2) if self.n else 0 # (a Python int: any width)

word_bits

word_bits(word, bits=None, order='msb')

The bits of a word in transmission order: from an int (or hex string) of bits bits, or from a list/array of bits as given

Source code in src/rpps/sequence/word.py
def word_bits(word, bits=None, order="msb"):
    """The bits of a word in transmission order: from an int (or hex string) of `bits` bits, or from a list/array of bits as given"""
    if isinstance(word, (list, tuple, np.ndarray)):
        return np.asarray(word).astype(bool)
    v = int(word, 0) if isinstance(word, str) else int(word)
    if bits is None:
        raise ConfigError("a word given as a number needs its width, `bits`")
    n = int(bits)
    if v < 0 or v >> n:
        raise ConfigError(f"word {v:#x} is wider than {n} bits")
    msb = np.unpackbits(np.frombuffer(v.to_bytes((n + 7)//8, "big"), np.uint8))[-n:] if n else np.zeros(0, np.uint8) # (any width)
    return (msb[::-1] if order == "lsb" else msb).astype(bool)

zc

Zadoff-Chu sequences: constant amplitude, zero periodic autocorrelation (CAZAC)

rp.sequence.zadoff_chu(25, 63)          root 25 of length 63 (LTE's PSS punctures its middle element)
rp.sequence.zadoff_chu(129, 839, 13)    a PRACH root, cyclically shifted by 13

x_u[n] = exp(-j pi u n (n + N mod 2) / N), u coprime to N. Every element has magnitude 1 and the periodic autocorrelation is zero at every lag but 0, so a received period correlated with the root gives one peak (the channel) and noise alone at every other lag: rp.sync.quality.from_sequence reads the SNR from that. Two roots of a prime length cross-correlate at 1/sqrt(N) at every lag.

As a definition (a preamble a profile's sync frame step names): {"base": "sequence", "type": "zc", "root": 25, "length": 63, "shift": 0}; loaded, .symbols is the sequence and .fields its root and shift.

Classes:

Name Description
ZadoffChu

A Zadoff-Chu sequence definition: symbols (complex, unit magnitude), fields ({"root", "shift"})

Functions:

Name Description
zadoff_chu

Root u of length N (u coprime to N, 0 < u < N), cyclically advanced by shift: x[(n + shift) mod N]

ZadoffChu

ZadoffChu(name, root, length, shift=0)

A Zadoff-Chu sequence definition: symbols (complex, unit magnitude), fields ({"root", "shift"})

Source code in src/rpps/sequence/zc.py
def __init__(self, name, root, length, shift=0):
    self.name, self.root, self.length, self.shift = name, int(root), int(length), int(shift)
    self.symbols = zadoff_chu(self.root, self.length, self.shift)
    self.fields = {"root": self.root, "shift": self.shift}

zadoff_chu

zadoff_chu(u, N, shift=0)

Root u of length N (u coprime to N, 0 < u < N), cyclically advanced by shift: x[(n + shift) mod N]

Source code in src/rpps/sequence/zc.py
def zadoff_chu(u, N, shift=0):
    """Root u of length N (u coprime to N, 0 < u < N), cyclically advanced by `shift`: x[(n + shift) mod N]"""
    u, N = int(u), int(N)
    if N < 1 or not 0 < u < N or gcd(u, N) != 1:
        raise ValueError(f"Zadoff-Chu root {u} of length {N}: the root must be in 1..N-1 and coprime to N")
    n = (np.arange(N) + int(shift)) % N
    return np.exp(-1j*np.pi*u*n*(n + N % 2)/N)