Skip to content

Grid

rpps.grid

Resource grids of OFDM systems: cell search, the grid of each subframe with its channel estimates, and the physical channels read off it

grid steps in a profile take an OFDM system's samples to frames of its resource grid, and its physical channels read them, a branch each (rpps.profile.branch). Formula mappings are code here; tables and sequences are definitions.

  • lte (FDD and TDD): LteCell (PSS/SSS cell search; search lists the cells on a carrier), LteGrid (a frame per subframe, with each port's channel), PBCH (ports, MIB), PCFICH (CFI), PDCCH (DCI 1A, 1C), PDSCH (SIB1, SI), and tx. The profile is lte/downlink.
  • nr (FR1, 15 and 30 kHz): NrCell (PSS over a LEO pass's offsets, each SS/PBCH block tracked), NrGrid (a frame per subframe), PBCH, PDCCH (CORESET 0), PDSCH (LDPC, SIB1), and tx (with leo). Not every cell applies the per-symbol phase of 38.211 5.4: with fc the PDSCH tries both. The profile is nr/downlink.

rpps.grid.lte

LTE downlink (FDD and TDD): cell search, the resource grid with its channel estimates, and the physical channels to SIB1

Modules:

Name Description
cell

LTE cell search and frame timing (3GPP TS 36.211 6.11): a stream of samples to a stream of whole half-frames

channels

LTE downlink physical channels read off LteGrid's frames: PBCH (MIB), PCFICH (CFI), PDCCH (DCI), PDSCH (transport blocks)

grid

The LTE resource grid of each subframe, with every port's channel on every resource element

phy

LTE downlink physical layer: numerology, reference signals, resource-element maps, transmit diversity (3GPP TS 36.211)

tx

An LTE downlink to test the receive side with: cell signals, MIB, CFI, a DCI 1A to the SI-RNTI and its PDSCH

cell

LTE cell search and frame timing (3GPP TS 36.211 6.11): a stream of samples to a stream of whole half-frames

Every 5 ms two symbols carry the synchronization signals on the 62 central subcarriers: the primary (PSS: a Zadoff-Chu root that names N_ID2 = 0..2) and the secondary (SSS: two m-sequences that name N_ID1 = 0..167 and which half-frame it is). The cell is 3 N_ID1 + N_ID2. Where the two are says the duplex mode: FDD has the PSS in the last symbol of slot 0 of subframes 0 and 5 and the SSS the symbol before; TDD the PSS in symbol 2 of subframes 1 and 6 and the SSS in the last symbol of the subframes before. Normal cyclic prefix.

Acquiring (on the first acquire seconds): the PSS at 1.92 MS/s over a grid of carrier offsets (offset +- span), its correlation folded on 5 ms; then each PSS at the full rate, the fractional offset from the cyclic prefix, and the SSS of each, which votes on N_ID1 and the duplex mode and labels the half-frames. A cell found has its synchronization signals subtracted from the samples and the search runs again about its carrier offset, so weaker cells on the same carrier are found too (search lists them; pci says which one to receive, else the strongest). Two cells of one N_ID2 with the same frame timing share their PSS, and the weaker is then seldom told apart. Tracking: each half-frame's PSS is found again near where the last one put it (an alpha-beta loop on its position: the sample clock drifts) and the cyclic prefix trims the offset.

Out come the samples from the first subframe 0 on, carrier offset taken off, cut into half-frames of exactly 5 ms at the nominal rate (a sample dropped or repeated between them as the clock drifts), so the grid after it sees subframes at fixed places: subframe n of the output is subframe n mod 10 of a radio frame. When the PSS is lost for lose half-frames it is acquired again, and zeros stand in for the half-frames missed, so that still holds. The cell goes in the stream's est["cell"].

Classes:

Name Description
LteCell

LTE cell search and half-frame timing (see the module)

Functions:

Name Description
pss

The PSS of root u: Zadoff-Chu of length 63 without its middle element (it would sit on DC)

sss

The 62 SSS values in subframe 0 (half 0) or 5 (half 1)

sss_table

(336, 62): every (N_ID1, half) hypothesis, N_ID1 major

search

The cells on a carrier, strongest first, from the start of x

LteCell

LteCell(offset=0.0, span=50000.0, resolution=5000.0, acquire=0.04, lose=20, gate=0.2, pci=-1, duplex='auto', name='cell')

Bases: Stage

LTE cell search and half-frame timing (see the module)

offset: where the carrier is expected [Hz from the centre]; span, resolution: the offsets searched around it [Hz] acquire: seconds of samples the acquisition looks at; lose: half-frames without a PSS before acquiring again gate: the PSS's normalized correlation below which a half-frame has none pci: the cell to receive (-1: the strongest); duplex: "fdd", "tdd" or "auto" (the SSS says)

Source code in src/rpps/grid/lte/cell.py
def __init__(self, offset=0.0, span=50e3, resolution=5e3, acquire=0.04, lose=20, gate=0.2, pci=-1, duplex="auto",
             name="cell"):
    if duplex not in ("auto", "fdd", "tdd"):
        raise ValueError(f"LteCell: duplex {duplex!r} (auto, fdd, tdd)")
    self.offset, self.span, self.resolution = float(offset), float(span), float(resolution)
    self.acquire, self.lose, self.gate, self.name = float(acquire), int(lose), float(gate), name
    self.pci, self.duplex = int(pci), duplex

pss

pss(u)

The PSS of root u: Zadoff-Chu of length 63 without its middle element (it would sit on DC)

Source code in src/rpps/grid/lte/cell.py
def pss(u):
    """The PSS of root u: Zadoff-Chu of length 63 without its middle element (it would sit on DC)"""
    return np.delete(zadoff_chu(u, 63), 31)

sss

sss(n_id1, n_id2, half)

The 62 SSS values in subframe 0 (half 0) or 5 (half 1)

Source code in src/rpps/grid/lte/cell.py
def sss(n_id1, n_id2, half):
    """The 62 SSS values in subframe 0 (half 0) or 5 (half 1)"""
    qp = n_id1//30
    q = (n_id1 + qp*(qp + 1)//2)//30
    mp = n_id1 + q*(q + 1)//2
    m0 = mp % 31
    m1 = (m0 + mp//31 + 1) % 31
    n = np.arange(31)
    s0, s1 = S_T[(n + m0) % 31], S_T[(n + m1) % 31]
    c0, c1 = C_T[(n + n_id2) % 31], C_T[(n + n_id2 + 3) % 31]
    z0, z1 = Z_T[(n + m0 % 8) % 31], Z_T[(n + m1 % 8) % 31]
    d = np.empty(62)
    if half == 0:
        d[0::2], d[1::2] = s0*c0, s1*c1*z0
    else:
        d[0::2], d[1::2] = s1*c0, s0*c1*z1
    return d

sss_table

sss_table(n_id2)

(336, 62): every (N_ID1, half) hypothesis, N_ID1 major

Source code in src/rpps/grid/lte/cell.py
def sss_table(n_id2):
    """(336, 62): every (N_ID1, half) hypothesis, N_ID1 major"""
    if n_id2 not in _SSS:
        _SSS[n_id2] = np.array([sss(n1, n_id2, h) for n1 in range(168) for h in (0, 1)])
    return _SSS[n_id2]

search

search(x, fs, offset=0.0, span=50000.0, resolution=5000.0, duplex='auto', acquire=0.04, max_cells=8, gate=0.2)

The cells on a carrier, strongest first, from the start of x

A list of dicts: pci, duplex ("fdd" or "tdd"), offset [Hz from the centre], start (the first sample of a subframe 0), sss (the mean SSS correlation, 1: clean), level_db (the synchronization signals' power against the strongest's). offset, span, resolution: the carrier offsets searched; acquire: seconds looked at; gate: the strongest cell's PSS correlation at least

Source code in src/rpps/grid/lte/cell.py
def search(x, fs, offset=0.0, span=50e3, resolution=5e3, duplex="auto", acquire=0.04, max_cells=8, gate=0.2):
    """The cells on a carrier, strongest first, from the start of x

    A list of dicts: pci, duplex ("fdd" or "tdd"), offset [Hz from the centre], start (the first sample of a subframe 0),
    sss (the mean SSS correlation, 1: clean), level_db (the synchronization signals' power against the strongest's).
    offset, span, resolution: the carrier offsets searched; acquire: seconds looked at; gate: the strongest cell's PSS
    correlation at least"""
    fs = float(fs)
    nfft = _nfft(fs)
    x = np.asarray(x[:int(acquire*fs)], complex)
    out = []
    for lk in _cells(x, fs, nfft, float(offset), float(span), float(resolution), duplex, gate, int(max_cells)):
        out.append({"pci": lk.pci, "duplex": lk.duplex, "offset": float(lk.f), "start": int(round(lk.start)), "sss": lk.sss,
                    "power": lk.power})
    top = max((c["power"] for c in out), default=1.0) or 1.0
    for c in out:
        c["level_db"] = float(10*np.log10(max(c.pop("power"), 1e-30)/top))
    return out

channels

LTE downlink physical channels read off LteGrid's frames: PBCH (MIB), PCFICH (CFI), PDCCH (DCI), PDSCH (transport blocks)

Each reads whole subframe frames (rpps.grid.lte.grid: a partial frame waits for the rest) and gives bits. Each publishes what it decoded from the first item of its subframe (rpps.base.control.publish), so a profile's controls carry it to the channels after it: the MIB's port count to every channel, the CFI to the PDCCH and PDSCH of its subframe, a DCI's allocation to the PDSCH of its subframe (3GPP TS 36.211, 36.212, 36.213). Coding is rpps's: the LTE Gold sequence, tail-biting convolutional code with its rate matching, turbo code with its rate matching, CRC-16 and CRC-24A.

PBCH   subframe 0: 1, 2 or 4 ports and the frame's quarter of the 40 ms scrambling are tried, the CRC mask says which:
       gives the 24 MIB bits; publishes ports, n_rb, phich_ng, phich_duration, sfn
PCFICH every subframe, once `ports` is known: gives the CFI (2 bits); publishes cfi (for its subframe)
PDCCH  once ports, cfi and the PHICH's size and duration are known: the common search space (CCEs 0-15, aggregation 4
       and 8) for the `rntis`, formats 1A and 1C: gives each DCI's bits; publishes the first's fields (for its
       subframe). TDD: the PHICH's size also depends on the uplink-downlink configuration, which SIB1 gives, so
       m_i = 1, 0 and 2 are tried until a DCI checks, the one a subframe number last took first
PDSCH  where a DCI gave an allocation (riv not None): localized or distributed, one code block; a 1C has no
       redundancy version, so the four are tried; gives the transport block when its CRC-24A checks. TDD subframe 1
       (special: DwPTS) is not covered (est "special")

Every message names its subframe: subframe, counted from the first the grid gave.

Classes:

Name Description
PBCH

The MIB of every subframe 0 (see the module)

PCFICH

The CFI of every subframe, once the port count is known (see the module)

PDCCH

DCIs in the common search space for the RNTIs given (see the module)

PDSCH

The transport block a DCI allocated in its subframe (see the module)

Functions:

Name Description
tail_biting

K bits (CRC included) from soft bits of the 1/3 tail-biting code, rate matched to len(llr) (positive = 0)

tail_biting_batch

tail_biting of each of llrs (soft bits of any lengths): (len(llrs), K) bits, the Viterbi of a length in one batch

PBCH

PBCH(name='pbch')

Bases: _Channel

The MIB of every subframe 0 (see the module)

Source code in src/rpps/grid/lte/channels.py
def __init__(self, name="pbch"):
    super().__init__(name)

PCFICH

PCFICH(ports=None, name='pcfich')

Bases: _Channel

The CFI of every subframe, once the port count is known (see the module)

Methods:

Name Description
read

The CFI of one grid frame: the code word nearest what the PCFICH holds

Source code in src/rpps/grid/lte/channels.py
def __init__(self, ports=None, name="pcfich"):
    super().__init__(name, ports=ports)
read
read(head, G, H)

The CFI of one grid frame: the code word nearest what the PCFICH holds

Source code in src/rpps/grid/lte/channels.py
def read(self, head, G, H):
    """The CFI of one grid frame: the code word nearest what the PCFICH holds"""
    pci, sf = head["pci"], head["sf"]
    k, l = phy.pcfich_res(pci, head["n_rb"], self.ports)
    s = phy.soft_bits(phy.undo_diversity(G, H, k, l, self.ports))
    s = s*phy.sign(phy.gold(((sf + 1)*(2*pci + 1) << 9) + pci, 32))
    score = {cfi: float(np.sum(s*phy.sign(w))) for cfi, w in phy.CFI_WORDS.items()}
    return max(score, key=score.get)

PDCCH

PDCCH(rntis=(phy.SI_RNTI,), ports=None, cfi=None, phich_ng=None, phich_duration=0, name='pdcch')

Bases: _Channel

DCIs in the common search space for the RNTIs given (see the module)

Methods:

Name Description
cces

(N_CCE, 72) soft bits of the control region: REGs equalized, the shift and interleaver undone, descrambled

find

(format, RNTI, payload bits) of the DCIs of one grid frame; mi (a dict kept from frame to frame: subframe

search

(format, RNTI, payload bits) of every DCI for the RNTIs in the common search space of CCEs cc

Source code in src/rpps/grid/lte/channels.py
def __init__(self, rntis=(phy.SI_RNTI,), ports=None, cfi=None, phich_ng=None, phich_duration=0, name="pdcch"):
    super().__init__(name, rntis=tuple(int(r) for r in rntis), ports=ports, cfi=cfi, phich_ng=phich_ng,
                     phich_duration=phich_duration)
cces
cces(head, G, H, mi=1)

(N_CCE, 72) soft bits of the control region: REGs equalized, the shift and interleaver undone, descrambled (mi: TDD's PHICH multiplier)

Source code in src/rpps/grid/lte/channels.py
def cces(self, head, G, H, mi=1):
    """(N_CCE, 72) soft bits of the control region: REGs equalized, the shift and interleaver undone, descrambled
    (mi: TDD's PHICH multiplier)"""
    pci, n_rb, sf = head["pci"], head["n_rb"], head["sf"]
    extended = bool(self.phich_duration)
    key = (pci, n_rb, phy.control_symbols(self.cfi, n_rb), phy.phich_groups(self.phich_ng, n_rb, mi), int(self.ports),
           extended, phy.short_phich(head["duplex"], sf))
    M = len(phy.control_regs(*key))
    k, l = phy.control_res(*key)
    wbar = phy.soft_bits(phy.undo_diversity(G, H, k, l, int(self.ports))).reshape(M, 8)
    w = wbar[(np.arange(M) - pci) % M] # Undo the cyclic shift by the cell id
    z = np.zeros_like(w)
    z[np.asarray(phy.subblock_perm(M))] = w # and the quadruplet interleaver
    bits = z.reshape(-1)*phy.sign(phy.gold((sf << 9) + pci, 8*M))
    n = M//9
    return bits[:n*72].reshape(n, 72)
find
find(head, G, H, mi)

(format, RNTI, payload bits) of the DCIs of one grid frame; mi (a dict kept from frame to frame: subframe number -> TDD's m_i) says which PHICH size to try first, and takes the one that checked

Source code in src/rpps/grid/lte/channels.py
def find(self, head, G, H, mi):
    """(format, RNTI, payload bits) of the DCIs of one grid frame; `mi` (a dict kept from frame to frame: subframe
    number -> TDD's m_i) says which PHICH size to try first, and takes the one that checked"""
    sf, duplex = head["sf"], head["duplex"]
    tries = (1,) if duplex == "fdd" else sorted((1, 0, 2), key=lambda m: m != mi.get(sf, 1))
    for m in tries:
        found = self.search(self.cces(head, G, H, m), head["n_rb"], duplex)
        if found:
            if duplex == "tdd":
                mi[sf] = m
            return found
    return []
search
search(cc, n_rb, duplex)

(format, RNTI, payload bits) of every DCI for the RNTIs in the common search space of CCEs cc

Source code in src/rpps/grid/lte/channels.py
def search(self, cc, n_rb, duplex):
    """(format, RNTI, payload bits) of every DCI for the RNTIs in the common search space of CCEs `cc`"""
    sizes = {phy.dci_1a_size(n_rb, duplex): "1A", phy.dci_1c_size(n_rb): "1C"}
    cands = [cc[s0:s0 + L].reshape(-1) for L, starts in ((4, (0, 4, 8, 12)), (8, (0, 8))) for s0 in starts
             if s0 + L <= len(cc)]
    decoded = {K: tail_biting_batch(cands, K + 16) for K in sizes} # (every candidate of a size in one batch)
    found, seen = [], set()
    for i in range(len(cands)):
        for K, fmt in sizes.items():
            b = decoded[K][i]
            rnti = _int(b[K:] ^ crc_bits(b[:K], "crc16_xmodem"))
            key = (rnti, K, b[:K].tobytes())
            if rnti in self.rntis and key not in seen: # (aggregation 8 holds the 4 of the same DCI)
                seen.add(key)
                found.append((fmt, rnti, b[:K]))
    return found

PDSCH

PDSCH(ports=None, cfi=None, name='pdsch')

Bases: _Channel

The transport block a DCI allocated in its subframe (see the module)

Source code in src/rpps/grid/lte/channels.py
def __init__(self, ports=None, cfi=None, name="pdsch"):
    super().__init__(name, ports=ports, cfi=cfi, format="1A", rnti=None, riv=None, mcs=None, rv=0, tpc=0,
                     distributed=0, gap=0, flag=1, harq=0, ndi=0)

tail_biting

tail_biting(llr, K)

K bits (CRC included) from soft bits of the 1/3 tail-biting code, rate matched to len(llr) (positive = 0)

Source code in src/rpps/grid/lte/channels.py
def tail_biting(llr, K):
    """K bits (CRC included) from soft bits of the 1/3 tail-biting code, rate matched to len(llr) (positive = 0)"""
    d = _conv_rm(K, len(llr)).decode(np.asarray(llr, float))
    return np.asarray(_conv().decoder.decode(d)).astype(np.uint8)

tail_biting_batch

tail_biting_batch(llrs, K)

tail_biting of each of llrs (soft bits of any lengths): (len(llrs), K) bits, the Viterbi of a length in one batch

Source code in src/rpps/grid/lte/channels.py
def tail_biting_batch(llrs, K):
    """`tail_biting` of each of llrs (soft bits of any lengths): (len(llrs), K) bits, the Viterbi of a length in one batch"""
    out = np.zeros((len(llrs), K), np.uint8)
    by_len = {}
    for i, llr in enumerate(llrs):
        by_len.setdefault(len(llr), []).append(i)
    for E, rows in by_len.items():
        rm = _conv_rm(K, E)
        d = np.array([rm.decode(np.asarray(llrs[i], float)) for i in rows])
        out[rows] = np.asarray(_conv().decoder.decode_batch(d)).astype(np.uint8)
    return out

grid

The LTE resource grid of each subframe, with every port's channel on every resource element

LteGrid takes what LteCell gives (whole half-frames from a subframe 0, carrier offset off) and gives one frame per subframe: a stream of complex items, frame_len(n_rb) a subframe, laid out as

HEAD items      the subframe's header: cell id, subframe number 0..9, N_RB, subframe count, 1 for TDD
                (as real values)
14 x 12 N_RB    the grid G[l, k]: symbol l, subcarrier k from the lowest (the DC subcarrier left out)
4 x 14 x 12 N_RB  the channel H[p, l, k] of ports 0-3, from the cell-specific reference signals

so the physical channels after it (each a branch of the profile, reading the same frames) take their resource elements and undo the transmit diversity by unpack. The cell comes from LteCell's estimates in the stream.

Classes:

Name Description
LteGrid

Subframes of samples to grid frames (see the module). n_rb: resource blocks (default: those that fill the FFT);

Functions:

Name Description
n_rb_of

N_RB from the frame length

unpack

(header dict, G (14, 12 N_RB), H (4, 14, 12 N_RB)) of one frame: views, no copies

frames

The whole frames of a block: (n, frame_len) view

LteGrid

LteGrid(n_rb=None, cell='cell')

Bases: Stage

Subframes of samples to grid frames (see the module). n_rb: resource blocks (default: those that fill the FFT); cell: the name of LteCell's estimates

Source code in src/rpps/grid/lte/grid.py
def __init__(self, n_rb=None, cell="cell"):
    self.n_rb, self.cell = n_rb, cell

n_rb_of

n_rb_of(frame_items)

N_RB from the frame length

Source code in src/rpps/grid/lte/grid.py
def n_rb_of(frame_items):
    """N_RB from the frame length"""
    n, r = divmod(frame_items - HEAD, 5*14*12)
    if r:
        raise ValueError(f"{frame_items} items is not an LTE grid frame")
    return n

unpack

unpack(frame)

(header dict, G (14, 12 N_RB), H (4, 14, 12 N_RB)) of one frame: views, no copies

Source code in src/rpps/grid/lte/grid.py
def unpack(frame):
    """(header dict, G (14, 12 N_RB), H (4, 14, 12 N_RB)) of one frame: views, no copies"""
    f = np.asarray(frame)
    n_rb = int(round(f[2].real))
    nsc = 12*n_rb
    head = {"pci": int(round(f[0].real)), "sf": int(round(f[1].real)), "n_rb": n_rb, "count": int(round(f[3].real)),
            "duplex": "tdd" if f[4].real > 0.5 else "fdd"}
    G = f[HEAD:HEAD + 14*nsc].reshape(14, nsc)
    H = f[HEAD + 14*nsc:HEAD + 5*14*nsc].reshape(4, 14, nsc)
    return head, G, H

frames

frames(x, n_rb)

The whole frames of a block: (n, frame_len) view

Source code in src/rpps/grid/lte/grid.py
def frames(x, n_rb):
    """The whole frames of a block: (n, frame_len) view"""
    F = frame_len(n_rb)
    x = np.asarray(x)
    return x[:len(x)//F*F].reshape(-1, F)

phy

LTE downlink physical layer: numerology, reference signals, resource-element maps, transmit diversity (3GPP TS 36.211)

FDD and TDD (frame structures 1 and 2), normal cyclic prefix, 15 kHz subcarriers. A subframe (1 ms) is two slots of seven OFDM symbols; the resource grid of a subframe is (14, 12 N_RB): symbol l = 0..13 (slot l // 7), subcarrier k = 0..12 N_RB - 1 from the lowest, the DC subcarrier left out. Sample rates are 1.92 MS/s per FFT of 128: FFT = Fs / 15 kHz.

Maps give resource elements as two arrays (k, l) in the order the standard fills them, so a channel's symbols are G[l, k]. Transmit diversity (6.3.4.3) is undone over those: 1 port as is, 2 ports Alamouti over pairs (SFBC), 4 ports SFBC with frequency-switched pairs (ports 0, 2 then 1, 3).

Functions:

Name Description
cp_lengths

(first symbol's prefix, the others') in samples at this FFT size

symbol_starts

The useful part's first sample of the 14 symbols of a subframe, from the subframe's first sample

sc_bin

FFT bin of subcarrier k = 0..12 N_RB - 1 (the DC bin skipped)

grid

The (14, 12 N_RB) grid of one subframe's samples. Each FFT window starts early samples into the prefix (clear of

ramp

e^(-j 2 pi (start + step k)) for k = 0..n-1 (cycles): a derotation, complex64. Built from two short tables and their

gold

c(0..n-1) of 7.2 (the rpps definition sequence/recurrence/lte_gold); lengths are taken in steps, so a channel's

sign

Bits to the signs a soft bit is multiplied by to descramble it: 0 -> +1, 1 -> -1

crs_values

r(m) for m = 0..2 N_RB - 1, of cell pci, slot ns (0..19), symbol l of the slot (normal prefix)

crs_shift

v of 6.10.1.2, before v_shift = PCI mod 6

crs_mask

(14, 12 N_RB) bool: where the reference signals of ports 0..ports-1 are (no data there)

channel

H (4, 14, 12 N_RB): each port's channel on every resource element of subframe sf's grid G. Least squares at the

undo_diversity

The symbols sent on resource elements (k, l), in that order, for 1, 2 or 4 transmit ports. Each is scaled by the

soft_bits

QPSK (b(2i) on the real part, b(2i+1) on the imaginary, a 0 positive): soft bits, positive = 0

qpskness

-Re(sum z^4) / sum |z|^4: 1 for QPSK on the diagonals, ~0 for noise or the wrong equalizer

pbch_res

(k, l) of the 240 PBCH resource elements of subframe 0: slot 1 symbols 0-3, the 72 central subcarriers, around the

parse_mib

The 24 MIB bits (36.331 6.2.2): dl-Bandwidth 3, phich-Config 3, the SFN's 8 MSBs, then 10 bits of later releases

reg_res

The four resource elements (k, l) of the REG from subcarrier k0

short_phich

TDD subframes 1 and 6: an extended PHICH of two symbols (Table 6.9.3-1)

phich_regs

The PHICH's REGs (k0, l), three a group (6.9.3)

control_regs

The PDCCH's REGs (k0, l)

control_symbols

OFDM symbols of the control region: the CFI, one more at 10 resource blocks or fewer (Table 6.7-1)

phich_groups

PHICH groups

control_res

(k, l) of the PDCCH REGs' resource elements in order (control_regs, each REG's four)

subblock_perm

The 32-column sub-block interleaver's read-out order of n items (36.212 5.1.4.2.1, dummies left out)

dci_1a_size

Format 1A's payload bits (5.3.3.1.3)

parse_1a

DCI 1A's fields, with an SI-, P- or RA-RNTI

riv_decode

(first resource block, count) of a contiguous allocation (36.213 7.1.6.3)

step_1c

N_RB^step of format 1C's allocation (36.213 Table 7.1.6.3-1)

dci_1c_size

Format 1C's payload bits

gaps

(N_gap, N_VRB, interleaving unit) of a gap (Table 6.2.3.2-1)

dvrb_map

(2, N_VRB): each distributed block's physical block, per slot

tbs_table

{I_TBS: [TBS, ...]} of a table/lte definition

allocation

(blocks, TBS) of a DCI, or None

pdsch_res

(k, l) of a PDSCH's elements

cp_lengths

cp_lengths(nfft)

(first symbol's prefix, the others') in samples at this FFT size

Source code in src/rpps/grid/lte/phy.py
def cp_lengths(nfft):
    """(first symbol's prefix, the others') in samples at this FFT size"""
    s = nfft/2048
    return int(round(160*s)), int(round(144*s))

symbol_starts

symbol_starts(nfft)

The useful part's first sample of the 14 symbols of a subframe, from the subframe's first sample

Source code in src/rpps/grid/lte/phy.py
def symbol_starts(nfft):
    """The useful part's first sample of the 14 symbols of a subframe, from the subframe's first sample"""
    cp0, cp = cp_lengths(nfft)
    slot = cp0 + nfft + 6*(cp + nfft)
    out = []
    for ns in (0, 1):
        for l in range(7):
            out.append(ns*slot + (cp0 if l == 0 else cp0 + nfft + (l - 1)*(cp + nfft) + cp))
    return np.array(out)

sc_bin

sc_bin(k, nfft, n_rb)

FFT bin of subcarrier k = 0..12 N_RB - 1 (the DC bin skipped)

Source code in src/rpps/grid/lte/phy.py
def sc_bin(k, nfft, n_rb):
    """FFT bin of subcarrier k = 0..12 N_RB - 1 (the DC bin skipped)"""
    k = np.asarray(k)
    return np.where(k < 6*n_rb, k - 6*n_rb, k - 6*n_rb + 1) % nfft

grid

grid(x, nfft, n_rb, early=None)

The (14, 12 N_RB) grid of one subframe's samples. Each FFT window starts early samples into the prefix (clear of the symbol before, and of a timing that runs late), the phase ramp that leaves taken off

Source code in src/rpps/grid/lte/phy.py
def grid(x, nfft, n_rb, early=None):
    """The (14, 12 N_RB) grid of one subframe's samples. Each FFT window starts `early` samples into the prefix (clear of
    the symbol before, and of a timing that runs late), the phase ramp that leaves taken off"""
    early = nfft//128 if early is None else early
    idx, bins, turn = _grid_plan(int(nfft), int(n_rb), int(early))
    W = np.fft.fft(np.asarray(x)[idx], axis=1)
    return W[:, bins]*turn[None, :]

ramp

ramp(n, start, step)

e^(-j 2 pi (start + step k)) for k = 0..n-1 (cycles): a derotation, complex64. Built from two short tables and their outer product (k = 128 a + b), not n exponentials: the phase is reduced to a cycle in float64 first, so it stays exact over a stream of any length

Source code in src/rpps/grid/lte/phy.py
def ramp(n, start, step):
    """e^(-j 2 pi (start + step k)) for k = 0..n-1 (cycles): a derotation, complex64. Built from two short tables and their
    outer product (k = 128 a + b), not n exponentials: the phase is reduced to a cycle in float64 first, so it stays exact
    over a stream of any length"""
    b = np.arange(128)
    a = np.arange(-(-n//128))
    lo = np.exp(-2j*np.pi*((step*b) % 1.0))
    hi = np.exp(-2j*np.pi*((start + step*128*a) % 1.0))
    return (hi[:, None]*lo[None, :]).reshape(-1)[:n].astype(np.complex64)

gold

gold(c_init, n)

c(0..n-1) of 7.2 (the rpps definition sequence/recurrence/lte_gold); lengths are taken in steps, so a channel's sequence of any length reuses one made before

Source code in src/rpps/grid/lte/phy.py
def gold(c_init, n):
    """c(0..n-1) of 7.2 (the rpps definition sequence/recurrence/lte_gold); lengths are taken in steps, so a channel's
    sequence of any length reuses one made before"""
    m = max(1024, 1 << int(np.ceil(np.log2(max(n, 1)))))
    return _gold(int(c_init), m)[:n]

sign

sign(c)

Bits to the signs a soft bit is multiplied by to descramble it: 0 -> +1, 1 -> -1

Source code in src/rpps/grid/lte/phy.py
def sign(c):
    """Bits to the signs a soft bit is multiplied by to descramble it: 0 -> +1, 1 -> -1"""
    return 1.0 - 2.0*np.asarray(c, float)

crs_values cached

crs_values(pci, ns, l, n_rb)

r(m) for m = 0..2 N_RB - 1, of cell pci, slot ns (0..19), symbol l of the slot (normal prefix)

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=4096)
def crs_values(pci, ns, l, n_rb):
    """r(m) for m = 0..2 N_RB - 1, of cell `pci`, slot ns (0..19), symbol l of the slot (normal prefix)"""
    c = gold((1 << 10)*(7*(ns + 1) + l + 1)*(2*pci + 1) + 2*pci + 1, 4*110)
    r = (sign(c[0::2]) + 1j*sign(c[1::2]))/np.sqrt(2)
    return r[np.arange(2*n_rb) + 110 - n_rb]

crs_shift

crs_shift(port, ns, l)

v of 6.10.1.2, before v_shift = PCI mod 6

Source code in src/rpps/grid/lte/phy.py
def crs_shift(port, ns, l):
    """v of 6.10.1.2, before v_shift = PCI mod 6"""
    if port == 0:
        return 0 if l == 0 else 3
    if port == 1:
        return 3 if l == 0 else 0
    if port == 2:
        return 3*(ns % 2)
    return 3 + 3*(ns % 2)

crs_mask

crs_mask(pci, n_rb, ports)

(14, 12 N_RB) bool: where the reference signals of ports 0..ports-1 are (no data there)

Source code in src/rpps/grid/lte/phy.py
def crs_mask(pci, n_rb, ports):
    """(14, 12 N_RB) bool: where the reference signals of ports 0..ports-1 are (no data there)"""
    m = np.zeros((14, 12*n_rb), bool)
    for p in range(ports):
        for slot in (0, 1):
            for l in CRS_SYMBOLS[p]:
                m[slot*7 + l, (crs_shift(p, slot, l) + pci) % 6::6] = True
    return m

channel

channel(G, pci, n_rb, sf, ports=4)

H (4, 14, 12 N_RB): each port's channel on every resource element of subframe sf's grid G. Least squares at the reference signals, linear in frequency between them (constant past the edges), and a straight line in time through the port's symbols of the subframe (it barely moves in 1 ms). Ports past ports are zeros. Every port and symbol at once: a port's reference signals are a comb of step 6, so each subcarrier's two neighbours are found by arithmetic

Source code in src/rpps/grid/lte/phy.py
def channel(G, pci, n_rb, sf, ports=4):
    """H (4, 14, 12 N_RB): each port's channel on every resource element of subframe sf's grid G. Least squares at the
    reference signals, linear in frequency between them (constant past the edges), and a straight line in time through
    the port's symbols of the subframe (it barely moves in 1 ms). Ports past `ports` are zeros. Every port and symbol at
    once: a port's reference signals are a comb of step 6, so each subcarrier's two neighbours are found by arithmetic"""
    nsc = 12*n_rb
    H = np.zeros((4, 14, nsc), np.complex64)
    plan = _channel_plan(int(pci), int(n_rb), int(sf), int(ports))
    if plan is None:
        return H
    sym, kk, ref, i0, a, r, per_port = plan
    h = G[sym[:, None], kk]/ref # Least squares at each reference signal
    hs = h[r, i0]*(1 - a) + h[r, i0 + 1]*a # (rows, nsc)
    for p, (sel, dt, den, tt) in enumerate(per_port):
        H_p = hs[sel]
        mean = H_p.mean(0)
        slope = np.sum(dt[:, None]*(H_p - mean), axis=0)/den
        H[p] = mean[None, :] + slope[None, :]*tt[:, None]
    return H

undo_diversity

undo_diversity(G, H, k, l, ports)

The symbols sent on resource elements (k, l), in that order, for 1, 2 or 4 transmit ports. Each is scaled by the channel's power (soft bits keep their reliability)

Source code in src/rpps/grid/lte/phy.py
def undo_diversity(G, H, k, l, ports):
    """The symbols sent on resource elements (k, l), in that order, for 1, 2 or 4 transmit ports. Each is scaled by the
    channel's power (soft bits keep their reliability)"""
    r = G[l, k]
    h = H[:, l, k]
    z = np.zeros(len(k), complex)
    if ports == 1:
        return np.conj(h[0])*r
    n = len(k)//2*2
    if ports == 2:
        a, b = r[0:n:2], r[1:n:2]
        ha, hb = (h[0, 0:n:2] + h[0, 1:n:2])/2, (h[1, 0:n:2] + h[1, 1:n:2])/2 # A pair shares one channel
        z[0:n:2] = np.conj(ha)*a + hb*np.conj(b)
        z[1:n:2] = np.conj(ha)*b - hb*np.conj(a)
        return z
    n = len(k)//4*4
    for q, (p1, p2) in ((0, (0, 2)), (2, (1, 3))): # Quartets: the first pair on ports 0 and 2, the second on 1 and 3
        a, b = r[q:n:4], r[q + 1:n:4]
        ha = (h[p1, q:n:4] + h[p1, q + 1:n:4])/2
        hb = (h[p2, q:n:4] + h[p2, q + 1:n:4])/2
        z[q:n:4] = np.conj(ha)*a + hb*np.conj(b)
        z[q + 1:n:4] = np.conj(ha)*b - hb*np.conj(a)
    return z

soft_bits

soft_bits(z)

QPSK (b(2i) on the real part, b(2i+1) on the imaginary, a 0 positive): soft bits, positive = 0

Source code in src/rpps/grid/lte/phy.py
def soft_bits(z):
    """QPSK (b(2i) on the real part, b(2i+1) on the imaginary, a 0 positive): soft bits, positive = 0"""
    s = np.empty(2*len(z))
    s[0::2], s[1::2] = z.real, z.imag
    return s

qpskness

qpskness(z)

-Re(sum z^4) / sum |z|^4: 1 for QPSK on the diagonals, ~0 for noise or the wrong equalizer

Source code in src/rpps/grid/lte/phy.py
def qpskness(z):
    """-Re(sum z^4) / sum |z|^4: 1 for QPSK on the diagonals, ~0 for noise or the wrong equalizer"""
    return float(-np.sum(z**4).real/max(np.sum(np.abs(z)**4), 1e-30))

pbch_res cached

pbch_res(pci, n_rb)

(k, l) of the 240 PBCH resource elements of subframe 0: slot 1 symbols 0-3, the 72 central subcarriers, around the reference signals of four ports whatever the cell has

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=64)
def pbch_res(pci, n_rb):
    """(k, l) of the 240 PBCH resource elements of subframe 0: slot 1 symbols 0-3, the 72 central subcarriers, around the
    reference signals of four ports whatever the cell has"""
    k0 = 6*n_rb - 36
    ks, ls = [], []
    for l in range(4):
        for k in range(k0, k0 + 72):
            if l < 2 and (k - pci % 6) % 3 == 0:
                continue
            ks.append(k)
            ls.append(7 + l)
    return np.array(ks), np.array(ls)

parse_mib

parse_mib(b)

The 24 MIB bits (36.331 6.2.2): dl-Bandwidth 3, phich-Config 3, the SFN's 8 MSBs, then 10 bits of later releases

Source code in src/rpps/grid/lte/phy.py
def parse_mib(b):
    """The 24 MIB bits (36.331 6.2.2): dl-Bandwidth 3, phich-Config 3, the SFN's 8 MSBs, then 10 bits of later releases"""
    v = lambda a, n: int("".join(str(int(x)) for x in b[a:a + n]), 2)
    return {"n_rb": BANDWIDTH.get(v(0, 3)), "phich_duration": v(3, 1), "phich_ng": PHICH_NG[v(4, 2)], "sfn_msb": v(6, 8)}

reg_res

reg_res(k0, l, pci, ports)

The four resource elements (k, l) of the REG from subcarrier k0

Source code in src/rpps/grid/lte/phy.py
def reg_res(k0, l, pci, ports):
    """The four resource elements (k, l) of the REG from subcarrier k0"""
    if _reg_step(l, ports) == 6: # (around the reference signals of ports 0 and 1, even in a one-port cell)
        return [k for k in range(k0, k0 + 6) if (k - pci % 6) % 3 != 0]
    return list(range(k0, k0 + 4))

short_phich

short_phich(duplex, sf)

TDD subframes 1 and 6: an extended PHICH of two symbols (Table 6.9.3-1)

Source code in src/rpps/grid/lte/phy.py
def short_phich(duplex, sf):
    """TDD subframes 1 and 6: an extended PHICH of two symbols (Table 6.9.3-1)"""
    return duplex == "tdd" and sf in (1, 6)

phich_regs

phich_regs(pci, n_rb, groups, ports, extended=False, short=False)

The PHICH's REGs (k0, l), three a group (6.9.3)

Symbol 0 (normal duration), symbols 0-2 (extended), 0-1 (extended, short)

Source code in src/rpps/grid/lte/phy.py
def phich_regs(pci, n_rb, groups, ports, extended=False, short=False):
    """The PHICH's REGs (k0, l), three a group (6.9.3)

    Symbol 0 (normal duration), symbols 0-2 (extended), 0-1 (extended, `short`)"""
    pcf = pcfich_regs(pci, n_rb)
    free = [[k for k in range(0, 12*n_rb, _reg_step(l, ports)) if (k, l) not in pcf] for l in range(3)]
    ref = len(free[1 if extended and short else 0])
    out = set()
    for m in range(groups):
        for i in range(3):
            l = 0 if not extended else (m//2 + i + 1) % 2 if short else i
            n = len(free[l])
            out.add((free[l][(pci*n//ref + m + (i*n)//3) % n], l))
    return out

control_regs cached

control_regs(pci, n_rb, symbols, phich_groups, ports, extended=False, short=False)

The PDCCH's REGs (k0, l)

Time first, past the PCFICH and the PHICH (phich_regs)

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=256)
def control_regs(pci, n_rb, symbols, phich_groups, ports, extended=False, short=False):
    """The PDCCH's REGs (k0, l)

    Time first, past the PCFICH and the PHICH (`phich_regs`)"""
    used = set(pcfich_regs(pci, n_rb)) | phich_regs(pci, n_rb, phich_groups, ports, extended, short)
    return [(k, l) for k in range(12*n_rb) for l in range(symbols) if k % _reg_step(l, ports) == 0 and (k, l) not in used]

control_symbols

control_symbols(cfi, n_rb)

OFDM symbols of the control region: the CFI, one more at 10 resource blocks or fewer (Table 6.7-1)

Source code in src/rpps/grid/lte/phy.py
def control_symbols(cfi, n_rb):
    """OFDM symbols of the control region: the CFI, one more at 10 resource blocks or fewer (Table 6.7-1)"""
    return int(cfi) + (1 if n_rb <= 10 else 0)

phich_groups

phich_groups(ng, n_rb, mi=1)

PHICH groups

ceil(Ng N_RB / 8), times m_i in TDD (Table 6.9-1: by the uplink-downlink configuration and the subframe)

Source code in src/rpps/grid/lte/phy.py
def phich_groups(ng, n_rb, mi=1):
    """PHICH groups

    ceil(Ng N_RB / 8), times m_i in TDD (Table 6.9-1: by the uplink-downlink configuration and the subframe)"""
    return int(mi)*int(np.ceil(ng*n_rb/8))

control_res cached

control_res(pci, n_rb, symbols, phich_groups_, ports, extended=False, short=False)

(k, l) of the PDCCH REGs' resource elements in order (control_regs, each REG's four)

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=256)
def control_res(pci, n_rb, symbols, phich_groups_, ports, extended=False, short=False):
    """(k, l) of the PDCCH REGs' resource elements in order (control_regs, each REG's four)"""
    return _res(control_regs(pci, n_rb, symbols, phich_groups_, ports, extended, short), pci, ports)

subblock_perm cached

subblock_perm(n)

The 32-column sub-block interleaver's read-out order of n items (36.212 5.1.4.2.1, dummies left out)

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=256)
def subblock_perm(n):
    """The 32-column sub-block interleaver's read-out order of n items (36.212 5.1.4.2.1, dummies left out)"""
    from ... import code
    return code.load("interleave/lte_subblock", length=n).encoder.src

dci_1a_size

dci_1a_size(n_rb, duplex='fdd')

Format 1A's payload bits (5.3.3.1.3)

Padded to format 0's and past the ambiguous sizes. TDD has a HARQ bit more and the downlink assignment index (format 0: the UL index or assignment index)

Source code in src/rpps/grid/lte/phy.py
def dci_1a_size(n_rb, duplex="fdd"):
    """Format 1A's payload bits (5.3.3.1.3)

    Padded to format 0's and past the ambiguous sizes. TDD has a HARQ bit more and the downlink assignment index (format 0:
    the UL index or assignment index)"""
    tdd = duplex == "tdd"
    f1a = 1 + 1 + riv_bits(n_rb) + 5 + 3 + 1 + 2 + 2 + (3 if tdd else 0)
    f0 = 1 + 1 + riv_bits(n_rb) + 5 + 1 + 2 + 3 + 1 + (2 if tdd else 0)
    n = max(f1a, f0)
    return n + 1 if n in AMBIGUOUS else n

parse_1a

parse_1a(bits, n_rb, duplex='fdd')

DCI 1A's fields, with an SI-, P- or RA-RNTI

With those the NDI picks the second gap of a distributed allocation (gap, from 50 resource blocks) and the TPC's low bit the TBS column

Source code in src/rpps/grid/lte/phy.py
def parse_1a(bits, n_rb, duplex="fdd"):
    """DCI 1A's fields, with an SI-, P- or RA-RNTI

    With those the NDI picks the second gap of a distributed allocation (`gap`, from 50 resource blocks) and the TPC's low
    bit the TBS column"""
    take = _fields(bits)
    d = {"flag": take(1), "distributed": take(1), "riv": take(riv_bits(n_rb)), "mcs": take(5),
         "harq": take(4 if duplex == "tdd" else 3), "ndi": take(1), "rv": take(2), "tpc": take(2)}
    d["gap"] = int(d["distributed"] and n_rb >= 50 and d["ndi"])
    return d

riv_decode

riv_decode(riv, n_rb)

(first resource block, count) of a contiguous allocation (36.213 7.1.6.3)

Source code in src/rpps/grid/lte/phy.py
def riv_decode(riv, n_rb):
    """(first resource block, count) of a contiguous allocation (36.213 7.1.6.3)"""
    L, S = riv//n_rb + 1, riv % n_rb
    if S + L > n_rb:
        L, S = n_rb - L + 2, n_rb - 1 - S
    return S, L

step_1c

step_1c(n_rb)

N_RB^step of format 1C's allocation (36.213 Table 7.1.6.3-1)

Source code in src/rpps/grid/lte/phy.py
def step_1c(n_rb):
    """N_RB^step of format 1C's allocation (36.213 Table 7.1.6.3-1)"""
    return 2 if n_rb < 50 else 4

dci_1c_size

dci_1c_size(n_rb)

Format 1C's payload bits

The gap (N_RB >= 50), the allocation in steps of N_RB^step over the first gap's virtual blocks, 5 bits of TBS

Source code in src/rpps/grid/lte/phy.py
def dci_1c_size(n_rb):
    """Format 1C's payload bits

    The gap (N_RB >= 50), the allocation in steps of N_RB^step over the first gap's virtual blocks, 5 bits of TBS"""
    return (1 if n_rb >= 50 else 0) + _riv_1c_bits(n_rb) + 5

gaps

gaps(n_rb, second=False)

(N_gap, N_VRB, interleaving unit) of a gap (Table 6.2.3.2-1)

Source code in src/rpps/grid/lte/phy.py
def gaps(n_rb, second=False):
    """(N_gap, N_VRB, interleaving unit) of a gap (Table 6.2.3.2-1)"""
    if n_rb < 11:
        g = (n_rb + 1)//2
    elif n_rb == 11:
        g = 4
    else:
        g = next(g for top, g in ((19, 8), (26, 12), (44, 18), (63, 27), (79, 32), (110, 48)) if n_rb <= top)
    if not second:
        n = 2*min(g, n_rb - g)
        return g, n, n
    if n_rb < 50:
        raise ValueError(f"{n_rb} resource blocks have one gap")
    g = 9 if n_rb <= 63 else 16
    return g, n_rb//(2*g)*2*g, 2*g

dvrb_map cached

dvrb_map(n_rb, second=False)

(2, N_VRB): each distributed block's physical block, per slot

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=32)
def dvrb_map(n_rb, second=False):
    """(2, N_VRB): each distributed block's physical block, per slot"""
    gap, n_vrb, unit = gaps(n_rb, second)
    P = 1 if n_rb <= 10 else 2 if n_rb <= 26 else 3 if n_rb <= 63 else 4 # RBG size (36.213 Table 7.1.6.1-1)
    rows = int(np.ceil(unit/(4*P)))*P
    null = 4*rows - unit
    out = np.zeros((2, n_vrb), np.int64)
    for n in range(n_vrb):
        t, base = n % unit, unit*(n//unit)
        a = 2*rows*(t % 2) + t//2 + base
        b = rows*(t % 4) + t//4 + base
        if null and t >= unit - null:
            even = a - rows if t % 2 else a - rows + null//2
        elif null and t % 4 >= 2:
            even = b - null//2
        else:
            even = b
        odd = (even - base + unit//2) % unit + base
        for slot, v in enumerate((even, odd)):
            out[slot, n] = v if v - base < unit//2 else v + gap - unit//2
    out.flags.writeable = False
    return out

tbs_table cached

tbs_table(name='lte/tbs')

{I_TBS: [TBS, ...]} of a table/lte definition

lte/tbs (36.213 Table 7.1.7.2.1-1, the N_PRB columns 1..10 a DCI 1A for system information uses) or lte/tbs_1c (Table 7.1.7.2.3-1)

Source code in src/rpps/grid/lte/phy.py
@functools.lru_cache(maxsize=None)
def tbs_table(name="lte/tbs"):
    """{I_TBS: [TBS, ...]} of a table/lte definition

    lte/tbs (36.213 Table 7.1.7.2.1-1, the N_PRB columns 1..10 a DCI 1A for system information uses) or lte/tbs_1c (Table
    7.1.7.2.3-1)"""
    from ... import _config
    t = _config.read(_config.find("table", name))
    return {r[0]: list(r[1:]) for r in t["rows"]}

allocation

allocation(d, n_rb)

(blocks, TBS) of a DCI, or None

d: the fields of parse_1a or parse_1c, with "format". None for an allocation or size the standard does not have

Source code in src/rpps/grid/lte/phy.py
def allocation(d, n_rb):
    """(blocks, TBS) of a DCI, or None

    d: the fields of parse_1a or parse_1c, with "format". None for an allocation or size the standard does not have"""
    if d["format"] == "1C":
        step = step_1c(n_rb)
        first, count = riv_decode(int(d["riv"]), gaps(n_rb)[1]//step)
        first, count, distributed = first*step, count*step, True
        row = tbs_table("lte/tbs_1c").get(int(d["mcs"]))
        tbs = None if row is None else row[0]
    else:
        first, count = riv_decode(int(d["riv"]), n_rb)
        distributed = bool(d["distributed"])
        row = tbs_table().get(int(d["mcs"]))
        tbs = None if row is None else row[(3 if int(d["tpc"]) & 1 else 2) - 1] # N_PRB^1A: the TPC's low bit (36.213 7.1.7)
    if tbs is None or first < 0 or count < 1:
        return None
    if distributed:
        m = dvrb_map(n_rb, bool(d["gap"]))
        if first + count > m.shape[1]:
            return None
        blocks = tuple(np.sort(m[slot, first:first + count]) for slot in (0, 1))
    else:
        if first + count > n_rb:
            return None
        blocks = (np.arange(first, first + count),)*2
    return blocks, tbs

pdsch_res

pdsch_res(blocks, symbols, pci, sf, n_rb, ports, duplex='fdd')

(k, l) of a PDSCH's elements

On the resource blocks blocks (those of the even slot, of the odd slot): subcarrier first, then symbol, from symbol symbols (the control region's), around the reference signals, the synchronization signals and the PBCH. FDD: PSS and SSS in symbols 6 and 5 of subframes 0 and 5; TDD: SSS in symbol 13 of those, PSS in symbol 2 of subframes 1 and 6

Source code in src/rpps/grid/lte/phy.py
def pdsch_res(blocks, symbols, pci, sf, n_rb, ports, duplex="fdd"):
    """(k, l) of a PDSCH's elements

    On the resource blocks `blocks` (those of the even slot, of the odd slot): subcarrier first, then symbol, from symbol
    `symbols` (the control region's), around the reference signals, the synchronization signals and the PBCH. FDD: PSS and
    SSS in symbols 6 and 5 of subframes 0 and 5; TDD: SSS in symbol 13 of those, PSS in symbol 2 of subframes 1 and 6"""
    ks = [(12*np.asarray(b)[:, None] + np.arange(12)).reshape(-1) for b in blocks]
    mask = crs_mask(pci, n_rb, ports)
    mid = (6*n_rb - 36, 6*n_rb + 36)
    if duplex == "tdd":
        sync = (13,) if sf in (0, 5) else (2,) if sf in (1, 6) else ()
    else:
        sync = (5, 6) if sf in (0, 5) else ()
    if sf == 0:
        sync += (7, 8, 9, 10) # the PBCH
    K, L = [], []
    for l in range(symbols, 14):
        k = ks[l//7]
        keep = ~mask[l, k]
        if l in sync:
            keep &= ~((k >= mid[0]) & (k < mid[1]))
        K.append(k[keep])
        L.append(np.full(int(keep.sum()), l))
    return np.concatenate(K), np.concatenate(L)

tx

An LTE downlink to test the receive side with: cell signals, MIB, CFI, a DCI 1A to the SI-RNTI and its PDSCH

x = rp.grid.lte.tx.downlink(pci=77, ports=2, n_rb=15, frames=8, sib=bits)    # 3.84 MS/s, from subframe 0 of SFN 0

Every downlink subframe carries the reference signals of its ports and a PCFICH; the synchronization signals where the duplex mode puts them; subframe 0 the PBCH (the MIB of its frame's SFN); subframe 5 of every even frame a DCI (1A, localized or distributed, or 1C) in the common search space and the transport block sib on the PDSCH it allocates (36.331 5.2.1.2: where SIB1 goes). TDD: the uplink subframes of the uplink-downlink configuration are silent and the special ones carry only their control region and synchronization signals. Transmit diversity over the ports (6.3.4.3), each port's resource grid to samples by its own IFFT; channel puts each port through a gain of its own, sums them and adds a carrier offset, a delay and noise (cells on one carrier: the sum of their channels' outputs). Normal cyclic prefix (3GPP TS 36.211, 36.212, 36.213).

Functions:

Name Description
diversity

(ports, len(x)): what each port sends on the resource elements of a channel, in order (6.3.4.3)

riv

The resource indication value of a contiguous allocation (36.213 7.1.6.3)

dci_1a

DCI 1A's payload bits

dci_1c

DCI 1C's payload bits

subframe

(ports, 14, 12 N_RB): what each port sends in a subframe

modulate

(ports, samples): each port's grid (ports, 14 n, 12 N_RB) to samples, a subframe per 14 symbols

downlink

(ports, samples) of a downlink at the rate of n_rb's FFT

channel

The ports' samples (ports, n) through a flat gain each, summed; then a carrier offset [Hz at fs], delay samples of

diversity

diversity(x, ports)

(ports, len(x)): what each port sends on the resource elements of a channel, in order (6.3.4.3)

Source code in src/rpps/grid/lte/tx.py
def diversity(x, ports):
    """(ports, len(x)): what each port sends on the resource elements of a channel, in order (6.3.4.3)"""
    x = np.asarray(x, complex)
    y = np.zeros((ports, len(x)), complex)
    if ports == 1:
        y[0] = x
        return y
    s = 1/np.sqrt(2)
    if ports == 2:
        a, b = x[0::2], x[1::2]
        y[0, 0::2], y[0, 1::2] = s*a, s*b
        y[1, 0::2], y[1, 1::2] = -s*np.conj(b), s*np.conj(a)
        return y
    for q, (p1, p2) in ((0, (0, 2)), (2, (1, 3))):
        a, b = x[q::4], x[q + 1::4]
        y[p1, q::4], y[p1, q + 1::4] = s*a, s*b
        y[p2, q::4], y[p2, q + 1::4] = -s*np.conj(b), s*np.conj(a)
    return y

riv

riv(first, count, n_rb)

The resource indication value of a contiguous allocation (36.213 7.1.6.3)

Source code in src/rpps/grid/lte/tx.py
def riv(first, count, n_rb):
    """The resource indication value of a contiguous allocation (36.213 7.1.6.3)"""
    if count - 1 <= n_rb//2:
        return n_rb*(count - 1) + first
    return n_rb*(n_rb - count + 1) + (n_rb - 1 - first)

dci_1a

dci_1a(n_rb, first, count, mcs, rv=0, tpc=0, distributed=0, gap=0, duplex='fdd')

DCI 1A's payload bits

For an allocation (first, count: virtual blocks), padded to its size (36.212 5.3.3.1.3)

Source code in src/rpps/grid/lte/tx.py
def dci_1a(n_rb, first, count, mcs, rv=0, tpc=0, distributed=0, gap=0, duplex="fdd"):
    """DCI 1A's payload bits

    For an allocation (first, count: virtual blocks), padded to its size (36.212 5.3.3.1.3)"""
    tdd = duplex == "tdd"
    b = ([1, distributed] + _bits(riv(first, count, n_rb), phy.riv_bits(n_rb)) + _bits(mcs, 5) + _bits(0, 4 if tdd else 3)
         + [gap] + _bits(rv, 2) + _bits(tpc, 2) + ([0, 0] if tdd else []))
    return np.array(b + [0]*(phy.dci_1a_size(n_rb, duplex) - len(b)), np.uint8)

dci_1c

dci_1c(n_rb, first, count, mcs, gap=0)

DCI 1C's payload bits

first and count (virtual blocks) multiples of N_RB^step, mcs the TBS's row

Source code in src/rpps/grid/lte/tx.py
def dci_1c(n_rb, first, count, mcs, gap=0):
    """DCI 1C's payload bits

    first and count (virtual blocks) multiples of N_RB^step, mcs the TBS's row"""
    step = phy.step_1c(n_rb)
    if first % step or count % step:
        raise ValueError(f"DCI 1C allocates in steps of {step}")
    n = phy.gaps(n_rb)[1]//step
    b = ([gap] if n_rb >= 50 else []) + _bits(riv(first//step, count//step, n), phy.dci_1c_size(n_rb) - 5 - (n_rb >= 50))
    return np.array(b + _bits(mcs, 5), np.uint8)

subframe

subframe(pci, sf, sfn, n_rb, ports, cfi=1, phich_ng=1.0, dci=None, sib=None, rv=0, rnti=phy.SI_RNTI, cce=0, L=4, fmt='1A', duplex='fdd', uldl=1, extended=False)

(ports, 14, 12 N_RB): what each port sends in a subframe

fmt: the DCI's format; uldl: TDD's uplink-downlink configuration; extended: the PHICH's duration

Source code in src/rpps/grid/lte/tx.py
def subframe(pci, sf, sfn, n_rb, ports, cfi=1, phich_ng=1.0, dci=None, sib=None, rv=0, rnti=phy.SI_RNTI, cce=0, L=4,
             fmt="1A", duplex="fdd", uldl=1, extended=False):
    """(ports, 14, 12 N_RB): what each port sends in a subframe

    fmt: the DCI's format; uldl: TDD's uplink-downlink configuration; extended: the PHICH's duration"""
    nsc = 12*n_rb
    X = np.zeros((ports, 14, nsc), complex)
    kind = TDD_CONFIGS[uldl][sf] if duplex == "tdd" else "D"
    if kind == "U":
        return X
    for p in range(ports): # Reference signals (a special subframe's: those of its control region here)
        for slot in (0, 1):
            ns = 2*sf + slot
            for l in phy.CRS_SYMBOLS[p]:
                if kind == "D" or slot*7 + l < 3:
                    X[p, slot*7 + l, (phy.crs_shift(p, ns, l) + pci) % 6::6] = phy.crs_values(pci, ns, l, n_rb)
    k = 6*n_rb - 31 + np.arange(62) # Synchronization signals, on port 0
    if duplex == "fdd" and sf in (0, 5):
        X[0, 6, k] = pss((25, 29, 34)[pci % 3])
        X[0, 5, k] = sss(pci//3, pci % 3, sf // 5)
    if duplex == "tdd" and sf in (0, 5):
        X[0, 13, k] = sss(pci//3, pci % 3, sf // 5)
    if duplex == "tdd" and sf in (1, 6):
        X[0, 2, k] = pss((25, 29, 34)[pci % 3])
    def put(sym, k, l):
        X[:, l, k] += diversity(sym, ports)
    if sf == 0: # PBCH
        m = mib(n_rb, sfn, phich_ng, int(extended))
        crc = crc_bits(m, "crc16_xmodem") ^ np.array({1: [0]*16, 2: [1]*16, 4: [0, 1]*8}[ports], np.uint8)
        e = tail_biting_encode(np.concatenate((m, crc)), 1920) ^ phy.gold(pci, 1920)
        q = sfn % 4
        put(qpsk(e[q*480:(q + 1)*480]), *phy.pbch_res(pci, n_rb))
    short = phy.short_phich(duplex, sf)
    if extended: # (the control region holds the PHICH)
        cfi = max(cfi, (2 if short else 3) - (n_rb <= 10))
    w = phy.CFI_WORDS[cfi] ^ phy.gold(((sf + 1)*(2*pci + 1) << 9) + pci, 32) # PCFICH
    put(qpsk(w), *phy.pcfich_res(pci, n_rb, ports))
    if dci is not None: # PDCCH: the DCI in CCEs cce..cce+L-1, the rest of the region <NIL>
        mi = TDD_MI[uldl][sf] if duplex == "tdd" else 1
        regs = phy.control_regs(pci, n_rb, phy.control_symbols(cfi, n_rb), phy.phich_groups(phich_ng, n_rb, mi), ports,
                                extended, short)
        M = len(regs)
        c = np.concatenate((dci, crc_bits(dci, "crc16_xmodem") ^ np.array(_bits(rnti, 16), np.uint8)))
        bits = np.zeros(8*M, np.uint8)
        bits[72*cce:72*(cce + L)] = tail_biting_encode(c, 72*L)
        nil = np.ones(8*M, bool)
        nil[72*cce:72*(cce + L)] = False
        bits ^= phy.gold((sf << 9) + pci, 8*M)
        quads = qpsk(bits).reshape(M, 4)
        quads[nil.reshape(M, 8)[:, 0]] = 0
        w = quads[np.asarray(phy.subblock_perm(M))] # The quadruplet interleaver, then the shift by the cell
        wbar = w[(np.arange(M) + pci) % M]
        put(wbar.reshape(-1), *phy._res(regs, pci, ports))
    if sib is not None: # PDSCH: the transport block the DCI allocated
        d = phy.parse_1c(dci, n_rb) if fmt == "1C" else phy.parse_1a(dci, n_rb, duplex)
        blocks, _ = phy.allocation({**d, "format": fmt}, n_rb)
        k, l = phy.pdsch_res(blocks, phy.control_symbols(cfi, n_rb), pci, sf, n_rb, ports, duplex)
        tb = np.asarray(sib, np.uint8)
        c = np.concatenate((tb, crc_bits(tb, "crc24_lte_a")))
        K = len(c)
        d = np.asarray(_turbo(K).encode(c)).astype(np.uint8)
        e = np.asarray(_turbo_rm(K, 2*len(k), rv).encode(d)).astype(np.uint8)
        e ^= phy.gold((rnti << 14) + (sf << 9) + pci, len(e))
        put(qpsk(e), k, l)
    return X

modulate

modulate(X, nfft)

(ports, samples): each port's grid (ports, 14 n, 12 N_RB) to samples, a subframe per 14 symbols

Source code in src/rpps/grid/lte/tx.py
def modulate(X, nfft):
    """(ports, samples): each port's grid (ports, 14 n, 12 N_RB) to samples, a subframe per 14 symbols"""
    ports, nsym, nsc = X.shape
    n_rb = nsc//12
    cp0, cp = phy.cp_lengths(nfft)
    b = phy.sc_bin(np.arange(nsc), nfft, n_rb)
    out = []
    for i in range(nsym):
        F = np.zeros((ports, nfft), complex)
        F[:, b] = X[:, i]
        t = np.fft.ifft(F, axis=1)*np.sqrt(nfft)
        c = cp0 if i % 7 == 0 else cp
        out.append(np.concatenate((t[:, -c:], t), axis=1))
    return np.concatenate(out, axis=1)
downlink(pci=77, ports=2, n_rb=15, frames=4, sib=None, mcs=None, first=None, count=None, cfi=None, phich_ng=1.0, sfn0=0, L=4, fmt='1A', distributed=False, gap=0, rv=0, duplex='fdd', uldl=1, extended=False)

(ports, samples) of a downlink at the rate of n_rb's FFT

From subframe 0 of frame sfn0, frames radio frames (6 RB: 1.92 MS/s, 15: 3.84, 25: 7.68, 50: 15.36). sib: the transport block in subframe 5 of every even frame: its length a TBS of the 1A table at N_PRB^1A 2, or of the 1C table with fmt "1C" (the mcs is found for it), on count virtual blocks from first (distributed 1A and 1C: distributed ones, over gap gap), redundancy version rv (a 1C does not say it); its DCI at aggregation L. cfi: default the smallest whose control region holds L CCEs. duplex, uldl, extended: see subframe

Source code in src/rpps/grid/lte/tx.py
def downlink(pci=77, ports=2, n_rb=15, frames=4, sib=None, mcs=None, first=None, count=None, cfi=None, phich_ng=1.0,
             sfn0=0, L=4, fmt="1A", distributed=False, gap=0, rv=0, duplex="fdd", uldl=1, extended=False):
    """(ports, samples) of a downlink at the rate of n_rb's FFT

    From subframe 0 of frame sfn0, `frames` radio frames (6 RB: 1.92 MS/s, 15: 3.84, 25: 7.68, 50: 15.36). sib: the
    transport block in subframe 5 of every even frame: its length a TBS of the 1A table at N_PRB^1A 2, or of the 1C table
    with fmt "1C" (the mcs is found for it), on `count` virtual blocks from `first` (distributed 1A and 1C: distributed
    ones, over gap `gap`), redundancy version rv (a 1C does not say it); its DCI at aggregation L. cfi: default the smallest
    whose control region holds L CCEs. duplex, uldl, extended: see `subframe`"""
    if cfi is None:
        mi = TDD_MI[uldl][5] if duplex == "tdd" else 1
        cfi = next(c for c in ((3,) if extended else (1, 2, 3))
                   if len(phy.control_regs(pci, n_rb, phy.control_symbols(c, n_rb), phy.phich_groups(phich_ng, n_rb, mi),
                                           ports, extended)) >= 9*L)
    nfft = {v: k for k, v in phy.N_RB.items()}[n_rb]
    dci = None
    if sib is not None:
        step = phy.step_1c(n_rb) if fmt == "1C" else 1
        if count is None: # (the allocation holds the block)
            count = (2 if n_rb <= 6 else 4) if step == 1 else 2*step if n_rb > 6 else 2
        first = 0 if first is None else first
        if fmt == "1C":
            if mcs is None:
                mcs = next(m for m, row in sorted(phy.tbs_table("lte/tbs_1c").items()) if row[0] == len(sib))
            dci = dci_1c(n_rb, first, count, mcs, gap)
        else:
            if mcs is None:
                mcs = next(m for m, row in sorted(phy.tbs_table().items()) if row[1] == len(sib))
            dci = dci_1a(n_rb, first, count, mcs, rv, 0, int(distributed), gap, duplex)
    grids = []
    for f in range(frames):
        sfn = (sfn0 + f) % 1024
        for sf in range(10):
            on = sib is not None and sf == 5 and sfn % 2 == 0
            grids.append(subframe(pci, sf, sfn, n_rb, ports, cfi, phich_ng, dci if on else None, sib if on else None, rv,
                                  L=L, fmt=fmt, duplex=duplex, uldl=uldl, extended=extended))
    return modulate(np.concatenate(grids, axis=1), nfft)

channel

channel(y, gains=None, cfo=0.0, fs=None, delay=0, snr_db=None, seed=0)

The ports' samples (ports, n) through a flat gain each, summed; then a carrier offset [Hz at fs], delay samples of noise before, and noise at snr_db (per sample, of the summed signal)

Source code in src/rpps/grid/lte/tx.py
def channel(y, gains=None, cfo=0.0, fs=None, delay=0, snr_db=None, seed=0):
    """The ports' samples (ports, n) through a flat gain each, summed; then a carrier offset [Hz at fs], `delay` samples of
    noise before, and noise at snr_db (per sample, of the summed signal)"""
    rng = np.random.default_rng(seed)
    ports = len(y)
    if gains is None:
        gains = np.exp(2j*np.pi*rng.random(ports))*(0.6 + 0.4*rng.random(ports))
    x = np.sum(np.asarray(gains)[:, None]*y, axis=0)
    x = np.concatenate((np.zeros(delay, complex), x))
    if cfo:
        x = x*np.exp(2j*np.pi*cfo*np.arange(len(x))/fs)
    if snr_db is not None:
        p = np.mean(np.abs(x[delay:])**2)
        n = np.sqrt(p/10**(snr_db/10)/2)
        x = x + n*(rng.standard_normal(len(x)) + 1j*rng.standard_normal(len(x)))
    return x.astype(np.complex64)

rpps.grid.nr

5G NR downlink (FR1, 15 and 30 kHz), with LEO non-terrestrial Doppler: SS/PBCH block, MIB, CORESET 0, DCI 1_0, SIB1

Modules:

Name Description
cell

5G NR cell search and slot timing through LEO Doppler (38.211 7.4.2-7.4.3, 38.213 4.1): samples to whole slots

channels

NR downlink channels read off NrGrid's frames: PBCH (MIB), PDCCH (DCI 1_0 in CORESET 0), PDSCH (SIB1)

grid

The NR resource grid of each subframe: NrCell's slots to a stream of frames, one a millisecond

phy

5G NR downlink physical layer at 15 and 30 kHz subcarriers (FR1): SS/PBCH block, PBCH payload, CORESET 0, PDCCH, PDSCH

tx

A 5G NR downlink to test the receive side with, and a LEO satellite pass to put it through

cell

5G NR cell search and slot timing through LEO Doppler (38.211 7.4.2-7.4.3, 38.213 4.1): samples to whole slots

The SS/PBCH block is at 15 or 30 kHz (scs), the sample rate scs x nfft; pattern says where a half frame's candidate blocks start (38.213 4.1: A at 15 kHz; B or C at 30, by the band: C unless told).

Acquiring (the first acquire seconds): the PSS at 256 x scs samples a second over carrier offsets offset +- span (a LEO pass at S-band moves the carrier by up to some 50 kHz), folded on the SS/PBCH block period (period, 20 ms). Then each block at the full rate: the residual offset from the PSS-to-SSS phase, less the cell's bias in it (NR gives each symbol's carrier a phase of its own, 38.211 5.4: a constant for a cell, found against the four symbols' cyclic prefixes), the SSS's N_ID1, and from the PBCH (DM-RS, then its CRC) the block's index and half frame, which place the slots and the frame, and the spacing of the channels it points to (the MIB's). Over the blocks of the acquisition, the sample clock (the delay's rate: a satellite's range stretches the signal by tens of ppm) and the offset's rate.

Tracking: every block, its PSS's timing error and its offset (the bias kept up to date) drive two loops of the second order: time (the next slot's start and the clock's rate) and frequency (the offset and its rate: a pass changes it by hundreds of Hz a second). Between blocks the offset follows its rate, the derotation's phase continuous. With no Doppler the rates stay near zero: the same receiver serves a terrestrial cell.

Out come the samples of whole slots (at the block's spacing) from the start of the frame holding the first block acquired, derotated, each slot started at the nearest sample to where the clock puts it (a sample dropped or repeated between slots), so the output's frames start every 10 ms of it and every second frame holds the block (20 ms). Lost for lose periods, the cell is acquired again, zeros standing in for the slots missed. est["cell"]: the cell, block, half frame, the spacings, offset and its rate, the clock's rate [ppm].

Classes:

Name Description
NrCell

NR cell search and slot timing, LEO Doppler tracked (see the module)

NrCell

NrCell(offset=0.0, span=60000.0, resolution=0.0, period=0.02, acquire=0.065, lose=8, gate=0.25, fc=0.0, scs=15000.0, pattern='auto', name='cell')

Bases: Stage

NR cell search and slot timing, LEO Doppler tracked (see the module)

offset, span, resolution: carrier offsets searched [Hz] (resolution 0: 4 kHz at 15 kHz spacing, 8 at 30); period: SS/PBCH block period [s]; acquire: seconds looked at; lose: periods without the block before acquiring again; gate: the PSS's normalized correlation for a block; fc: the block centre's absolute frequency (on the raster), when known: the PSS-to-SSS bias is then one of two, none or what the upconversion phase gives at fc (est "phase"), whichever the cyclic prefixes' average is nearer; scs: the block's subcarrier spacing; pattern: "A", "B", "C" or "auto" (A at 15 kHz, C at 30)

Source code in src/rpps/grid/nr/cell.py
def __init__(self, offset=0.0, span=60e3, resolution=0.0, period=0.02, acquire=0.065, lose=8, gate=0.25, fc=0.0,
             scs=15e3, pattern="auto", name="cell"):
    self.scs, self.mu = float(scs), phy.mu_of(scs)
    self.pattern = ("C" if self.mu else "A") if pattern == "auto" else pattern
    if phy.SSB_PATTERNS.get(self.pattern, (None,))[0] != self.mu:
        raise ValueError(f"NrCell: pattern {pattern!r} at {self.scs/1e3:g} kHz (A at 15, B or C at 30)")
    self.offset, self.span, self.period = float(offset), float(span), float(period)
    self.resolution = float(resolution) or 4e3*(1 << self.mu)
    self.acquire, self.lose, self.gate, self.name = float(acquire), int(lose), float(gate), name
    self.fc = float(fc)

channels

NR downlink channels read off NrGrid's frames: PBCH (MIB), PDCCH (DCI 1_0 in CORESET 0), PDSCH (SIB1)

The PBCH is at the SS/PBCH block's spacing, the PDCCH and PDSCH at the one its MIB names (15 or 30 kHz each). Each estimates its channel from its own DM-RS (least squares, linear between them in frequency, and in time for the PDSCH) and publishes what it decoded from the first item of its slot (rpps.base.control.publish), as rpps.grid.lte's do:

PBCH   subframes NrGrid marks as holding the block: the MIB and the payload's timing (SFN, half frame, k_SSB's MSB);
       publishes sfn (and the output frame it was read in, frame_ref), coreset0, ss0, k_ssb, dmrs_pos, barred
PDCCH  once the MIB is known, and unless its k_SSB says the block has no SIB1 (above 23: est "no_sib1"): the Type0 occasions (38.213 13: slots n0 and the one after, of frames of the right
       parity) of CORESET 0 (`min_bw`: the band's minimum channel bandwidth, which picks its table), every candidate of aggregation 4, 8 and 16 (polar, block/polar/nr_dci), for the `rntis`; publishes
       a DCI 1_0's fields (for its subframe, with its slot)
PDSCH  where a DCI allocated it (contiguous virtual blocks, interleaved onto the CORESET's or not): the TBS (38.214 5.1.3.2), LDPC (block/ldpc/nr_bg*), the transport block's CRC;
       gives the block when the CRC checks

The phase NR's upconversion gives each symbol (38.211 5.4: e^(j 2 pi f0 (t - t_start,l - N_CP,l Tc)), the carrier's phase restarted every symbol) reaches a receiver that mixes down continuously as e^(-j 2 pi fc t_l) on symbol l: t_l its useful part's start in the subframe, fc the absolute frequency at 0 Hz, here the SS/PBCH block's centre on the synchronization raster. The PBCH and PDCCH, a DM-RS in every symbol, do not notice; the PDSCH, its DM-RS in some, does. Not every cell shows it (on air, one cell of two did: one sharing its carrier with LTE did not), so the PDSCH, given fc, tries the block with the phase taken off and without, the one that worked last first: the CRC says which.

Classes:

Name Description
PBCH

The MIB of every SS/PBCH block NrGrid marks (see the module)

PDCCH

DCI 1_0 in CORESET 0's Type0 occasions (see the module)

PDSCH

The transport block a DCI 1_0 allocated (see the module)

PBCH

PBCH(name='pbch')

Bases: _NrChannel

The MIB of every SS/PBCH block NrGrid marks (see the module)

Source code in src/rpps/grid/nr/channels.py
def __init__(self, name="pbch"):
    super().__init__(name)

PDCCH

PDCCH(rntis=(phy.SI_RNTI,), min_bw=5, name='pdcch')

Bases: _NrChannel

DCI 1_0 in CORESET 0's Type0 occasions (see the module)

Methods:

Name Description
search

(aggregation, CCE, payload bits, RNTI) of every DCI for the RNTIs in one slot's grid

Source code in src/rpps/grid/nr/channels.py
def __init__(self, rntis=(phy.SI_RNTI,), min_bw=5, name="pdcch"):
    super().__init__(name, rntis=tuple(int(r) for r in rntis), min_bw=int(min_bw), sfn=None, frame_ref=0,
                     coreset0=None, ss0=None, k_ssb=0, i_ssb=0, dmrs_pos=2, barred=0)
search
search(pci, G, slot, c0bin, n_rb, nsym, first)

(aggregation, CCE, payload bits, RNTI) of every DCI for the RNTIs in one slot's grid

Source code in src/rpps/grid/nr/channels.py
def search(self, pci, G, slot, c0bin, n_rb, nsym, first):
    """(aggregation, CCE, payload bits, RNTI) of every DCI for the RNTIs in one slot's grid"""
    K = phy.dci_10_si_size(n_rb) + 24
    n_cce = n_rb*nsym//6
    found = []
    for L in (4, 8, 16): # Every candidate of a level in one list decode (they share K and E)
        starts = list(range(0, n_cce - L + 1, L))
        if not starts:
            continue
        soft = []
        for cce in starts:
            data, (mb, ms, mi) = phy.pdcch_res(c0bin, n_rb, nsym, first, pci, cce, L)
            ref = np.empty(len(mb), complex)
            for sym in np.unique(ms):
                seq = phy.pdcch_dmrs(pci, slot, sym, 3*n_rb)
                ref[ms == sym] = seq[mi[ms == sym]]
            z, _ = phy.equalize(G, data, (mb, ms), ref)
            soft.append(phy.soft_bits(z, 2)*phy.sign(phy.gold(pci, 108*L)))
        dec = _dci_code(K, 108*L).decoder
        paths, _ = dec.paths(np.concatenate(soft))
        res = dec.residue(paths)
        for w, cce in enumerate(starts):
            for p, r in enumerate(res[w]):
                if int(r) in self.rntis:
                    bits = paths[w, p, :K - 24]
                    if not any(np.array_equal(bits, f[2]) for f in found):
                        found.append((L, cce, bits, int(r)))
                    break
    return found

PDSCH

PDSCH(fc=0.0, min_bw=5, name='pdsch')

Bases: _NrChannel

The transport block a DCI 1_0 allocated (see the module)

Source code in src/rpps/grid/nr/channels.py
def __init__(self, fc=0.0, min_bw=5, name="pdsch"):
    super().__init__(name, coreset0=None, k_ssb=0, dmrs_pos=2, fdra=None, tdra=0, vrb=0, mcs=0, rv=0, sii=0,
                     rnti=phy.SI_RNTI, aggregation=None, cce=None, slot=None, fc=float(fc), min_bw=int(min_bw))
    self.order = [True, False] if self.fc else [False] # Take the symbols' phase off: first what worked last

grid

The NR resource grid of each subframe: NrCell's slots to a stream of frames, one a millisecond

HEAD items       cell id, subframe of the frame 0-9, SIZE (samples of a subframe / 15: nfft x 2^mu), subframe count,
                 the first slot symbol (counted through the subframe) of the SS/PBCH block NrCell tracks if the
                 subframe holds it (else -1) and the symbol past its last, its index, its half frame, mu of the
                 channels' grid, mu of the block's
4 x 240          the block's own grid B[l, k] (its spacing: NR's may differ from the channels'), where held
14 2^mu x nfft   the grid G[slot, l, bin] of each of the subframe's slots at the channels' spacing (the MIB's):
                 every FFT bin, lowest frequency first, the block's centre at nfft/2

NR has no reference signal over the whole band: each channel after it (a branch of the profile) estimates its channel from its own DM-RS. A frame's length depends on the sample rate alone, 16 + 960 + 14 x Fs / 15 kHz. unpack(frame) gives the header and the grids.

Classes:

Name Description
NrGrid

Slots of samples to grid frames (see the module); cell: the name of NrCell's estimates

Functions:

Name Description
unpack

(header dict, G (slots, 14, nfft), B (4, 240)) of one frame: views, no copies

NrGrid

NrGrid(cell='cell', period=0.02)

Bases: Stage

Slots of samples to grid frames (see the module); cell: the name of NrCell's estimates

Source code in src/rpps/grid/nr/grid.py
def __init__(self, cell="cell", period=0.02):
    self.cell, self.period = cell, float(period)

unpack

unpack(frame)

(header dict, G (slots, 14, nfft), B (4, 240)) of one frame: views, no copies

Source code in src/rpps/grid/nr/grid.py
def unpack(frame):
    """(header dict, G (slots, 14, nfft), B (4, 240)) of one frame: views, no copies"""
    f = np.asarray(frame)
    v = lambda i: int(round(f[i].real))
    size, mu = v(2), v(7)
    nfft = size >> mu
    head = {"pci": v(0), "subframe": v(1), "nfft": nfft, "count": v(3), "ssb_symbol": v(4), "ssb_end": v(5),
            "i_ssb": v(6), "mu": mu, "mu_ssb": v(8), "n_hf": v(9)}
    return head, f[HEAD + BLOCK:HEAD + BLOCK + 14*size].reshape(1 << mu, 14, nfft), f[HEAD:HEAD + BLOCK].reshape(4, 240)

phy

5G NR downlink physical layer at 15 and 30 kHz subcarriers (FR1): SS/PBCH block, PBCH payload, CORESET 0, PDCCH, PDSCH

3GPP TS 38.211 (signals, mapping), 38.212 (7.1 BCH, 7.3 DCI), 38.213 (4.1: block positions; 13: CORESET 0 and Type0 search space), 38.214 (5.1 PDSCH). The numerology mu is 0 (15 kHz) or 1 (30 kHz): a slot is 14 symbols in 1 ms >> mu, and at a sample rate of scs x nfft it is 15 nfft samples; the first symbol of every half millisecond has the longer prefix. The SS/PBCH block and the channels it points to may differ in mu.

The grid of a slot is (14, nfft): every FFT bin, lowest frequency first, with the SS/PBCH block's subcarrier 120 at 0 Hz (NrCell puts it there). So subcarrier k of the block is bin nfft/2 - 120 + k of a grid at its spacing, and every other channel is placed from it: CORESET 0 from the block's first subcarrier, k_SSB and the table's offset.

Functions:

Name Description
mu_of

The numerology of a subcarrier spacing [Hz]

cp_lengths

(the long prefix, the others') in samples

slot_len

Samples of a slot, at either spacing

symbol_starts

The useful part's first sample of a slot's 14 symbols

grid

The (14, nfft) grid of a slot's samples, lowest frequency first

symbol_phase

Undoes the upconversion phase

modulate

Samples of slots from their grids (n*14, nfft), as grid reads them

pbch_dmrs

The 144 PBCH DM-RS symbols of block i_SSB-bar (i_SSB + 4 n_hf below 3 GHz)

ssb_map

(k, l) of the block's PBCH (432) and of its DM-RS (144), in mapping order, k 0-239 and l 0-3 within the block

ssb_bins

Bin of each of the block's 240 subcarriers

ssb_place

(slot in the half frame, first symbol in it) of candidate block i_SSB

equalize

(Y conj(H), |H|^2) of the data REs of a grid from the DM-RS

read_pbch

The PBCH of a block's grid (4, 240), or None where the CRC fails

payload_scramble

The 32 bits XORed onto the interleaved payload (7.1.2): c(j + v M), M = 29, v the SFN's 3rd and 2nd LSBs

payload_encode

The 32 PBCH payload bits (before CRC): the 24 MIB bits (SFN's MSBs in them), the timing bits, interleaved, scrambled

payload_decode

(MIB bits 24, sfn, hrf, k_SSB's MSB) from the 32 payload bits after the CRC

parse_mib

The MIB's fields (38.331 6.2.2) by name (SFN's MSBs left to payload_decode)

pbch_scramble

PBCH scrambling (38.211 7.3.3.1)

coreset0

CORESET 0 (38.213 13)

coreset0_first_bin

CORESET 0's first bin, or None

type0_slots

(slots n0, n0 + 1), frame parity, first symbol of Type0 occasions

cce_regs

For each CCE, the (symbol, RB) of its 6 REGs (interleaved mapping, bundles of L = 6, R = 2, shift = cell id)

pdcch_dmrs

The PDCCH DM-RS of a symbol: n values (3 a RB)

parse_dci_10_si

DCI format 1_0 with the SI-RNTI (38.212 7.3.1.2.1)

vrb_interleaver

VRB-to-PRB (38.211 7.3.1.6)

dmrs_symbols

PDSCH DM-RS symbols of the slot: single symbol, dmrs-AdditionalPosition pos2 (Table 7.4.1.1.2-3)

tbs

Transport block size (38.214 5.1.3.2) from the REs a PRB carries in the slot

pdsch_res

PDSCH data and DM-RS elements

pdcch_res

(bins, symbols) of a candidate's data REs in mapping order, and of its DM-RS (bins, symbols, sequence index)

ldpc_for

The code block's LDPC code for a transport block of TBS bits (one code block: K' = TBS + its CRC)

qam

Symbols of bits, Qm 2, 4, 6 (Gray, 38.211 5.1.3-5.1.5)

soft_bits

Max-log soft bits (positive = 0) of equalized symbols z (unit channel), Qm 2, 4, 6

mu_of

mu_of(scs)

The numerology of a subcarrier spacing [Hz]

Source code in src/rpps/grid/nr/phy.py
def mu_of(scs):
    """The numerology of a subcarrier spacing [Hz]"""
    mu = SPACINGS.get(float(scs))
    if mu is None:
        raise ValueError(f"NR: subcarrier spacing {scs/1e3:g} kHz (15 or 30)")
    return mu

cp_lengths

cp_lengths(nfft, mu)

(the long prefix, the others') in samples

Source code in src/rpps/grid/nr/phy.py
def cp_lengths(nfft, mu):
    """(the long prefix, the others') in samples"""
    cp = int(round(nfft*144/2048))
    return cp + int(round(nfft*(16 << mu)/2048)), cp

slot_len

slot_len(nfft)

Samples of a slot, at either spacing

Source code in src/rpps/grid/nr/phy.py
def slot_len(nfft):
    """Samples of a slot, at either spacing"""
    return 15*nfft

symbol_starts cached

symbol_starts(nfft, mu)

The useful part's first sample of a slot's 14 symbols

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=32)
def symbol_starts(nfft, mu):
    """The useful part's first sample of a slot's 14 symbols"""
    long, cp = cp_lengths(nfft, mu)
    out, pos = [], 0
    for l in range(14):
        c = long if l % (14 if mu else 7) == 0 else cp
        out.append(pos + c)
        pos += c + nfft
    assert pos == slot_len(nfft)
    out = np.array(out)
    out.flags.writeable = False
    return out

grid

grid(x, nfft, mu, early=None)

The (14, nfft) grid of a slot's samples, lowest frequency first

The window starts early samples into the prefix, its phase ramp taken off

Source code in src/rpps/grid/nr/phy.py
def grid(x, nfft, mu, early=None):
    """The (14, nfft) grid of a slot's samples, lowest frequency first

    The window starts `early` samples into the prefix, its phase ramp taken off"""
    early = nfft//128 if early is None else early
    st = symbol_starts(nfft, mu) - early
    W = np.fft.fft(np.asarray(x)[st[:, None] + np.arange(nfft)[None, :]], axis=1)
    f = np.fft.fftfreq(nfft, 1/nfft)
    W = W*np.exp(2j*np.pi*f*early/nfft)[None, :]
    return np.fft.fftshift(W, axes=1)

symbol_phase

symbol_phase(fc, nfft, mu, slot=0)

Undoes the upconversion phase

e^(j 2 pi fc t_l) (38.211 5.4) for a receiver whose 0 Hz is at fc (t_l: the useful part's start in the subframe; slot: the slot's number, which in the subframe is slot mod 2^mu)

Source code in src/rpps/grid/nr/phy.py
def symbol_phase(fc, nfft, mu, slot=0):
    """Undoes the upconversion phase

    e^(j 2 pi fc t_l) (38.211 5.4) for a receiver whose 0 Hz is at fc (t_l: the useful part's start in the subframe; slot:
    the slot's number, which in the subframe is slot mod 2^mu)"""
    t = ((slot % (1 << mu))*slot_len(nfft) + symbol_starts(nfft, mu))/(15e3*(1 << mu)*nfft)
    return np.exp(2j*np.pi*((fc*t) % 1.0))

modulate

modulate(G, nfft, mu)

Samples of slots from their grids (n*14, nfft), as grid reads them

Source code in src/rpps/grid/nr/phy.py
def modulate(G, nfft, mu):
    """Samples of slots from their grids (n*14, nfft), as `grid` reads them"""
    long, cp = cp_lengths(nfft, mu)
    out = []
    for i, row in enumerate(np.asarray(G)):
        t = np.fft.ifft(np.fft.ifftshift(row))*np.sqrt(nfft)
        c = long if i % (14 if mu else 7) == 0 else cp
        out.append(np.concatenate((t[-c:], t)))
    return np.concatenate(out)

pbch_dmrs

pbch_dmrs(pci, i_ssb_bar)

The 144 PBCH DM-RS symbols of block i_SSB-bar (i_SSB + 4 n_hf below 3 GHz)

Source code in src/rpps/grid/nr/phy.py
def pbch_dmrs(pci, i_ssb_bar):
    """The 144 PBCH DM-RS symbols of block i_SSB-bar (i_SSB + 4 n_hf below 3 GHz)"""
    c = gold((1 << 11)*(i_ssb_bar + 1)*(pci//4 + 1) + (1 << 6)*(i_ssb_bar + 1) + pci % 4, 288)
    return (sign(c[0::2]) + 1j*sign(c[1::2]))/np.sqrt(2)

ssb_map cached

ssb_map(pci)

(k, l) of the block's PBCH (432) and of its DM-RS (144), in mapping order, k 0-239 and l 0-3 within the block

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=1008)
def ssb_map(pci):
    """(k, l) of the block's PBCH (432) and of its DM-RS (144), in mapping order, k 0-239 and l 0-3 within the block"""
    v = pci % 4
    pk, pl, dk, dl = [], [], [], []
    for l in (1, 2, 3):
        ks = range(240) if l != 2 else [k for k in range(240) if k < 48 or k >= 192]
        for k in ks:
            if (k - v) % 4 == 0:
                dk.append(k); dl.append(l)
            else:
                pk.append(k); pl.append(l)
    return np.array(pk), np.array(pl), np.array(dk), np.array(dl)

ssb_bins

ssb_bins(nfft)

Bin of each of the block's 240 subcarriers

Source code in src/rpps/grid/nr/phy.py
def ssb_bins(nfft):
    """Bin of each of the block's 240 subcarriers"""
    return nfft//2 - 120 + np.arange(240)

ssb_place

ssb_place(pattern, i_ssb)

(slot in the half frame, first symbol in it) of candidate block i_SSB

Source code in src/rpps/grid/nr/phy.py
def ssb_place(pattern, i_ssb):
    """(slot in the half frame, first symbol in it) of candidate block i_SSB"""
    _, first, period = SSB_PATTERNS[pattern]
    return divmod(first[i_ssb % len(first)] + period*(i_ssb//len(first)), 14)

equalize

equalize(G, data, dmrs, ref)

(Y conj(H), |H|^2) of the data REs of a grid from the DM-RS

data: (bins, symbols); dmrs: (bins, symbols), their values ref. Least squares at each, linear in frequency within a symbol, and linear in time between DM-RS symbols (constant past them)

Source code in src/rpps/grid/nr/phy.py
def equalize(G, data, dmrs, ref):
    """(Y conj(H), |H|^2) of the data REs of a grid from the DM-RS

    data: (bins, symbols); dmrs: (bins, symbols), their values `ref`. Least squares at each, linear in frequency within a
    symbol, and linear in time between DM-RS symbols (constant past them)"""
    db, ds = data
    mb, ms = dmrs[0], dmrs[1]
    ls = G[ms, mb]/ref
    syms = np.unique(ms)
    Hs = np.array([np.interp(db, mb[ms == s], ls[ms == s].real) + 1j*np.interp(db, mb[ms == s], ls[ms == s].imag)
                   for s in syms]) # (DM-RS symbols, data REs)
    if len(syms) == 1:
        H = Hs[0]
    else:
        w = np.interp(ds, syms, np.arange(len(syms))) # Each data RE's place among the DM-RS symbols
        i0 = np.minimum(np.floor(w).astype(np.int64), len(syms) - 2)
        a = w - i0
        j = np.arange(len(db))
        H = Hs[i0, j]*(1 - a) + Hs[i0 + 1, j]*a
    return G[ds, db]*np.conj(H), np.abs(H)**2

read_pbch

read_pbch(B, pci)

The PBCH of a block's grid (4, 240), or None where the CRC fails

A dict (mib: its 24 bits, sfn, hrf, k_ssb_msb, i_ssb). The DM-RS says i_SSB-bar; the scrambling takes two bits of the block's index where a half frame has 4 candidates (i_SSB-bar then carries the half frame in its third) and three where it has more: both are tried, the CRC says which

Source code in src/rpps/grid/nr/phy.py
def read_pbch(B, pci):
    """The PBCH of a block's grid (4, 240), or None where the CRC fails

    A dict (mib: its 24 bits, sfn, hrf, k_ssb_msb, i_ssb). The DM-RS says i_SSB-bar; the scrambling takes two bits of the
    block's index where a half frame has 4 candidates (i_SSB-bar then carries the half frame in its third) and three where it
    has more: both are tried, the CRC says which"""
    pk, pl, dk, dl = ssb_map(pci)
    ibar = _pbch_index(B, pci)
    z, _ = equalize(B, (pk, pl), (dk, dl), pbch_dmrs(pci, ibar))
    s = soft_bits(z, 2)
    for i_ssb in sorted({ibar & 3, ibar}):
        a, err = _pbch_code().decoder.decode(s*sign(pbch_scramble(pci, i_ssb)), status=True)
        if err[0] >= 0:
            mib, sfn, hrf, kmsb = payload_decode(np.asarray(a, np.uint8), pci)
            return {"mib": mib, "sfn": sfn, "hrf": hrf, "k_ssb_msb": kmsb, "i_ssb": i_ssb}
    return None

payload_scramble

payload_scramble(pci, sfn_lsb23)

The 32 bits XORed onto the interleaved payload (7.1.2): c(j + v M), M = 29, v the SFN's 3rd and 2nd LSBs

Source code in src/rpps/grid/nr/phy.py
def payload_scramble(pci, sfn_lsb23):
    """The 32 bits XORed onto the interleaved payload (7.1.2): c(j + v M), M = 29, v the SFN's 3rd and 2nd LSBs"""
    s = np.zeros(32, np.uint8)
    c = gold(pci, 29*4)
    j = 0
    for i in range(32):
        if i in UNSCRAMBLED:
            continue
        s[i] = c[j + sfn_lsb23*29]
        j += 1
    return s

payload_encode

payload_encode(mib, sfn, hrf, k_ssb, pci)

The 32 PBCH payload bits (before CRC): the 24 MIB bits (SFN's MSBs in them), the timing bits, interleaved, scrambled

Source code in src/rpps/grid/nr/phy.py
def payload_encode(mib, sfn, hrf, k_ssb, pci):
    """The 32 PBCH payload bits (before CRC): the 24 MIB bits (SFN's MSBs in them), the timing bits, interleaved, scrambled"""
    mib = np.asarray(mib, np.uint8).copy()
    mib[1:7] = [(sfn >> (9 - i)) & 1 for i in range(6)]
    a = np.r_[mib, [(sfn >> 3) & 1, (sfn >> 2) & 1, (sfn >> 1) & 1, sfn & 1, hrf, (k_ssb >> 4) & 1, 0, 0]].astype(np.uint8)
    out = np.zeros(32, np.uint8)
    out[POS] = a
    return out ^ payload_scramble(pci, (sfn >> 1) & 3)

payload_decode

payload_decode(bits, pci)

(MIB bits 24, sfn, hrf, k_SSB's MSB) from the 32 payload bits after the CRC

Source code in src/rpps/grid/nr/phy.py
def payload_decode(bits, pci):
    """(MIB bits 24, sfn, hrf, k_SSB's MSB) from the 32 payload bits after the CRC"""
    b = np.asarray(bits, np.uint8)
    v = (int(b[POS[25]]) << 1) | int(b[POS[26]]) # The SFN's 3rd and 2nd LSBs: sent as they are
    a = (b ^ payload_scramble(pci, v))[POS]
    sfn = 0
    for x in list(a[1:7]) + list(a[24:28]):
        sfn = (sfn << 1) | int(x)
    return a[:24], sfn, int(a[28]), int(a[29])

parse_mib

parse_mib(mib)

The MIB's fields (38.331 6.2.2) by name (SFN's MSBs left to payload_decode)

Source code in src/rpps/grid/nr/phy.py
def parse_mib(mib):
    """The MIB's fields (38.331 6.2.2) by name (SFN's MSBs left to payload_decode)"""
    v = lambda a, n: int("".join(str(int(x)) for x in mib[a:a + n]), 2)
    return {"scs_common": v(7, 1), "k_ssb_lsb": v(8, 4), "dmrs_pos": 2 + v(12, 1), "coreset0": v(13, 4), "ss0": v(17, 4),
            "barred": v(21, 1), "intra_freq": v(22, 1)}

pbch_scramble

pbch_scramble(pci, v, n=864)

PBCH scrambling (38.211 7.3.3.1)

c(i + v 864), v the block index's two LSBs where a half frame has 4 candidates, three where it has more

Source code in src/rpps/grid/nr/phy.py
def pbch_scramble(pci, v, n=864):
    """PBCH scrambling (38.211 7.3.3.1)

    c(i + v 864), v the block index's two LSBs where a half frame has 4 candidates, three where it has more"""
    return gold(pci, 864*8)[v*864:v*864 + n]

coreset0 cached

coreset0(index, scs=15000.0, scs_common=15000.0, min_bw=5)

CORESET 0 (38.213 13)

For the SS/PBCH block's spacing, the CORESET's, and the band's minimum channel bandwidth [MHz] (5 or 10; 40: the tables of its own where the block is at 30 kHz)

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=None)
def coreset0(index, scs=15e3, scs_common=15e3, min_bw=5):
    """CORESET 0 (38.213 13)

    For the SS/PBCH block's spacing, the CORESET's, and the band's minimum channel bandwidth [MHz] (5 or 10; 40: the tables
    of its own where the block is at 30 kHz)"""
    name = f"nr/coreset0_{int(scs/1e3)}_{int(scs_common/1e3)}" + ("_40" if min_bw >= 40 and scs == 30e3 else "")
    cols, rows = table(name)
    r = next((dict(zip(cols, r)) for r in rows if r[0] == index), None)
    if r is None:
        raise ValueError(f"CORESET 0 index {index}: reserved")
    return r

coreset0_first_bin

coreset0_first_bin(nfft, k_ssb, offset, scs=15000.0, scs_common=15000.0)

CORESET 0's first bin, or None

The common resource block holding the SS/PBCH block's subcarrier 0 starts k_SSB subcarriers of 15 kHz before it, the CORESET offset of its own blocks below that

Source code in src/rpps/grid/nr/phy.py
def coreset0_first_bin(nfft, k_ssb, offset, scs=15e3, scs_common=15e3):
    """CORESET 0's first bin, or None

    The common resource block holding the SS/PBCH block's subcarrier 0 starts k_SSB subcarriers of 15 kHz before it, the
    CORESET `offset` of its own blocks below that"""
    below = (120*scs + k_ssb*15e3)/scs_common
    if below != round(below):
        return None
    return nfft//2 - int(below) - 12*offset

type0_slots

type0_slots(ss0, i_ssb, coreset_symbols, mu=0)

(slots n0, n0 + 1), frame parity, first symbol of Type0 occasions

For block i_SSB, at the PDCCH's mu; n0 + 1 past the frame's last slot is the next frame's first

Source code in src/rpps/grid/nr/phy.py
def type0_slots(ss0, i_ssb, coreset_symbols, mu=0):
    """(slots n0, n0 + 1), frame parity, first symbol of Type0 occasions

    For block i_SSB, at the PDCCH's mu; n0 + 1 past the frame's last slot is the next frame's first"""
    t = type0(ss0)
    x = (t["o"] << mu) + int(np.floor(i_ssb*t["m"]))
    n = 10 << mu
    first = t["first"]
    first = (0 if i_ssb % 2 == 0 else coreset_symbols) if first == "alt" else int(first)
    return (x % n, x % n + 1), (x//n) % 2, first

cce_regs cached

cce_regs(n_rb, symbols, pci, L=6, R=2)

For each CCE, the (symbol, RB) of its 6 REGs (interleaved mapping, bundles of L = 6, R = 2, shift = cell id)

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=256)
def cce_regs(n_rb, symbols, pci, L=6, R=2):
    """For each CCE, the (symbol, RB) of its 6 REGs (interleaved mapping, bundles of L = 6, R = 2, shift = cell id)"""
    n_reg = n_rb*symbols
    nb = n_reg//L
    C = nb//R
    f = np.zeros(nb, np.int64)
    for c in range(C):
        for r in range(R):
            f[c*R + r] = (r*C + c + pci) % nb
    regs = [(i % symbols, i//symbols) for i in range(n_reg)] # Numbered time first
    out = []
    for j in range(n_reg//6):
        bundles = [f[6*j//L + t] for t in range(6//L)]
        out.append([regs[b*L + q] for b in bundles for q in range(L)])
    return out

pdcch_dmrs

pdcch_dmrs(pci, slot, symbol, n)

The PDCCH DM-RS of a symbol: n values (3 a RB)

Source code in src/rpps/grid/nr/phy.py
def pdcch_dmrs(pci, slot, symbol, n):
    """The PDCCH DM-RS of a symbol: n values (3 a RB)"""
    c = gold(((1 << 17)*(14*slot + symbol + 1)*(2*pci + 1) + 2*pci) % (1 << 31), 2*n)
    return (sign(c[0::2]) + 1j*sign(c[1::2]))/np.sqrt(2)

parse_dci_10_si

parse_dci_10_si(bits, n_rb)

DCI format 1_0 with the SI-RNTI (38.212 7.3.1.2.1)

Source code in src/rpps/grid/nr/phy.py
def parse_dci_10_si(bits, n_rb):
    """DCI format 1_0 with the SI-RNTI (38.212 7.3.1.2.1)"""
    p = 0
    def take(n):
        nonlocal p
        v = int("".join(str(int(x)) for x in bits[p:p + n]), 2)
        p += n
        return v
    return {"fdra": take(int(np.ceil(np.log2(n_rb*(n_rb + 1)/2)))), "tdra": take(4), "vrb": take(1), "mcs": take(5), "rv": take(2),
            "sii": take(1)}

vrb_interleaver cached

vrb_interleaver(n_rb, bundle=2)

VRB-to-PRB (38.211 7.3.1.6)

The SI-RNTI's in CORESET 0: bundles of bundle blocks, written into two rows

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=64)
def vrb_interleaver(n_rb, bundle=2):
    """VRB-to-PRB (38.211 7.3.1.6)

    The SI-RNTI's in CORESET 0: bundles of `bundle` blocks, written into two rows"""
    n = -(-n_rb//bundle)
    cols = n//2
    f = list(range(n))
    for c in range(cols):
        for r in range(2):
            if c*2 + r < n - 1:
                f[c*2 + r] = r*cols + c
    out = np.array([bundle*f[v//bundle] + v % bundle for v in range(n_rb)])
    out.flags.writeable = False
    return out

dmrs_symbols

dmrs_symbols(mapping, s, l, dmrs_pos)

PDSCH DM-RS symbols of the slot: single symbol, dmrs-AdditionalPosition pos2 (Table 7.4.1.1.2-3)

Source code in src/rpps/grid/nr/phy.py
def dmrs_symbols(mapping, s, l, dmrs_pos):
    """PDSCH DM-RS symbols of the slot: single symbol, dmrs-AdditionalPosition pos2 (Table 7.4.1.1.2-3)"""
    if mapping == "A":
        d = s + l
        add = {8: [7], 9: [7], 10: [6, 9], 11: [6, 9], 12: [6, 9], 13: [7, 11], 14: [7, 11]}.get(d, [])
        return [dmrs_pos] + add
    add = {5: [4], 6: [4], 7: [4], 8: [3, 6], 9: [4, 7], 10: [4, 7], 11: [4, 8], 12: [5, 9], 13: [5, 9]}.get(l, [])
    return [s] + [s + a for a in add]

tbs

tbs(n_re_prb, n_prb, qm, rate, layers=1)

Transport block size (38.214 5.1.3.2) from the REs a PRB carries in the slot

Source code in src/rpps/grid/nr/phy.py
def tbs(n_re_prb, n_prb, qm, rate, layers=1):
    """Transport block size (38.214 5.1.3.2) from the REs a PRB carries in the slot"""
    n_re = min(156, n_re_prb)*n_prb
    ninfo = n_re*rate*qm*layers
    if ninfo <= 3824:
        n = max(3, int(np.floor(np.log2(ninfo))) - 6)
        nq = max(24, (1 << n)*int(np.floor(ninfo/(1 << n))))
        return next(t for t in _tbs_list() if t >= nq)
    n = int(np.floor(np.log2(ninfo - 24))) - 5
    nq = max(3840, (1 << n)*int(np.floor((ninfo - 24)/(1 << n) + 0.5)))
    if rate <= 1/4:
        C = int(np.ceil((nq + 24)/3816))
        return 8*C*int(np.ceil((nq + 24)/(8*C))) - 24
    if nq > 8424:
        C = int(np.ceil((nq + 24)/8424))
        return 8*C*int(np.ceil((nq + 24)/(8*C))) - 24
    return 8*int(np.ceil((nq + 24)/8)) - 24

pdsch_res

pdsch_res(c0bin, prbs, s, l, mapping, dmrs_pos, blocks=())

PDSCH data and DM-RS elements

(bins, symbols) and (bins, symbols, sequence index), on the resource blocks prbs (from CORESET 0's lowest, in the virtual blocks' order), symbols s..s+l-1: around the DM-RS symbols, and the REs of the SS/PBCH blocks in the slot (blocks: of each, (first symbol, the symbol past its last, first bin, the bin past its last))

Source code in src/rpps/grid/nr/phy.py
def pdsch_res(c0bin, prbs, s, l, mapping, dmrs_pos, blocks=()):
    """PDSCH data and DM-RS elements

    (bins, symbols) and (bins, symbols, sequence index), on the resource blocks `prbs` (from CORESET 0's lowest, in the
    virtual blocks' order), symbols s..s+l-1: around the DM-RS symbols, and the REs of the SS/PBCH blocks in the slot
    (`blocks`: of each, (first symbol, the symbol past its last, first bin, the bin past its last))"""
    dm = dmrs_symbols(mapping, s, l, dmrs_pos)
    sc = (c0bin + 12*np.asarray(prbs)[:, None] + np.arange(12)).reshape(-1)
    bins, syms = [], []
    for sym in range(s, s + l):
        if sym in dm:
            continue
        keep = np.ones(len(sc), bool)
        for first, end, low, high in blocks:
            if first <= sym < end:
                keep &= ~((sc >= low) & (sc < high))
        bins.append(sc[keep]); syms.append(np.full(int(keep.sum()), sym))
    up = np.sort(sc)
    db, ds, di = [], [], []
    for sym in dm:
        b = up[(up - c0bin) % 2 == 0]
        db.append(b); ds.append(np.full(len(b), sym)); di.append((b - c0bin)//2)
    return (np.concatenate(bins), np.concatenate(syms)), (np.concatenate(db), np.concatenate(ds), np.concatenate(di))

pdcch_res cached

pdcch_res(c0bin, n_rb, symbols, first_symbol, pci, cce, L)

(bins, symbols) of a candidate's data REs in mapping order, and of its DM-RS (bins, symbols, sequence index)

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=4096)
def pdcch_res(c0bin, n_rb, symbols, first_symbol, pci, cce, L):
    """(bins, symbols) of a candidate's data REs in mapping order, and of its DM-RS (bins, symbols, sequence index)"""
    regs = [r for j in range(cce, cce + L) for r in cce_regs(n_rb, symbols, pci)[j]]
    data, dmrs = [], []
    for sym, rb in regs:
        for k in range(12):
            b = c0bin + 12*rb + k
            if k % 4 == 1:
                dmrs.append((first_symbol + sym, b, 3*rb + k//4))
            else:
                data.append((first_symbol + sym, b))
    data.sort()
    dmrs.sort()
    d = np.array(data)
    m = np.array(dmrs)
    return (d[:, 1], d[:, 0]), (m[:, 1], m[:, 0], m[:, 2])

ldpc_for cached

ldpc_for(tbs_bits, rate, E, rv, qm)

The code block's LDPC code for a transport block of TBS bits (one code block: K' = TBS + its CRC)

Source code in src/rpps/grid/nr/phy.py
@functools.lru_cache(maxsize=256)
def ldpc_for(tbs_bits, rate, E, rv, qm):
    """The code block's LDPC code for a transport block of TBS bits (one code block: K' = TBS + its CRC)"""
    from ... import code
    from ...code.types.nr_ldpc import base_graph, segment
    crc = "crc16_xmodem" if tbs_bits <= 3824 else "crc24_lte_a"
    B = tbs_bits + (16 if tbs_bits <= 3824 else 24)
    bg = base_graph(tbs_bits, rate)
    C, kp, K, Z = segment(B, bg)
    if C != 1:
        raise ValueError(f"NR PDSCH: {C} code blocks (one is what is covered)")
    return crc, code.load(f"block/ldpc/nr_bg{bg}", kp=kp, e=E, rv=rv, qm=qm, z=Z)

qam

qam(bits, qm)

Symbols of bits, Qm 2, 4, 6 (Gray, 38.211 5.1.3-5.1.5)

Source code in src/rpps/grid/nr/phy.py
def qam(bits, qm):
    """Symbols of bits, Qm 2, 4, 6 (Gray, 38.211 5.1.3-5.1.5)"""
    b = 1 - 2.0*np.asarray(bits, float).reshape(-1, qm)
    if qm == 2:
        return (b[:, 0] + 1j*b[:, 1])/np.sqrt(2)
    if qm == 4:
        return (b[:, 0]*(2 - b[:, 2]) + 1j*b[:, 1]*(2 - b[:, 3]))/np.sqrt(10)
    return (b[:, 0]*(4 - b[:, 2]*(2 - b[:, 4])) + 1j*b[:, 1]*(4 - b[:, 3]*(2 - b[:, 5])))/np.sqrt(42)

soft_bits

soft_bits(z, qm, noise=1.0)

Max-log soft bits (positive = 0) of equalized symbols z (unit channel), Qm 2, 4, 6

Source code in src/rpps/grid/nr/phy.py
def soft_bits(z, qm, noise=1.0):
    """Max-log soft bits (positive = 0) of equalized symbols z (unit channel), Qm 2, 4, 6"""
    z = np.asarray(z)
    if qm == 2:
        s = np.empty(2*len(z))
        s[0::2], s[1::2] = z.real, z.imag
        return s*2*np.sqrt(2)/noise
    pts = qam(np.array([[(v >> (qm - 1 - i)) & 1 for i in range(qm)] for v in range(1 << qm)]).reshape(-1), qm)
    labels = np.array([[(v >> (qm - 1 - i)) & 1 for i in range(qm)] for v in range(1 << qm)])
    d = -np.abs(z[:, None] - pts[None, :])**2/noise
    out = np.empty((len(z), qm))
    for i in range(qm):
        out[:, i] = d[:, labels[:, i] == 0].max(axis=1) - d[:, labels[:, i] == 1].max(axis=1)
    return out.reshape(-1)

tx

A 5G NR downlink to test the receive side with, and a LEO satellite pass to put it through

y = rp.grid.nr.tx.downlink(pci=17, nfft=512, frames=8, sib=bits)       # 7.68 MS/s, from slot 0 of SFN 0
y = rp.grid.nr.tx.downlink(scs=30e3, nfft=512, sib=bits)              # 30 kHz, 15.36 MS/s
x = rp.grid.nr.tx.leo(y, fs=7.68e6, fc=2.185e9, t0=-2.0)               # 2 s before closest approach

SS/PBCH blocks every 20 ms (even frames, half frame hrf), blocks ssb of the pattern's candidates; the MIB of each frame; in slot n0 of each block's Type0-PDCCH occasion a DCI 1_0 to the SI-RNTI in CORESET 0 (aggregation L), and the transport block sib on the PDSCH it allocates, in the occasion of every block sent (mapping from the default table A, rate matched around the SS/PBCH block). The block at scs, the control and shared channels at scs_common, one antenna port. leo moves the receiver under a satellite in a circular orbit: the delay follows the slant range (the samples stretched and squeezed by it) and the carrier the Doppler, -fc dr/dt / c, tens of kHz at S-band, changing by hundreds of Hz a second at closest approach (3GPP TR 38.811 6.9 gives the same orders).

Functions:

Name Description
sib_size

The TBS of an allocation (what a DCI with these fields carries)

downlink

Samples of a downlink, scs x nfft a second

orbit

Slant range [m] to a satellite in a circular orbit passing overhead, t seconds from closest approach

doppler

The carrier's Doppler shift [Hz] at t (from closest approach)

leo

y's samples received from a LEO pass starting t0 s from closest approach: delayed by the slant range (less its value

sib_size

sib_size(n_rb_alloc, tdra_row, dmrs_pos, mcs)

The TBS of an allocation (what a DCI with these fields carries)

Source code in src/rpps/grid/nr/tx.py
def sib_size(n_rb_alloc, tdra_row, dmrs_pos, mcs):
    """The TBS of an allocation (what a DCI with these fields carries)"""
    t = phy.tdra(tdra_row, dmrs_pos)
    nd = len(phy.dmrs_symbols(t["mapping"], t["s"], t["l"], dmrs_pos))
    qm, r = phy.mcs(mcs)
    return phy.tbs(12*t["l"] - 12*nd, n_rb_alloc, qm, r)
downlink(pci=17, nfft=512, frames=4, sib=None, ssb=(0,), coreset0=0, ss0=0, k_ssb=0, dmrs_pos=2, mcs=2, first=0, count=None, tdra=0, L=4, cce=0, sfn0=0, fc=0.0, scs=15000.0, scs_common=None, pattern=None, lmax=None, hrf=0, vrb=0, min_bw=5)

Samples of a downlink, scs x nfft a second

From slot 0 of frame sfn0, frames radio frames. sib: the transport block (its length: the TBS the allocation carries, sib_size). fc: the SS/PBCH block centre's absolute frequency, for the phase NR's upconversion gives each symbol (38.211 5.4; 0: none). scs, scs_common (default: scs): the block's subcarrier spacing and the other channels'; pattern: "A", "B" or "C" (default A at 15 kHz, C at 30); lmax: candidate blocks in a half frame, 4 or 8 (default 4 at 15 kHz, 8 at 30); hrf: the half frame the blocks are in; vrb: interleaved virtual blocks

Source code in src/rpps/grid/nr/tx.py
def downlink(pci=17, nfft=512, frames=4, sib=None, ssb=(0,), coreset0=0, ss0=0, k_ssb=0, dmrs_pos=2, mcs=2, first=0,
             count=None, tdra=0, L=4, cce=0, sfn0=0, fc=0.0, scs=15e3, scs_common=None, pattern=None, lmax=None, hrf=0,
             vrb=0, min_bw=5):
    """Samples of a downlink, scs x nfft a second

    From slot 0 of frame sfn0, `frames` radio frames. sib: the transport block (its length: the TBS the allocation carries,
    `sib_size`). fc: the SS/PBCH block centre's absolute frequency, for the phase NR's upconversion gives each symbol (38.211
    5.4; 0: none). scs, scs_common (default: scs): the block's subcarrier spacing and the other channels'; pattern: "A", "B"
    or "C" (default A at 15 kHz, C at 30); lmax: candidate blocks in a half frame, 4 or 8 (default 4 at 15 kHz, 8 at 30);
    hrf: the half frame the blocks are in; vrb: interleaved virtual blocks"""
    from ... import code, link
    mu = phy.mu_of(scs)
    mu_c = mu if scs_common is None else phy.mu_of(scs_common)
    scs_common = 15e3*(1 << mu_c)
    size = nfft << mu # samples of a subframe / 15
    nfft_c = size >> mu_c
    pattern = ("C" if mu else "A") if pattern is None else pattern
    lmax = (8 if mu else 4) if lmax is None else lmax
    c0 = phy.coreset0(coreset0, scs, scs_common, min_bw)
    n_rb, nsym = c0["rbs"], c0["symbols"]
    c0bin = phy.coreset0_first_bin(nfft_c, k_ssb, c0["offset"], scs, scs_common)
    if c0bin is None or c0bin < 0 or c0bin + 12*n_rb > nfft_c:
        raise ValueError(f"CORESET 0 (k_SSB {k_ssb}) does not lie on the grid of {nfft_c} subcarriers")
    count = n_rb if count is None else count
    pbch_code = code.load("block/polar/nr_pbch").encoder
    per_c = 10 << mu_c # slots a frame, at the channels' spacing and at the block's
    per_b = 10 << mu
    Gc = np.zeros((frames*per_c, 14, nfft_c), complex)
    Gb = np.zeros((frames*per_b, 14, nfft), complex)
    held = {} # slot of Gc -> the footprints of the blocks in it
    for f in range(frames):
        sfn = (sfn0 + f) % 1024
        if sfn % 2: # Blocks every 20 ms
            continue
        mib = phy.build_mib(int(mu_c), k_ssb, dmrs_pos, coreset0, ss0)
        e = pbch_code.encode(phy.payload_encode(mib, sfn, hrf, k_ssb, pci)).astype(np.uint8)
        for i in ssb:
            slot, l0 = phy.ssb_place(pattern, i)
            slot += (5 << mu)*hrf
            G = Gb[f*per_b + slot]
            b = phy.ssb_bins(nfft)
            G[l0, b[56:183]] = phy.pss(pci % 3)
            G[l0 + 2, b[56:183]] = phy.sss(pci//3, pci % 3)
            pk, pl, dk, dl = phy.ssb_map(pci)
            v = i & (3 if lmax == 4 else 7)
            G[l0 + pl, b[pk]] = phy.qam(e ^ phy.pbch_scramble(pci, v), 2)
            G[l0 + dl, b[dk]] = phy.pbch_dmrs(pci, v + (4*hrf if lmax == 4 else 0))
            # What it covers of the channels' grid
            lead = phy.cp_lengths(nfft, mu)[1]
            at = slot*phy.slot_len(nfft) + int(phy.symbol_starts(nfft, mu)[l0])
            begin, end = at - lead, at + 3*(nfft + lead) + nfft
            cp_c = phy.cp_lengths(nfft_c, mu_c)[1]
            for s in range(per_c):
                st = s*phy.slot_len(nfft_c) + phy.symbol_starts(nfft_c, mu_c)
                hit = np.nonzero((st + nfft_c > begin + cp_c//2) & (st - cp_c < end - cp_c//2))[0]
                if len(hit):
                    half = 120*(1 << mu)//(1 << mu_c)
                    held.setdefault(f*per_c + s, []).append((int(hit[0]), int(hit[-1]) + 1, nfft_c//2 - half, nfft_c//2 + half))
    if sib is not None:
        done = set()
        for f in range(frames):
            sfn = (sfn0 + f) % 1024
            for i in ssb: # SIB1 in slot n0 of every block's Type0 occasion
                (n0, _), parity, fsym = phy.type0_slots(ss0, i, nsym, mu_c)
                at = f*per_c + n0
                if sfn % 2 != parity or at in done:
                    continue
                done.add(at)
                s, G = n0, Gc[at]
                dci = dci_10_si(n_rb, first, count, tdra, mcs, vrb=vrb)
                K = len(dci) + 24
                c = code.load("block/polar/nr_dci", K=K, E=108*L, mask=phy.SI_RNTI).encoder
                bits = c.encode(dci).astype(np.uint8) ^ phy.gold(pci, 108*L)
                (db, ds), (mb, ms, mi) = phy.pdcch_res(c0bin, n_rb, nsym, fsym, pci, cce, L)
                G[ds, db] = phy.qam(bits, 2)
                for sym in np.unique(ms):
                    seq = phy.pdcch_dmrs(pci, s, sym, 3*n_rb)
                    sel = ms == sym
                    G[sym, mb[sel]] = seq[mi[sel]]
                t = phy.tdra(tdra + 1, dmrs_pos)
                prbs = np.arange(first, first + count)
                if vrb:
                    prbs = phy.vrb_interleaver(n_rb)[prbs]
                (pb, ps), (qb, qs, qi) = phy.pdsch_res(c0bin, prbs, t["s"], t["l"], t["mapping"], dmrs_pos, held.get(at, ()))
                qm, rate = phy.mcs(mcs)
                tb = np.asarray(sib, np.uint8)
                crc, ldpc = phy.ldpc_for(len(tb), rate, qm*len(pb), 0, qm)
                cw = ldpc.encoder.encode(np.r_[tb, np.asarray(link.load(f"crc/{crc}").encoder.field(tb)).astype(np.uint8)])
                bits = cw.astype(np.uint8) ^ phy.gold((phy.SI_RNTI << 15) + pci, len(cw))
                G[ps, pb] = phy.qam(bits, qm)
                for sym in np.unique(qs):
                    seq = phy.pdsch_dmrs(pci, s, sym, int(qi.max()) + 1)
                    sel = qs == sym
                    G[sym, qb[sel]] = seq[qi[sel]]
    if fc:
        for G, n, m in ((Gb, nfft, mu), (Gc, nfft_c, mu_c)):
            for s in range(len(G)):
                G[s] *= np.conj(phy.symbol_phase(fc, n, m, s))[:, None]
    return (phy.modulate(Gb.reshape(-1, nfft), nfft, mu) + phy.modulate(Gc.reshape(-1, nfft_c), nfft_c, mu_c))

orbit

orbit(t, altitude=600000.0)

Slant range [m] to a satellite in a circular orbit passing overhead, t seconds from closest approach

Source code in src/rpps/grid/nr/tx.py
def orbit(t, altitude=600e3):
    """Slant range [m] to a satellite in a circular orbit passing overhead, t seconds from closest approach"""
    a = R_EARTH + altitude
    w = np.sqrt(MU/a**3)
    return np.sqrt(R_EARTH**2 + a**2 - 2*R_EARTH*a*np.cos(w*np.asarray(t, float)))

doppler

doppler(t, fc, altitude=600000.0)

The carrier's Doppler shift [Hz] at t (from closest approach)

Source code in src/rpps/grid/nr/tx.py
def doppler(t, fc, altitude=600e3):
    """The carrier's Doppler shift [Hz] at t (from closest approach)"""
    dt = 1e-3
    return -fc*(orbit(t + dt, altitude) - orbit(t - dt, altitude))/(2*dt)/C_LIGHT

leo

leo(y, fs, fc, t0=0.0, altitude=600000.0, delay=0, taps=24)

y's samples received from a LEO pass starting t0 s from closest approach: delayed by the slant range (less its value at the start) and shifted by the carrier's phase over it; delay samples of nothing before

Source code in src/rpps/grid/nr/tx.py
def leo(y, fs, fc, t0=0.0, altitude=600e3, delay=0, taps=24):
    """y's samples received from a LEO pass starting t0 s from closest approach: delayed by the slant range (less its value
    at the start) and shifted by the carrier's phase over it; `delay` samples of nothing before"""
    n = np.arange(len(y))
    t = t0 + n/fs
    tau = (orbit(t, altitude) - orbit(t0, altitude))/C_LIGHT
    src = n - tau*fs # Where in y each received sample comes from
    i0 = np.floor(src).astype(np.int64)
    frac = src - i0
    out = np.zeros(len(y), complex)
    k = np.arange(-taps//2 + 1, taps//2 + 1)
    yp = np.concatenate((np.zeros(taps), y, np.zeros(taps)))
    for kk in k: # Windowed sinc interpolation
        w = np.sinc(frac - kk)*(0.5 + 0.5*np.cos(np.pi*(frac - kk)/(taps/2)))
        out += w*yp[np.clip(i0 + kk + taps, 0, len(yp) - 1)]
    out *= np.exp(-2j*np.pi*fc*tau)
    return np.concatenate((np.zeros(delay, complex), out))