Contents
Sionna Signal Processing and General Utilities (signal/, utils/)
Let’s close out the last two “non-link” modules. signal/ provides general DSP components at the waveform level, while utils/ is cross-module infrastructure. These two modules show up most often when reading other people’s code, so they deserve a write-up of their own.
1. signal/: Signal Processing
| File | Purpose | Main public classes/functions |
|---|---|---|
__init__.py | Entry point of the signal-processing submodule | Aggregates and re-exports symbols from utils/window/filter/upsampling/downsampling |
filter.py | Filter blocks | Filter (abstract base class), RaisedCosineFilter, RootRaisedCosineFilter, SincFilter, CustomFilter |
window.py | Window function blocks | Window (abstract base class), CustomWindow, HannWindow, HammingWindow, BlackmanWindow |
upsampling.py | Upsampling | Upsampling(Block): inserts zeros between samples, length becomes n*samples_per_symbol |
downsampling.py | Downsampling | Downsampling(Block): decimates by samples_per_symbol; offset and num_symbols can be set |
utils.py | Signal utility functions | convolve, fft, ifft (normalized), empirical_psd, empirical_aclr |
Every block supports the padding argument: "same" keeps the output length equal to the input (symmetric truncation happens internally), while "full" returns the complete convolution result. In link-level simulation you almost always use "same" — otherwise the length changes after every filter and the dimensions stop lining up.
Pulse Shaping
The root-raised-cosine (RRC) filter is the most commonly used one; its frequency response is
is the roll-off factor: the closer it is to 0, the more compact the spectrum but the longer the time-domain tail; the closer to 1, the faster the time-domain convergence but the more bandwidth it occupies. Placing one RRC at each end of the link (so the pair forms a raised-cosine response overall) is the standard matched-filtering practice.
import torch
from sionna.phy.signal import (RaisedCosineFilter, RootRaisedCosineFilter,
SincFilter, CustomFilter)
rrc = RootRaisedCosineFilter(span_in_symbols=8, samples_per_symbol=4, beta=0.35)
rc = RaisedCosineFilter(span_in_symbols=8, samples_per_symbol=4, beta=0.35)
sinc = SincFilter(span_in_symbols=8, samples_per_symbol=4)
x = torch.randn(32, 100)
y = rrc(x, padding="same") # torch.Size([32, 100])
coefficients = torch.randn(33) # custom filter coefficients
filt = CustomFilter(samples_per_symbol=4, coefficients=coefficients)
y = filt(x, padding="same")
span_in_symbols determines the truncation length: in theory the RRC impulse response is infinitely long, so in practice it must be truncated to span_in_symbols * samples_per_symbol + 1 taps. Too small a span introduces obvious truncation error (the sidelobes get cut off); too large wastes computation — somewhere between 8 and 16 is usually enough.
Upsampling and Downsampling
import torch
from sionna.phy.signal import Upsampling, Downsampling
upsampler = Upsampling(samples_per_symbol=4)
x = torch.randn(32, 100)
y = upsampler(x) # torch.Size([32, 400])
downsampler = Downsampling(samples_per_symbol=4, offset=2)
y_ds = downsampler(y) # torch.Size([32, 100])
The offset of Downsampling selects the decimation phase — in polyphase filtering or timing-synchronization scenarios the optimal sampling point is not necessarily at the first position, and offset exists precisely for that.
Window Functions and Spectrum Tools
import torch
from sionna.phy.signal import HannWindow, HammingWindow, BlackmanWindow, CustomWindow
window = HannWindow()
x = torch.randn(32, 64)
y = window(x) # torch.Size([32, 64])
custom = CustomWindow(torch.hann_window(64))
For a custom window you just pass the coefficients; CustomWindow does not check where the coefficients come from.
import torch
from sionna.phy.signal import convolve, fft, ifft, empirical_psd, empirical_aclr
out = convolve(torch.randn(64, 100), torch.randn(10), padding="same") # [64, 100]
X = torch.randn(32, 64, dtype=torch.complex64)
X_f = fft(X) # torch.Size([32, 64])
x_t = ifft(X_f) # torch.Size([32, 64])
freqs, psd = empirical_psd(X, show=False) # each of shape [64]
aclr = empirical_aclr(X, oversampling=2.0) # scalar tensor
empirical_psd computes the empirical power spectral density (averaged over the batch dimension), and empirical_aclr computes the adjacent-channel leakage ratio. These two are quick tools for assessing spectral quality — far more convenient than hand-rolled FFTs when doing waveform design.
2. utils/: General Utilities
| File | Purpose | Main public classes/functions |
|---|---|---|
__init__.py | Entry point of the PHY utilities submodule | Wildcard-imports all submodules: metrics/numerics/tensors/linalg/misc/plotting/random |
metrics.py | Common evaluation metrics | compute_ber, compute_ser, compute_bler, count_errors, count_block_errors |
numerics.py | Numerical methods | expand_bound (widen a search interval), bisection_method (root finding by bisection) |
tensors.py | Extended PyTorch tensor operations | expand_to_rank, flatten_dims, flatten_last_dims, insert_dims, split_dim, diag_part_axis, flatten_multi_index, gather_from_batched_indices, tensor_values_are_in_set, random_tensor_from_values, enumerate_indices, find_true_position |
linalg.py | Linear-algebra utilities | inv_cholesky (inverse of a Cholesky factor), matrix_pinv (Moore–Penrose pseudoinverse) |
misc.py | Miscellaneous utilities and template classes | complex_normal, lin_to_db, db_to_lin, watt_to_dbm, dbm_to_watt, ebnodb2no, hard_decisions, sample_bernoulli, sim_ber, to_list, dict_keys_to_int, scalar_to_shaped_tensor, DeepUpdateDict, Interpolate, SplineGriddataInterpolation, MCSDecoder, TransportBlock, SingleLinkChannel |
plotting.py | Plotting functions | plot_ber, PlotBER |
random.py | torch.compile-compatible random utilities | randint, rand, uniform, normal, complex_normal |
A few worth remembering individually:
- The dimension operations in
tensors.pyare the most frequently used utility functions in Sionna. Its tensors routinely have 5 or 6 dimensions ([batch, num_tx, num_streams, num_ofdm_symbols, fft_size]), so before broadcasting you almost always needexpand_to_rankto align the ranks first. inv_choleskyis for situations where you need the “inverse of the Cholesky factor” rather than the “Cholesky factor of the inverse”, e.g. computing the whitening matrix of a covariance.ebnodb2nois the core conversion for SNR configuration: it turns (dB) into the noise variance . Note that you can pass in aresource_gridto account for pilot and CP overhead — if you don’t, the result is an idealized value that won’t match actual link performance; this is a very common source of discrepancies.random.pyexists on its own becausetorch.compilehas limited support for the native random APIs; these wrapper functions are the compile-compatible versions.SingleLinkChannelinmisc.pyis a convenience template that wraps the common “bits → encoding → modulation → channel → detection → decoding” pipeline, saving a lot of boilerplate in quick verification scripts.
Metrics and Noise
import torch
from sionna.phy.utils import (compute_ber, compute_ser, compute_bler,
count_errors, count_block_errors, ebnodb2no)
b = torch.tensor([0, 1, 0, 1])
b_hat = torch.tensor([0, 1, 1, 0])
compute_ber(b, b_hat) # 0.5
count_errors(b, b_hat) # 2
# Compute the noise variance No from Eb/No (dB); pass resource_grid to account for pilot/CP overhead
no = ebnodb2no(ebno_db=10.0, num_bits_per_symbol=4, coderate=0.5)
compute_ber returns a ratio, count_errors returns an absolute count. In Monte Carlo runs you usually accumulate total errors with the latter and divide by the total at the end — more stable than computing a ratio each round and then averaging.
Hard Decisions, dB Conversions, and Complex Gaussian Noise
import torch
from sionna.phy.utils import (hard_decisions, lin_to_db, db_to_lin,
watt_to_dbm, dbm_to_watt, complex_normal)
llr = torch.tensor([-1.5, 0.0, 2.3, -0.1])
hard_decisions(llr) # tensor([0., 0., 1., 0.])
lin_to_db(torch.tensor(100.0)) # 20.0
db_to_lin(torch.tensor(20.0)) # 100.0
watt_to_dbm(torch.tensor(1.0)) # 30.0
x = complex_normal([2, 3], var=2.0) # complex Gaussian, real and imaginary parts each get half the variance
Note how hard_decisions interprets the LLR: non-negative decides 1, negative decides 0 (an LLR of exactly 0 is decided as 1). This matches the convention used in the earlier fec/ post.
The variance in complex_normal(var=2.0) is the total power, split evenly between the real and imaginary parts (1.0 each). If you interpret it as a per-real-dimension variance, you’ll compute the power off by a factor of two — this is also where Sionna’s AWGN no parameter gets confusing (no is the noise power per complex dimension; internally AWGN adds no/2 to each of the real and imaginary parts).
Tensor Shape Operations
import torch
from sionna.phy.utils import (expand_to_rank, insert_dims, split_dim,
flatten_dims, flatten_last_dims)
x = torch.ones([3, 4])
expand_to_rank(x, 4, axis=-1).shape # expand to rank 4
insert_dims(x, num_dims=2, axis=-1).shape
split_dim(torch.ones([2, 12]), shape=[3, 4], axis=1).shape
flatten_dims(torch.ones([2, 3, 4, 5]), num_dims=2, axis=1).shape
flatten_last_dims(torch.ones([2, 3, 4]), num_dims=2).shape
expand_to_rank means “pad up to rank N”, while insert_dims means “insert a given number of dimensions”. The two names look similar but serve different purposes: the former makes the broadcasting rules between two tensors work out; the latter constructs new dimension axes.
Linear Algebra
import torch
from sionna.phy.utils import inv_cholesky, matrix_pinv
inv_cholesky(torch.eye(2)) # inverse of the Cholesky factor (identity here)
matrix_pinv(torch.randn(4, 2)).shape # torch.Size([2, 4]), Moore–Penrose pseudoinverse
BER Monte Carlo Simulation and Plotting
import numpy as np
from sionna.phy.utils import sim_ber, PlotBER, plot_ber
# mc_fun(ebno_db, batch_size) must return the transmitted bits b and the estimated bits b_hat
ber, bler = sim_ber(mc_fun, ebno_dbs=np.arange(0, 10, 2),
batch_size=100, max_mc_iter=10)
ber_plot = PlotBER(title="My BER Plot")
ber_plot.add(np.array([0, 2, 4]), np.array([0.1, 0.05, 0.01]), legend="Curve 1")
ber_plot() # display the curves
fig, ax = plot_ber(np.array([0, 2, 4]), np.array([0.2, 0.05, 0.01]),
legend="AWGN", title="BER vs SNR")
sim_ber is a standard Monte Carlo driver: given the SNR sweep points and a callback, it runs automatically until “enough errors have been collected” or “the iteration cap is reached”. The callback mc_fun(ebno_db, batch_size) must return the transmitted bits and the estimated bits so that it can count errors itself — don’t compute BER statistics inside the callback; leave it to sim_ber so that the curves remain comparable.
PlotBER is a stateful plotting object: you can add multiple curves and render them all at once; plot_ber is the single-call functional version.
3. Summary
That closes out the eight-part source-code notes. The overall thread:
| Post | Module | One-liner |
|---|---|---|
| 1 | Top level | The three base classes Object/Block/config underpin dtype handling, lazy building, and global randomness |
| 2 | channel/ | Uniformly outputs the CIR, then converts to time/frequency domain; TR 38.901 is split into a three-stage pipeline following the spec’s sections |
| 3 | fec/ | CRC + five code families; decoders uniformly consume LLRs |
| 4 | mimo/ | Equalization, detection, precoding, stream management; input (y, h, s) |
| 5 | ofdm/ | The resource grid as the coordinate system; inputs additionally carry err_var |
| 6 | nr/ | Chains the parts above into an end-to-end PUSCH link per the spec |
| 7 | signal/ utils/ | Filtering, windows, sampling, and the tensor/linalg/metrics foundation |
Looking back, Sionna’s code structure is easy to read mainly thanks to three consistent design conventions: lazy building via Block, centralized management of dtype and device, and “unified interfaces, diverse implementations” (channel models, detectors, and interpolators all follow this). Grasp these three points, and each submodule’s code is just another instance of the same pattern.
Comments
Loading comments…
Want to leave a note? Sign in first — comments are open to every signed-in reader.