原始来源:https://www.sharetechnote.com/html/5G/5G_PHY_DSP_SSB.html
正文
面向 SSB 的 NR 物理层 DSP
在本节中,我们将探讨如何利用 py3gpp 和符合 SigMF 规范的数据集,通过一套完整的 Python 实现,从 5G NR 下行信号中检测并译码物理广播信道(PBCH)。该脚本完整走通了 PBCH 译码流水线——从加载和预处理原始 IQ 采样,到识别 SSB、估计并补偿信道影响,最终对广播的系统信息进行极化码译码。借助 py3gpp 库中符合 3GPP 规范的信号处理函数,本节不仅演示了信号捕获与解调技术,还深入剖析了真实无线环境下的均衡、噪声处理与译码性能。
注:本节的源代码可在此处获取。本节使用的示例 IQ 文件可在 py3gpp 中找到。乍看之下代码可能令人生畏,但其中很大一部分只是用于调试打印。若去掉这些调试打印,它与 py3gpp 中的 test_py3gpp.ipynb 并没有太大差别。
- 文件加载与预处理
- 频谱概览与 SSB 检测
- SSB 资源网格
- 信道估计与均衡
- PBCH 译码 流水线的第一阶段专注于加载下行信号,并为后续处理做好准备。
| #The code begins by reading a SigMF-compliant IQ recording using the following line. This command loads the .sigmf-data file containing the raw complex baseband samples handle = sigmf.sigmffile.fromfile(‘30720KSPS_dl_signal.sigmf-data’) # Following this, some initial parameters are defined: These variables allow for configuring the frequency offset (delta_f) and numerology (mu) of the received waveform. delta_f = 0 f = 1 mu = 0 apply_fine_CFO = 0 # First generate reference sequences This block doesn’t generate all possible reference sequences at once. It creates initial, placeholder versions using default IDs (like NID2=0, NcellID=0). These are used to set up the variables, define their type, and perform initial normalization. The actual detection loops later in the code generate the correct reference sequences on-the-fly (e.g., nrPSS(current_NID2) within the NID2 detection loop) to perform correlations and find the true cell parameters. The initially generated pssRef, sssRef, and dmrsRef (after normalization) are primarily used later in the script for plotting the “Expected” points on the constellation diagrams, although ideally, they should be regenerated with the detected NID, NID2, and ibar_SSB before plotting for accuracy. pssRef = nrPSS(0).astype(np.complex128) # Use NID2=0 initially sssRef = nrSSS(0).astype(np.complex128) dmrsRef = nrPBCHDMRS(0, ibar_SSB=0).astype(np.complex128) # Normalize reference sequences to unit power pssRef = pssRef / np.sqrt(np.mean(np.abs(pssRef)**2)) sssRef = sssRef / np.sqrt(np.mean(np.abs(sssRef)**2)) dmrsRef = dmrsRef / np.sqrt(np.mean(np.abs(dmrsRef)**2)) # Read and preprocess waveform waveform = handle.read_samples() waveform /= max(waveform.real.max(), waveform.imag.max()) # scale max amplitude to 1 fs = handle.get_global_field(sigmf.SigMFFile.SAMPLE_RATE_KEY) waveform = waveform * np.exp(-1j2np.pidelta_f/fs(np.arange(len(waveform)))) # Normalize waveform to unit power waveform = waveform / np.sqrt(np.mean(np.abs(waveform)**2)) # Add noise with controlled SNR if ADD_NOISE: np.random.seed(NOISE_SEED) # for reproducible noise # Calculate required noise power for target SNR signal_power = np.mean(np.abs(waveform)2) noise_power = signal_power / (10(TARGET_SNR_DB/10)) noise_std = np.sqrt(noise_power/2) # Standard deviation for real and imaginary parts # Generate complex Gaussian noise noise = (np.random.normal(0, noise_std, waveform.shape[0]) + 1j * np.random.normal(0, noise_std, waveform.shape[0])) # Add noise to waveform waveform += noise # Calculate actual SNR actual_snr_db = 10 * np.log10(signal_power / np.mean(np.abs(noise)**2)) print(f’Target SNR = {TARGET_SNR_DB} dB’) print(f’Actual SNR = {actual_snr_db:.1f} dB’) |
|---|
#代码首先使用下面这行命令读取符合 SigMF 规范的 IQ 记录。该命令加载包含原始复基带采样的 .sigmf-data 文件
handle = sigmf.sigmffile.fromfile(‘30720KSPS_dl_signal.sigmf-data’)
随后定义了一些初始参数:这些变量用于配置接收波形的频偏(delta_f)和参数集(mu)。
delta_f = 0
f = 1
mu = 0
apply_fine_CFO = 0
先生成参考序列
这一代码块并不会一次性生成所有可能的参考序列,而是使用默认 ID(如 NID2=0、NcellID=0)创建初始的占位版本。它们用于建立变量、确定变量类型并进行初步归一化。代码后方的实际检测循环会即时生成正确的参考序列(例如 NID2 检测循环内的 nrPSS(current_NID2)),以执行相关运算并找到真实的小区参数。
最初生成的 pssRef、sssRef 和 dmrsRef(归一化后)主要供脚本后续在星座图上绘制”期望”点使用。不过为了准确起见,理想做法是在绘图前用检测到的 NID、NID2 和 ibar_SSB 重新生成这些序列。
pssRef = nrPSS(0).astype(np.complex128) # Use NID2=0 initially
sssRef = nrSSS(0).astype(np.complex128)
dmrsRef = nrPBCHDMRS(0, ibar_SSB=0).astype(np.complex128)
将参考序列归一化至单位功率
pssRef = pssRef / np.sqrt(np.mean(np.abs(pssRef)**2))
sssRef = sssRef / np.sqrt(np.mean(np.abs(sssRef)**2))
dmrsRef = dmrsRef / np.sqrt(np.mean(np.abs(dmrsRef)**2))
读取并预处理波形
waveform = handle.read_samples()
waveform /= max(waveform.real.max(), waveform.imag.max()) # scale max amplitude to 1
fs = handle.get_global_field(sigmf.SigMFFile.SAMPLE_RATE_KEY)
waveform = waveform * np.exp(-1j2np.pidelta_f/fs(np.arange(len(waveform))))
将波形归一化至单位功率
waveform = waveform / np.sqrt(np.mean(np.abs(waveform)**2))
添加具有指定信噪比的噪声
if ADD_NOISE:
np.random.seed(NOISE_SEED) # for reproducible noise
计算目标信噪比所需的噪声功率
signal_power = np.mean(np.abs(waveform)**2)
noise_power = signal_power / (10**(TARGET_SNR_DB/10))
noise_std = np.sqrt(noise_power/2) # Standard deviation for real and imaginary parts
生成复高斯噪声
noise = (np.random.normal(0, noise_std, waveform.shape) +
1j * np.random.normal(0, noise_std, waveform.shape))
将噪声加入波形
waveform += noise
计算实际信噪比
actual_snr_db = 10 * np.log10(signal_power / np.mean(np.abs(noise)**2))
print(f’Target SNR = {TARGET_SNR_DB} dB’)
print(f’Actual SNR = {actual_snr_db:.1f} dB’)
第一步是从 SigMF 格式的下行记录(即保存的 IQ 文件)中获取原始 IQ 采样,随后进行功率分析,并通过与参考波形做相关运算来完成 SSB 检测。该步骤的可视化输出如下所示。
图 (A) 展示了接收信号的时域功率分布,突出显示了检测到 SSB 突发的时刻。时频谱图 (B) 提供了细致的时频表示,揭示波形的周期结构与频谱占用情况。最后的图 (C) 汇总了平均功率谱,显示信号能量集中的清晰频带。这些图不仅验证了信号的完整性,也为准确解调和译码 PBCH 提供了关键的时间与频谱信息。图中标记为 (1) 和 (2) 的红线表示本节脚本定位到的 SSB 位置。

图注:(原页面未提供图示说明)
预处理与基本计算
这一代码块先配置预期的信号结构,然后生成主同步信号(PSS)的三种可能序列,将其与接收波形做相关运算,并找出相关峰最强的 PSS 序列,从而检测出 NID2。这是与 5G 小区同步的基本第一步。
| # Carrier Configuration This block configures the fundamental parameters of the 5G New Radio carrier being analyzed. It uses nrCarrierConfig to set the channel bandwidth via NSizeGrid = 106, indicating 106 Physical Resource Blocks (which commonly corresponds to a 20 MHz bandwidth for the typical 15 kHz subcarrier spacing used in synchronization), and defines the SubcarrierSpacing itself, likely set to 15 kHz based on the numerology parameter mu. Subsequently, nrOFDMInfo is used to calculate essential derived OFDM parameters, such as the appropriate FFT size and cyclic prefix lengths, based on this initial carrier configuration. carrier = nrCarrierConfig(NSizeGrid = 106, SubcarrierSpacing = 15 * 2**mu) info = nrOFDMInfo(carrier) Nfft = info[‘Nfft’] print(f’Nfft = {Nfft}’) # PSS Preparation and Index Calculation This section prepares for the Primary Synchronization Signal (PSS) detection by initializing storage arrays (peak_value, peak_index) to hold the results of correlation tests for the three possible NID2 values. It also defines key constants like the PSS length (PSS_LEN) and the number of resource elements per block (NRE_PER_PRB). Crucially, it calculates the precise frequency subcarrier indices (pssIndices) where the PSS signal is expected to be located, centered within the configured carrier bandwidth. peak_value = np.zeros(3) peak_index = np.zeros(3, ‘int’) PSS_LEN = 128 NRE_PER_PRB = 12 This calculates the specific frequency indices (subcarrier numbers) where the PSS is located within the full carrier resource grid defined by NSizeGrid. In this case it is assumed that the PSS is centered in the frequency domain. The calculation finds the center subcarrier of the 106 PRBs and then selects the 128 indices centered around it. (NOTE : In 5G, SSB is not always at the center of the resource grid. SSB position in the resource grid is configurable, but it is assumed to be at the center in this example) pssIndices = np.arange((carrier.NSizeGrid * NRE_PER_PRB // 2 - PSS_LEN // 2), (carrier.NSizeGrid * NRE_PER_PRB // 2 + PSS_LEN // 2 - 1)) #NID2 Detection Loop (Correlation)/PSS Detection This block performs the core NID2 detection by systematically testing each of the three possible NID2 values (0, 1, and 2). Within a loop, it generates a candidate time-domain Primary Synchronization Signal (PSS) waveform corresponding to the NID2 value currently being tested. This involves creating the PSS sequence, placing it on a resource grid, performing OFDM modulation, and removing the cyclic prefix. Then, this candidate PSS waveform is cross-correlated with the received signal. The loop finds and stores the magnitude and timing index of the highest correlation peak obtained for each candidate NID2, preparing for the final decision. for current_NID2 in np.arange(3, dtype=‘int’): slotGrid = nrResourceGrid(carrier) slotGrid = slotGrid[:, 0] slotGrid[pssIndices] = nrPSS(current_NID2) [refWaveform, info] = nrOFDMModulate(carrier, slotGrid, SampleRate = fs) refWaveform = refWaveform[info[‘CyclicPrefixLengths’][0]:]; # remove CP temp = scipy.signal.correlate(waveform[:int(25e-3 * fs)], refWaveform, ‘valid’) # correlate over 25 ms peak_index[current_NID2] = np.argmax(np.abs(temp)) peak_value[current_NID2] = np.abs(temp[peak_index[current_NID2]]) t_corr = np.arange(temp.shape[0])/fs*1e3 #axs[current_NID2].plot(t_corr, np.abs(temp)) detected_NID2 = np.argmax(peak_value) Since this part is so important, let me break down the block and look into the detailed meaning for current_NID2 in np.arange(3, dtype=‘int’):: This loop iterates through the three possible values for NID2: 0, 1, and 2. slotGrid = nrResourceGrid(carrier): Creates an empty resource grid (frequency vs. time) for one slot, based on the carrier config. slotGrid = slotGrid[:, 0]: Simplifies the grid to only consider the first OFDM symbol’s frequency resources. slotGrid[pssIndices] = nrPSS(current_NID2): Generates the PSS sequence corresponding to the current_NID2 value being tested in this loop iteration and places it onto the calculated frequency pssIndices within the slotGrid. [refWaveform, info] = nrOFDMModulate(…): Performs OFDM modulation. It converts the frequency-domain slotGrid (which contains only the PSS for this current_NID2) into a time-domain refWaveform. SampleRate = fs ensures this reference waveform has the same sample rate as the received waveform. refWaveform = refWaveform[info[‘CyclicPrefixLengths’][0]:]: Removes the cyclic prefix (CP) from the beginning of the generated refWaveform. Correlation is usually done using the main part of the OFDM symbol, without the CP. temp = scipy.signal.correlate(…): This is the crucial step. It calculates the cross-correlation between a segment of the input waveform (first 25 milliseconds) and the generated refWaveform (the PSS signal for current_NID2). High correlation occurs when the reference PSS aligns well in time with a matching PSS in the received signal. peak_index[current_NID2] = np.argmax(np.abs(temp)): Finds the time index where the correlation magnitude (np.abs(temp)) is highest for the current NID2. peak_value[current_NID2] = np.abs(temp[peak_index[current_NID2]]): Stores the magnitude of that highest correlation peak. |
|---|
载波配置
这一代码块配置所分析 5G NR 载波的基本参数。它使用 nrCarrierConfig 通过 NSizeGrid = 106 设置信道带宽,表示 106 个物理资源块(在同步所用的典型 15 kHz 子载波间隔下通常对应 20 MHz 带宽),并根据参数集参数 mu 将子载波间隔 SubcarrierSpacing 设为 15 kHz。随后使用 nrOFDMInfo 基于该初始载波配置计算必要的派生 OFDM 参数,例如合适的 FFT 点数和循环前缀长度。
carrier = nrCarrierConfig(NSizeGrid = 106, SubcarrierSpacing = 15 * 2**mu)
info = nrOFDMInfo(carrier)
Nfft = info[‘Nfft’]
print(f’Nfft = {Nfft}’)
PSS 准备与索引计算
本节为 PSS 检测做准备:初始化存储数组(peak_value、peak_index),用于保存三个可能 NID2 取值的相关测试结果;同时定义关键常量,如 PSS 长度(PSS_LEN)和每个资源块的资源粒子数(NRE_PER_PRB)。关键之处在于,它计算了 PSS 信号预期所在的精确频率子载波索引(pssIndices),位置处于所配置载波带宽的中心。
peak_value = np.zeros(3)
peak_index = np.zeros(3, ‘int’)
PSS_LEN = 128
NRE_PER_PRB = 12
这一步计算 PSS 在由 NSizeGrid 定义的全载波资源网格中所处的具体频率索引(子载波编号)。此处假设 PSS 位于频域中心。计算先找到 106 个资源块的中心子载波,再选取围绕它的 128 个索引。(注:在 5G 中,SSB 并不总是位于资源网格中心。SSB 在资源网格中的位置是可配置的,但本例假设它位于中心。)
pssIndices = np.arange((carrier.NSizeGrid * NRE_PER_PRB // 2 - PSS_LEN // 2), (carrier.NSizeGrid * NRE_PER_PRB // 2 + PSS_LEN // 2 - 1))
#NID2 检测循环(相关运算)/PSS 检测
这一代码块通过依次测试三个可能的 NID2 取值(0、1、2)来执行核心的 NID2 检测。循环中,它会为当前测试的 NID2 生成一个候选的时域主同步信号(PSS)波形:先创建 PSS 序列,放到资源网格上,执行 OFDM 调制,再去掉循环前缀。随后将这个候选 PSS 波形与接收信号做互相关。循环为每个候选 NID2 找到并记录最高相关峰的幅度和时间索引,为最终判决做准备。
for current_NID2 in np.arange(3, dtype=‘int’):
slotGrid = nrResourceGrid(carrier)
slotGrid = slotGrid[:, 0]
slotGrid[pssIndices] = nrPSS(current_NID2)
[refWaveform, info] = nrOFDMModulate(carrier, slotGrid, SampleRate = fs)
refWaveform = refWaveform[info[‘CyclicPrefixLengths’]:]; # remove CP
temp = scipy.signal.correlate(waveform[:int(25e-3 * fs)], refWaveform, ‘valid’) # correlate over 25 ms
peak_index[current_NID2] = np.argmax(np.abs(temp))
peak_value[current_NID2] = np.abs(temp[peak_index[current_NID2]])
t_corr = np.arange(temp.shape)/fs*1e3
#axs[current_NID2].plot(t_corr, np.abs(temp))
detected_NID2 = np.argmax(peak_value)
由于这一部分非常重要,下面我将该代码块拆解开来,逐一分析其具体含义。
- for current_NID2 in np.arange(3, dtype=‘int’):: 该循环遍历 NID2 的三个可能取值:0、1 和 2。
- slotGrid = nrResourceGrid(carrier): 基于载波配置,为一个时隙创建空的资源网格(频率对时间)。
- slotGrid = slotGrid[:, 0]: 将网格简化为只考虑第一个 OFDM 符号的频率资源。
- slotGrid[pssIndices] = nrPSS(current_NID2): 生成本轮循环正在测试的 current_NID2 所对应的 PSS 序列,并将其放置到 slotGrid 中计算得到的频率位置 pssIndices 上。
- [refWaveform, info] = nrOFDMModulate(…): 执行 OFDM 调制。它把频域的 slotGrid(此时只包含当前 current_NID2 的 PSS)转换为时域的 refWaveform。SampleRate = fs 确保该参考波形与接收波形具有相同的采样率。
- refWaveform = refWaveform[info[‘CyclicPrefixLengths’]:]: 从生成的 refWaveform 开头移除循环前缀(CP)。相关运算通常在不含 CP 的 OFDM 符号主体上进行。
- temp = scipy.signal.correlate(…): 这是关键步骤。它计算输入波形的一段(前 25 毫秒)与生成的 refWaveform(即当前 current_NID2 的 PSS 信号)之间的互相关。当参考 PSS 与接收信号中匹配的 PSS 在时间上对齐时,会出现很高的相关值。
- peak_index[current_NID2] = np.argmax(np.abs(temp)): 找出当前 NID2 下相关幅度(np.abs(temp))最大的时间索引。
- peak_value[current_NID2] = np.abs(temp[peak_index[current_NID2]]): 保存该最高相关峰的幅度。
功率随时间变化 - (A)
这一子图显示信号幅度随时间的变化,有助于识别 SSB 这类能量突发出现的时刻。红色垂直虚线标出了基于与 PSS 序列最强相关结果估计出的 SSB 定时位置。
| t_power = np.arange(len(waveform))/fs * 1000 # Time in milliseconds power_time = np.abs(waveform) ax0.plot(t_power, power_time) ssb_time = peak_index[detected_NID2]/fs*1e3 # Convert to milliseconds ax0.axvline(x=ssb_time, color=‘r’, linestyle=’—’, label=f’Detected SSB (NID2={detected_NID2})’) |
|---|
t_power = np.arange(len(waveform))/fs * 1000 # Time in milliseconds
power_time = np.abs(waveform)
ax0.plot(t_power, power_time)
ssb_time = peak_index[detected_NID2]/fs*1e3 # Convert to milliseconds
ax0.axvline(x=ssb_time, color=‘r’, linestyle=’—’, label=f’Detected SSB (NID2={detected_NID2})’)
- power_time = np.abs(waveform) 计算复波形的幅度。
- t_power 表示以毫秒为单位的时间轴。
- ax0.axvline(…) 绘制红色垂直虚线,利用相关峰值结果 peak_index[detected_NID 标记 SSB 的检测时刻
接收波形的时频谱图 - (B)
这一子图 (B) 通过时频谱图提供接收信号的时频视图。它揭示了周期性出现的 SSB 突发以及信号的整体频谱活动。图中再次画出 SSB 定时线作为参考。
| nperseg = Nfft f, t, Sxx = scipy.signal.spectrogram(waveform, fs=fs, nperseg=nperseg, noverlap=noverlap, return_onesided=False) f = np.fft.fftshift(f) Sxx = np.fft.fftshift(Sxx, axes=0) spec = ax1.pcolormesh(t1000, f/1e6, 10np.log10(np.abs(Sxx)), shading=‘gouraud’, cmap=‘viridis’, vmin=-90, vmax=-60) ax1.axvline(x=ssb_time, color=‘r’, linestyle=’—’, alpha=0.5) |
|---|
nperseg = Nfft
f, t, Sxx = scipy.signal.spectrogram(waveform, fs=fs, nperseg=nperseg, noverlap=noverlap, return_onesided=False)
f = np.fft.fftshift(f)
Sxx = np.fft.fftshift(Sxx, axes=0)
spec = ax1.pcolormesh(t1000, f/1e6, 10np.log10(np.abs(Sxx)), shading=‘gouraud’, cmap=‘viridis’, vmin=-90, vmax=-60)
ax1.axvline(x=ssb_time, color=‘r’, linestyle=’—’, alpha=0.5)
- 时频谱图使用 scipy.signal.spectrogram 计算。
- 频率 (f) 和功率值 (Sxx) 经 FFT 平移处理,使直流分量居中于 0。
- 绘图函数 ax1.pcolormesh(…) 以 dB 刻度显示时频谱图。
- 红色虚线(ax1.axvline(…))标出检测到的 SSB 定时位置,并与时间轴对齐。
由时频谱图得到的平均功率谱 - (C)
这一底部的子图显示随时间平均后的频谱功率,给出信号带宽与频谱占用的整体视图。
| power_spectrum = 10*np.log10(np.mean(np.abs(Sxx), axis=1)) ax2.plot(f/1e6, power_spectrum) |
|---|
power_spectrum = 10*np.log10(np.mean(np.abs(Sxx), axis=1))
ax2.plot(f/1e6, power_spectrum)
- np.mean(np.abs(Sxx), axis=1) 对时频谱图的功率在时间维度上取平均。
- 转换为 dB 刻度后,使用 ax2.plot(…) 随频率绘制。
检测到的 SSB 位置标记 - (1),(2)
红色垂直虚线(axvline)同时出现在”功率随时间变化”和”时频谱图”两个子图中,有助于在时域和时频两种视图之间对齐检测到的 SSB 时间位置。其计算方式为:
| ssb_time = peak_index[detected_NID2]/fs*1e3 |
|---|
ssb_time = peak_index[detected_NID2]/fs*1e3
- 其中 peak_index[…] 来自下面这个基于相关的检测循环: | temp = scipy.signal.correlate(waveform[:int(25e-3 * fs)], refWaveform, ‘valid’) peak_index[current_NID2] = np.argmax(np.abs(temp)) | | --- |
temp = scipy.signal.correlate(waveform[:int(25e-3 * fs)], refWaveform, ‘valid’)
- 该步骤通过匹配 PSS 序列并检测定时偏移,确定最可能的 SSB 位置。 接下来我想展示 SSB 的网格映射图,并绘制 SSB 中各信号与信道的星座图。下图详细展示了 5G NR 同步信号块(SSB)资源网格,以及关键下行信号对应的星座图。SSB 资源网格突出显示了各个分量——主同步信号(PSS)、辅同步信号(SSS)、解调参考信号(DMRS)和物理广播信道(PBCH)——在 OFDM 资源网格中于频率和时间两个维度上的映射方式。资源网格上的 (A)、(B)、(C) 标记将这些资源分配可视化,用不同颜色的叠加层指出每种信号类型的位置。配套的星座图提供了提取后接收符号的快照,便于直观评估信号质量与调制精度。这些图是评估同步性能和物理层译码在真实信道条件下鲁棒性的重要诊断手段。它们共同提供了对 SSB 块从 RE 分配到信号解调保真度的完整可视化诊断,有助于验证 5G NR 接收机流水线中的同步与译码环节。

图注:(原页面未提供图示说明)
OFDM 解调与资源网格准备
在进行任何资源提取或星座图绘制之前,必须先把原始的时域波形转换为对应的频域表示,即资源网格。5G NR 物理层结构(如 PSS、SSS、PBCH、DMRS)正是在这里以子载波和 OFDM 符号的形式展开布局的。
这一代码块接收波形和此前检测到的 NID2,执行若干关键步骤,进一步与 5G 小区同步并为广播信道译码做准备。它先细化定时同步,再将信号的相关部分解调到资源网格中;利用该网格检测物理小区 ID 的剩余部分(NID1,从而得到完整 NID)以及同步信号块的时间索引(ibar_SSB);最后识别并从解调后的网格中提取 PSS、SSS、PBCH DMRS 和 PBCH 数据符号。
| # Basic Parameters for SSB Basic parameters for the SSB are defined: nrbSSB (bandwidth = 20 RBs), scsSSB (subcarrier spacing, likely 15kHz), nSlot (initial slot assumption), and rxSampleRate. nrbSSB = 20 scsSSB = 15 * 2**(mu) nSlot = 0 rxSampleRate = fs # TimingOffset Estimation This is to find a precise starting point (the timingOffset in samples) within the input waveform that accurately aligns with the beginning of the Synchronization Signal Block (SSB). It does this by utilizing the already detected NID2 to generate the corresponding Primary Synchronization Signal (PSS) and then correlating this known PSS signal against the received waveform to find the point of best match. refGrid = np.zeros((nrbSSB12, 2), np.complex128) refGrid[nrPSSIndices(), 1] = nrPSS(detected_NID2) timingOffset = nrTimingEstimate(waveform = waveform, nrb = nrbSSB, scs = scsSSB, initialNSlot = nSlot, refGrid = refGrid, SampleRate = rxSampleRate) Following is the break down of the block refGrid = np.zeros((nrbSSB12, 2), np.complex128): Creates a small, empty resource grid. It spans the SSB bandwidth (20 RBs * 12 subcarriers/RB = 240 subcarriers) and covers 2 OFDM symbols. refGrid[nrPSSIndices(), 1] = nrPSS(detected_NID2): This line generates the PSS sequence based on the previously found detected_NID2. It then places this PSS sequence onto the appropriate subcarriers (nrPSSIndices()) within the first symbol (index 1) of the refGrid. This creates a reference signal containing just the PSS in its expected symbol position within the SSB structure. timingOffset = nrTimingEstimate(…): This function performs the core timing estimation. It takes the waveform, SSB parameters (nrb, scs, SampleRate), slot context (initialNSlot), and importantly, the refGrid containing only the PSS as inputs. The function likely works by correlating the reference PSS (from refGrid) against the time-domain waveform to find the time index where the correlation peak occurs, indicating the start of the SSB. The resulting sample index is stored in the timingOffset variable, which will be used subsequently for OFDM demodulation. # modulate about 8 symbols, only has to be at least 5 This block first takes the time-synchronized input signal (waveform starting at timingOffset) and converts a portion of it, guaranteed to contain the Synchronization Signal Block (SSB), from the time domain into its frequency domain representation (a resource grid). It then precisely extracts the specific 4 OFDM symbols that make up the SSB from this grid, preparing them for further analysis like signal extraction and decoding. rxGrid = nrOFDMDemodulate(waveform = waveform[timingOffset:][:np.min((len(waveform), 20488))], nrb = nrbSSB, scs = scsSSB, initialNSlot = nSlot, SampleRate=rxSampleRate, CyclicPrefixFraction=0.5) rxGrid = rxGrid[:,1:5] Following is the breakdown of the code rxGrid = nrOFDMDemodulate(…): This function performs the OFDM demodulation. It processes a segment of the waveform starting at the calculated timingOffset and extending for roughly 8 symbol durations (20488 samples, adjusted if the waveform ends sooner). It uses parameters specific to the SSB (nrbSSB, scsSSB, rxSampleRate) to correctly interpret the signal structure. The output rxGrid is a 2D array containing the complex values for each subcarrier (rows) across the demodulated OFDM symbols (columns, approx. 8 of them). rxGrid = rxGrid[:, 1:5]: This line uses NumPy slicing to select a specific portion of the rxGrid. : selects all rows (all 240 subcarriers for nrbSSB=20). 1:5 selects the columns (OFDM symbols) with indices 1, 2, 3, and 4. This precisely isolates the 4 OFDM symbols that constitute the SSB according to the 5G standard, discarding any extra symbols demodulated before (index 0) or after (indices 5, 6, 7). The rxGrid variable is updated to hold only these 4 relevant symbols. # Normalize by FFT size and additional factor to get correct constellation scaling This line scales the amplitude of all the complex values within the demodulated rxGrid. The main goal is to adjust the overall power level so that the received signal constellation points (PSS, SSS, DMRS, PBCH) align correctly with their expected standard positions, typically having magnitudes around 1, which simplifies visualization and subsequent processing steps like channel estimation or symbol demodulation. rxGrid = rxGrid / (np.sqrt(Nfft) * 3.0) # Factor of 3 to match expected constellation points rxGrid = rxGrid / …: This performs element-wise division on the entire rxGrid array. Every complex value in the grid is divided by the calculated normalization factor. np.sqrt(Nfft): This part applies standard OFDM normalization. The process of OFDM demodulation (which involves an FFT) introduces a scaling factor related to the FFT size (Nfft, likely 2048 in this context). Dividing by the square root of Nfft compensates for this inherent scaling introduced by the FFT operation. * 3.0: This is an additional, empirical, scaling factor. its purpose: to further adjust the scale so the received symbols visually match the ideal constellation points (e.g., QPSK points at +1/-1 on real/imag axes, or normalized to unit magnitude). # Get SSS indices and convert to frequency indices This block focuses on isolating the Secondary Synchronization Signal (SSS) from the demodulated SSB resource grid (rxGrid). It first identifies the specific resource elements where the SSS is located, extracts the corresponding received complex symbols, and then applies a specific normalization to these symbols, likely to prepare them for the correlation process used to detect NID1. sssIndices = nrSSSIndices() sssRx = nrExtractResources(sssIndices, rxGrid) sssRx /= np.max((sssRx.real.max(), sssRx.imag.max())) # scale sssRx symbols individually sssIndices = nrSSSIndices(): This function returns a list or array of standardized indices representing the specific time-frequency locations (resource elements) within the 4-symbol SSB grid where the SSS is transmitted. The SSS resides in the 3rd symbol (index 2) of the SSB. sssRx = nrExtractResources(sssIndices, rxGrid): This function uses the sssIndices to look up and extract the complex values from the rxGrid (which contains the 4 SSB symbols). The result, sssRx, is a vector containing the received symbols specifically for the SSS. sssRx /= np.max((sssRx.real.max(), sssRx.imag.max())): This line performs a specific normalization on the extracted sssRx symbols: It finds the maximum value among all real parts and the maximum value among all imaginary parts of the sssRx symbols. It takes the larger of these two maximums (i.e., the maximum extent of the constellation along either the real or imaginary axis). It divides every symbol in sssRx by this single maximum value. The effect is to scale the received SSS constellation so that the point furthest from the origin along either the real or imaginary axis now touches +1 on that axis (assuming the maximum value was positive). This type of normalization aims to adjust the overall amplitude scale before correlation, making it less sensitive to gain variations, while using the peak value as the reference. # SSS correlation for NID1 detection This section identifies the remaining component (NID1) needed to determine the full Physical Cell ID (NcellID) of the 5G cell. It achieves this by comparing the received Secondary Synchronization Signal (SSS) symbols, extracted previously (sssRx), against every possible reference SSS sequence. The reference sequence that best matches the received SSS reveals the correct NID1, which is then combined with the already known NID2 to get the full NcellID. sssEst = np.zeros(336) for NID1 in range(335): ncellid = (3NID1) + detected_NID2 sssRef = nrSSS(ncellid) sssEst[NID1] = np.abs(np.vdot(sssRx, sssRef)) detected_NID1 = np.argmax(sssEst) detected_NID = detected_NID13 + detected_NID2 sssEst = np.zeros(336): An array named sssEst is initialized with zeros. It has a size of 336 to store the correlation results for each possible NID1 hypothesis (where NID1 ranges from 0 to 335). for NID1 in range(335):: This loop iterates through potential NID1 values. Note: range(335) generates values from 0 up to 334. If the full range of NID1 (0-335) needs to be tested, this loop should ideally be range(336). As written, it tests NID1 from 0 to 334. ncellid = (3NID1) + detected_NID2: Inside the loop, this line calculates a candidate full Physical Cell ID (ncellid) based on the current NID1 being tested and the detected_NID2 found earlier. This follows the standard 5G formula: NcellID = 3 * NID1 + NID2. sssRef = nrSSS(ncellid): This generates the theoretical reference SSS sequence that corresponds to the candidate ncellid. Each NcellID (0-1007) has a unique SSS sequence. sssEst[NID1] = np.abs(np.vdot(sssRx, sssRef)): This is the core correlation step: np.vdot(sssRx, sssRef) computes the complex dot product between the received SSS symbols (sssRx) and the reference SSS sequence (sssRef). This measures how well they match. np.abs(…) takes the magnitude of the complex correlation result. A higher magnitude signifies a stronger match. The result is stored in the sssEst array at the index corresponding to the current NID1. detected_NID1 = np.argmax(sssEst): After the loop finishes testing all the NID1 hypotheses (0-334 in this case), this finds the index in sssEst that has the largest value. This index represents the most likely NID1. detected_NID = detected_NID13 + detected_NID2: This final calculation combines the detected_NID1 with the previously known detected_NID2 using the standard formula to determine the overall detected Physical Cell ID (detected_NID). # DMRS correlation for ibar_SSB detection This section determines the specific time index (ibar_SSB) of the received Synchronization Signal Block (SSB) relative to other potential SSBs within a burst. It works by comparing the received Demodulation Reference Signal (DMRS) symbols associated with the Physical Broadcast Channel (PBCH) against reference DMRS sequences generated for different possible ibar_SSB values. The ibar_SSB value whose reference DMRS best matches the received DMRS reveals the index of the received SSB, which is essential information for later PBCH decoding steps (specifically descrambling). dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’) xcorrPBCHDMRS = np.empty(7) for ibar_SSB in range(7): PBCHDMRS = nrPBCHDMRS(detected_NID, ibar_SSB) xcorrPBCHDMRS[ibar_SSB] = np.abs(np.vdot(nrExtractResources(dmrsIndices, rxGrid), PBCHDMRS)) ibar_SSB = np.argmax(np.abs(xcorrPBCHDMRS)) Following is the breakdown of the code and description dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’): This function call retrieves the specific resource element indices within the 4-symbol SSB grid where the PBCH DMRS symbols are located. The DMRS pattern depends on the Physical Cell ID (detected_NID). The style=‘matlab’ argument likely ensures the indices follow a specific convention (e.g., 1-based or ordering) compatible with MATLAB implementations. xcorrPBCHDMRS = np.empty(7): Initializes an empty NumPy array intended to store the correlation results for the 7 different ibar_SSB hypotheses being tested (indices 0 through 6). for ibar_SSB in range(7):: This loop iterates through the ibar_SSB hypotheses, testing the values 0, 1, 2, 3, 4, 5, and 6. Note: The actual maximum value of ibar_SSB (Lmax) can vary (4, 8, or 64 depending on frequency band), but the scrambling sequence used for PBCH often depends on ibar_SSB mod 8. Testing 0-6 covers a significant range of possibilities. PBCHDMRS = nrPBCHDMRS(detected_NID, ibar_SSB): Inside the loop, this generates the reference PBCH DMRS sequence for the current ibar_SSB hypothesis. The sequence itself depends on NID, and its scrambling depends on ibar_SSB. xcorrPBCHDMRS[ibar_SSB] = np.abs(np.vdot(nrExtractResources(dmrsIndices, rxGrid), PBCHDMRS)): This performs the correlation: nrExtractResources(dmrsIndices, rxGrid): Extracts the received DMRS symbols from the rxGrid at the locations specified by dmrsIndices. np.vdot(…): Calculates the complex dot product (correlation) between the extracted received DMRS and the generated reference DMRS (PBCHDMRS). np.abs(…): Takes the magnitude of the correlation result. The magnitude is stored in the xcorrPBCHDMRS array at the index corresponding to the current ibar_SSB hypothesis. ibar_SSB = np.argmax(np.abs(xcorrPBCHDMRS)): After testing hypotheses 0 through 6, this line finds the index (0-6) that yielded the highest correlation magnitude in the xcorrPBCHDMRS array. This index is then assigned to the ibar_SSB variable, representing the detected time index of the received SSB among the tested possibilities. # Create masks for PSS and SSS This section initializes several boolean arrays (masks) that have the same dimensions as the rxGrid (which holds the 4 symbols of the SSB). These masks (pss_mask, sss_mask, dmrs_mask, pbch_mask) act like templates, initially all set to False. They will be used in the following steps to mark the specific locations (resource elements) within the rxGrid where each type of signal (PSS, SSS, DMRS, PBCH) resides. pss_mask = np.zeros_like(rxGrid, dtype=bool) sss_mask = np.zeros_like(rxGrid, dtype=bool) dmrs_mask = np.zeros_like(rxGrid, dtype=bool) pbch_mask = np.zeros_like(rxGrid, dtype=bool) Following is the breakdown of the code and description pss_mask = np.zeros_like(rxGrid, dtype=bool): Creates a NumPy array pss_mask having the identical shape as rxGrid. The dtype=bool ensures it contains boolean values, and zeros_like initializes all elements to False. This mask will later identify PSS resource elements. sss_mask = np.zeros_like(rxGrid, dtype=bool): Similarly, creates sss_mask, a boolean array of the same shape as rxGrid, initialized to all False, intended for marking SSS locations. dmrs_mask = np.zeros_like(rxGrid, dtype=bool): Creates dmrs_mask, another boolean array matching rxGrid’s shape, initialized to all False, intended for marking PBCH DMRS locations. pbch_mask = np.zeros_like(rxGrid, dtype=bool): Creates pbch_mask, a final boolean array matching rxGrid’s shape, initialized to all False, intended for marking PBCH data symbol locations. # Get PSS indices for SSB grid This block determines the exact frequency locations (subcarrier indices) occupied by the Primary Synchronization Signal (PSS) within the SSB’s bandwidth. It then updates the pss_mask (created in the previous step) by marking these specific frequency locations within the first symbol of the SSB grid as True. pssIndices = nrPSSIndices() pss_freq_indices = pssIndices % (nrbSSB * 12) # Convert to frequency indices for SSB grid pss_mask[pss_freq_indices, 0] = True # PSS is in first symbol Following is the breakdown of the code and description pssIndices = nrPSSIndices(): This function retrieves the standard resource element indices where the PSS resides. These indices define which specific subcarriers (out of the 240 within the SSB’s 20 Resource Blocks) carry the PSS signal. pss_freq_indices = pssIndices % (nrbSSB * 12): This line ensures the indices are mapped correctly within the frequency dimension of the rxGrid. nrbSSB * 12 calculates the total number of subcarriers in the SSB bandwidth (20 * 12 = 240). The modulo operator (%) effectively maps the pssIndices (if they weren’t already 0-based relative to the SSB) into the range 0-239, representing the frequency index within the rxGrid. The result is stored in pss_freq_indices. pss_mask[pss_freq_indices, 0] = True: This command modifies the pss_mask. It uses pss_freq_indices to select the rows (subcarriers) corresponding to the PSS. It uses 0 to select the first column (OFDM symbol with index 0) within the 4-symbol mask, as the PSS occurs in the first symbol of the SSB structure. It sets the value at these specific row/column intersections within the pss_mask to True, marking the location of the PSS. # Get SSS indices for SSB grid Similar to the PSS masking, this code block determines the specific frequency locations (subcarrier indices) used by the Secondary Synchronization Signal (SSS) within the SSB’s bandwidth. It then updates the sss_mask by marking these frequency locations within the third symbol (index 2) of the SSB grid as True. sss_freq_indices = sssIndices % (nrbSSB * 12) # Convert to frequency indices for SSB grid sss_mask[sss_freq_indices, 2] = True # SSS is in third symbol (index 2) Following is the breakdown of the code and description sss_freq_indices = sssIndices % (nrbSSB * 12): This calculates the frequency indices for the SSS within the 0-239 subcarrier range of the SSB grid. sssIndices: This variable (presumably defined earlier, e.g., by sssIndices = nrSSSIndices()) contains the standard resource element indices for the SSS. nrbSSB * 12: Calculates the total number of subcarriers (240) within the SSB bandwidth. The modulo operator (%) maps the sssIndices into the range 0-239, corresponding to the frequency dimension (rows) of the rxGrid and masks. The result is stored in sss_freq_indices. sss_mask[sss_freq_indices, 2] = True: This command modifies the sss_mask. It uses sss_freq_indices to select the rows (subcarriers) where the SSS is located. It uses 2 to select the third column (OFDM symbol with index 2) within the 4-symbol mask. This is because the SSS is transmitted in the third symbol of the standard SSB structure. It sets the value at these specific SSS locations (rows specified by sss_freq_indices, column 2) within the sss_mask to True. # Get PBCH DMRS indices This block identifies the precise time-frequency locations (resource elements) within the 4-symbol SSB grid (rxGrid) where the PBCH DMRS is transmitted. It calculates the specific subcarrier and OFDM symbol indices for every DMRS symbol based on the detected Physical Cell ID (detected_NID) and then marks these locations as True in the dmrs_mask. dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’) symbol_size = nrbSSB * 12 symbol_indices = dmrsIndices // symbol_size # Get symbol indices freq_indices = dmrsIndices % symbol_size # Get frequency indices for i in range(len(freq_indices)): dmrs_mask[freq_indices[i], symbol_indices[i]] = True Following is the breakdown of the code and description dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’): This function call retrieves the standard indices for the PBCH DMRS resource elements. The locations of these DMRS symbols depend on the detected_NID. The function likely returns these as linear indices (e.g., 0 to 959 for a 240x4 grid) relative to the start of the SSB grid. The style=‘matlab’ argument likely specifies a particular indexing convention. symbol_size = nrbSSB * 12: Calculates the number of subcarriers within one OFDM symbol of the SSB (20 RBs * 12 subcarriers/RB = 240). This value represents the size of the frequency dimension. symbol_indices = dmrsIndices // symbol_size: This performs integer division of the linear dmrsIndices by the symbol_size. This effectively converts the linear index into the corresponding OFDM symbol index (0, 1, 2, or 3) within the 4-symbol SSB structure. freq_indices = dmrsIndices % symbol_size: This calculates the modulo (remainder) of the linear dmrsIndices divided by the symbol_size. This remainder gives the corresponding frequency index (subcarrier index, ranging from 0 to 239) within that OFDM symbol. for i in range(len(freq_indices)):: This loop iterates through all the calculated DMRS indices (the number of DMRS symbols within the SSB). dmrs_mask[freq_indices[i], symbol_indices[i]] = True: Inside the loop, for each DMRS symbol (i), this line takes its calculated frequency index (freq_indices[i]) and symbol index (symbol_indices[i]) and sets the corresponding element in the dmrs_mask to True. After the loop completes, all PBCH DMRS locations are marked True in the dmrs_mask. # Get PBCH indices This code identifies all the potential time-frequency locations (resource elements) within the 4-symbol SSB grid (rxGrid) that are designated for carrying the actual Physical Broadcast Channel (PBCH) data. It calculates the specific subcarrier and OFDM symbol index for each of these potential PBCH locations based on the detected Physical Cell ID (detected_NID) and marks these positions as True in the pbch_mask. Note that this initial marking includes resource elements that are also used for DMRS. pbchIndices = nrPBCHIndices(detected_NID) pbch_symbol_indices = pbchIndices // symbol_size pbch_freq_indices = pbchIndices % symbol_size for i in range(len(pbch_freq_indices)): pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]] = True Following is the breakdown of the code and description pbchIndices = nrPBCHIndices(detected_NID): This function call retrieves the standard indices for all resource elements allocated to the PBCH (data and potential DMRS overlaps). The specific locations depend on the detected_NID. These are likely returned as linear indices (e.g., 0-959) relative to the start of the 240x4 SSB grid. pbch_symbol_indices = pbchIndices // symbol_size: Calculates the OFDM symbol index (0, 1, 2, or 3) for each PBCH resource element index by performing integer division of the linear pbchIndices by symbol_size (which is 240, the number of subcarriers per symbol). PBCH data primarily resides in symbols 1 and 3 of the SSB. pbch_freq_indices = pbchIndices % symbol_size: Calculates the frequency index (subcarrier index, 0-239) for each PBCH resource element index by taking the modulo of the linear pbchIndices with symbol_size (240). for i in range(len(pbch_freq_indices)):: This loop iterates through all the resource element indices allocated for the PBCH. pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]] = True: Inside the loop, for each PBCH location (i), it uses the calculated frequency index (pbch_freq_indices[i]) and symbol index (pbch_symbol_indices[i]) to set the corresponding element in the pbch_mask to True. This marks all potential PBCH locations, including those that will later be identified as DMRS-only. # Remove DMRS positions from PBCH mask to avoid overlap This line performs a logical operation to refine the pbch_mask. Its purpose is to ensure that the final pbch_mask only identifies the resource elements carrying actual PBCH data, by explicitly removing any locations that are occupied by the PBCH DMRS. pbch_mask = pbch_mask & ~dmrs_mask Following is the breakdown of the code and description pbch_mask = pbch_mask & ~dmrs_mask: This performs an element-wise logical AND operation between two boolean masks: pbch_mask: At this point, it contains True for all resource elements designated for PBCH (including potential overlaps with DMRS). dmrs_mask: Contains True only at the locations of DMRS symbols. ~dmrs_mask: The ~ (tilde) is a logical NOT operator. It inverts dmrs_mask, resulting in a mask that is True everywhere except at the DMRS locations, where it is False. &: The logical AND operator compares pbch_mask and ~dmrs_mask element by element. The result for each element is True only if the element is True in both masks. If an element was True in the original pbch_mask (part of PBCH allocation) AND True in ~dmrs_mask (meaning it’s not a DMRS location), the result is True. If an element was True in the original pbch_mask BUT False in ~dmrs_mask (meaning it is a DMRS location), the result is False. Result: The pbch_mask is updated so that it now contains True only for the resource elements carrying PBCH data symbols, excluding those used for DMRS pilots. # Extract received signals This block extracts the actual received complex symbols for the Primary Synchronization Signal (PSS), Secondary Synchronization Signal (SSS), and the PBCH Demodulation Reference Signal (DMRS) from the main rxGrid. It uses the specific frequency and symbol indices determined in previous steps to pinpoint these signals within the 4-symbol SSB grid structure. The resulting arrays (pssRx, sssRx, dmrsRx) contain the demodulated values for each respective signal. pssRx = rxGrid[pss_freq_indices, 0] sssRx = rxGrid[sss_freq_indices, 2] dmrsRx = rxGrid[freq_indices, symbol_indices] Following is the breakdown of the code and description pssRx = rxGrid[pss_freq_indices, 0]: Extracts the PSS symbols. It indexes the rxGrid using: pss_freq_indices: An array holding the subcarrier indices for the PSS. 0: The index for the first OFDM symbol (where PSS is located). The resulting 1D array pssRx contains the complex values received at the PSS locations. sssRx = rxGrid[sss_freq_indices, 2]: Extracts the SSS symbols. It indexes the rxGrid using: sss_freq_indices: An array holding the subcarrier indices for the SSS. 2: The index for the third OFDM symbol (where SSS is located). The resulting 1D array sssRx contains the complex values received at the SSS locations. Note: This likely overwrites the previously normalized sssRx used for detection, now storing the values directly from the scaled rxGrid. dmrsRx = rxGrid[freq_indices, symbol_indices]: Extracts the PBCH DMRS symbols using advanced NumPy indexing. freq_indices: An array containing the subcarrier index for each DMRS symbol. symbol_indices: An array (same length as freq_indices) containing the OFDM symbol index for each corresponding DMRS symbol. NumPy uses these paired arrays to pick out the complex values from rxGrid at each specified (frequency, symbol) coordinate corresponding to a DMRS symbol. The resulting 1D array dmrsRx holds the complex values received at the PBCH DMRS locations. # Extract PBCH signals (excluding DMRS positions) This block carefully extracts the received complex symbols that correspond only to the actual Physical Broadcast Channel (PBCH) data, explicitly excluding the symbols used for the PBCH DMRS (Demodulation Reference Signal). It achieves this by iterating through the list of all potential PBCH resource element locations but only selecting those that are marked as True in the refined pbch_mask (where DMRS locations have already been set to False). The complex symbols from these validated PBCH data locations are then gathered from the rxGrid into the pbchRx array. pbch_freq_indices_no_dmrs = [] pbch_symbol_indices_no_dmrs = [] for i in range(len(pbch_freq_indices)): if pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]]: # Only include if not overlapping with DMRS pbch_freq_indices_no_dmrs.append(pbch_freq_indices[i]) pbch_symbol_indices_no_dmrs.append(pbch_symbol_indices[i]) pbchRx = rxGrid[pbch_freq_indices_no_dmrs, pbch_symbol_indices_no_dmrs] Following is the breakdown of the code and description pbch_freq_indices_no_dmrs = []: Initializes an empty list to collect the frequency indices (subcarrier numbers) of the resource elements carrying only PBCH data. pbch_symbol_indices_no_dmrs = []: Initializes a corresponding empty list to collect the OFDM symbol indices for those PBCH data resource elements. for i in range(len(pbch_freq_indices)):: This loop iterates through all the indices (pbch_freq_indices and pbch_symbol_indices) that were initially determined as potential PBCH locations (before DMRS removal). if pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]]:: Inside the loop, this condition checks the value within the refined pbch_mask at the specific location defined by the current frequency index (pbch_freq_indices[i]) and symbol index (pbch_symbol_indices[i]). Since pbch_mask was previously updated to be False at DMRS locations (via pbch_mask & ~dmrs_mask), this condition will only be True if the current location is not a DMRS location, meaning it contains actual PBCH data. pbch_freq_indices_no_dmrs.append(pbch_freq_indices[i]): If the if condition is met (the location is confirmed to be PBCH data only), the current frequency index is added to the pbch_freq_indices_no_dmrs list. pbch_symbol_indices_no_dmrs.append(pbch_symbol_indices[i]): Similarly, the corresponding symbol index is added to the pbch_symbol_indices_no_dmrs list. pbchRx = rxGrid[pbch_freq_indices_no_dmrs, pbch_symbol_indices_no_dmrs]: After the loop has filtered all the indices, this line uses advanced NumPy indexing. It takes the lists of validated frequency and symbol indices (pbch_freq_indices_no_dmrs, pbch_symbol_indices_no_dmrs) and uses them to extract the corresponding complex values directly from the rxGrid. The final 1D array pbchRx contains only the received complex symbols for the PBCH data, ready for the next processing stages like equalization and decoding. |
|---|
SSB 的基本参数
这里定义了 SSB 的基本参数:nrbSSB(带宽 = 20 RB)、scsSSB(子载波间隔,应为 15 kHz)、nSlot(初始时隙假设)以及 rxSampleRate。
nrbSSB = 20
scsSSB = 15 * 2**(mu)
nSlot = 0
rxSampleRate = fs
TimingOffset 估计
这一步旨在输入波形中找到一个精确的起点(以采样点数计的 timingOffset),使其与同步信号块(SSB)的起始位置准确对齐。做法是利用已检测到的 NID2 生成对应的主同步信号(PSS),再将这个已知的 PSS 信号与接收波形做相关,找到最佳匹配点。
refGrid = np.zeros((nrbSSB*12, 2), np.complex128)
refGrid[nrPSSIndices(), 1] = nrPSS(detected_NID2)
timingOffset = nrTimingEstimate(waveform = waveform, nrb = nrbSSB, scs = scsSSB, initialNSlot = nSlot, refGrid = refGrid, SampleRate = rxSampleRate)
以下是该代码块的逐行解析
- refGrid = np.zeros((nrbSSB*12, 2), np.complex128): 创建一个较小的空资源网格。它覆盖 SSB 带宽(20 RB × 12 子载波/RB = 240 个子载波)和 2 个 OFDM 符号。
- refGrid[nrPSSIndices(), 1] = nrPSS(detected_NID2): 这一行基于先前找到的 detected_NID2 生成 PSS 序列,并将其放到 refGrid 第一个符号(索引 1)中相应的子载波位置(nrPSSIndices())上。这样就构造出一个只包含 PSS、且位于 SSB 结构中预期符号位置的参考信号。
- timingOffset = nrTimingEstimate(…): 该函数执行核心的定时估计。
- 它以波形、SSB 参数(nrb、scs、SampleRate)、时隙上下文(initialNSlot)以及只包含 PSS 的 refGrid 作为输入。
- 该函数的工作方式很可能是将参考 PSS(来自 refGrid)与时域波形做相关,找到相关峰出现的时间索引,即 SSB 的起点。
- 得到的采样点索引保存在 timingOffset 变量中,随后将用于 OFDM 解调。
解调约 8 个符号,只需至少 5 个
这一代码块先取得已完成时间同步的输入信号(从 timingOffset 处开始的 waveform),把其中一段必定包含同步信号块(SSB)的内容从时域转换到频域表示(资源网格),然后从该网格中精确提取构成 SSB 的那 4 个 OFDM 符号,为后续的信号提取和译码等分析做好准备。
rxGrid = nrOFDMDemodulate(waveform = waveform[timingOffset:][:np.min((len(waveform), 2048*8))], nrb = nrbSSB, scs = scsSSB, initialNSlot = nSlot, SampleRate=rxSampleRate, CyclicPrefixFraction=0.5)
rxGrid = rxGrid[:,1:5]
以下是代码的逐段解析
- rxGrid = nrOFDMDemodulate(…): 该函数执行 OFDM 解调。
- 它处理的波形段从计算得到的 timingOffset 开始,延续约 8 个符号的时长(2048*8 个采样点,若波形提前结束则相应缩短)。
- 它使用 SSB 特有的参数(nrbSSB、scsSSB、rxSampleRate)来正确解读信号结构。
- 输出 rxGrid 是一个二维数组,包含解调后的各 OFDM 符号(列,约 8 个)上每个子载波(行)的复数值。
- rxGrid = rxGrid[:, 1:5]: 这一行使用 NumPy 切片选取 rxGrid 的特定部分。
- : 选取所有行(nrbSSB=20 时的全部 240 个子载波)。
- 1:5 选取索引为 1、2、3、4 的列(OFDM 符号)。
- 这样就精确地隔离出按 5G 标准构成 SSB 的 4 个 OFDM 符号,丢弃之前(索引 0)和之后(索引 5、6、7)多解调出来的符号。
- rxGrid 变量随后被更新为只包含这 4 个相关符号。
按 FFT 点数及附加因子归一化,以获得正确的星座图缩放
这一行对解调得到的 rxGrid 中所有复数值的幅度进行缩放。其主要目的是调整整体功率水平,使接收信号星座点(PSS、SSS、DMRS、PBCH)与标准中的预期位置正确对齐——这些位置通常幅度在 1 左右——从而简化可视化以及信道估计、符号解调等后续处理。
rxGrid = rxGrid / (np.sqrt(Nfft) * 3.0) # Factor of 3 to match expected constellation points
- rxGrid = rxGrid / …: 对整个 rxGrid 数组执行逐元素除法。网格中的每个复数值都要除以计算得到的归一化因子。
- np.sqrt(Nfft): 这部分执行标准的 OFDM 归一化。OFDM 解调过程(涉及 FFT 运算)会引入一个与 FFT 点数(Nfft,本例中很可能是 2048)相关的缩放因子。除以 Nfft 的平方根可以补偿 FFT 运算固有的这一缩放。
-
- 3.0: 这是额外的经验缩放因子。
- 其目的:进一步调整幅度比例,使接收符号在视觉上与理想星座点匹配(例如位于实轴/虚轴 +1/-1 处的 QPSK 点,或归一化到单位幅度)。
获取 SSS 索引并转换为频率索引
这一代码块的目标是从解调后的 SSB 资源网格(rxGrid)中分离出辅同步信号(SSS)。它先确定 SSS 所在的具体资源粒子,提取相应的接收复符号,然后对这些符号施加特定的归一化,很可能是为了后续用于检测 NID1 的相关运算做准备。
sssIndices = nrSSSIndices()
sssRx = nrExtractResources(sssIndices, rxGrid)
sssRx /= np.max((sssRx.real.max(), sssRx.imag.max())) # scale sssRx symbols individually
- sssIndices = nrSSSIndices(): 该函数返回一个标准化的索引列表(或数组),表示 4 符号 SSB 网格中 SSS 所在的具体时频位置(资源粒子)。SSS 位于 SSB 的第 3 个符号(索引 2)。
- sssRx = nrExtractResources(sssIndices, rxGrid): 该函数利用 sssIndices 在 rxGrid(包含 4 个 SSB 符号)中查找并提取相应的复数值。结果 sssRx 是一个向量,包含专属于 SSS 的接收符号。
- sssRx /= np.max((sssRx.real.max(), sssRx.imag.max())): 这一行对提取出的 sssRx 符号执行一种特定的归一化:
- 它找出 sssRx 所有符号实部的最大值和虚部的最大值。
- 取两者中较大的一个(即星座沿实轴或虚轴方向的最大延伸)。
- 将 sssRx 中的每个符号都除以这一个最大值。
- 其效果是缩放接收到的 SSS 星座,使得沿实轴或虚轴离原点最远的点恰好落在该轴的 +1 处(假设该最大值为正)。这种归一化旨在调整相关运算之前的整体幅度比例,降低其对增益变化的敏感度,同时以峰值作为参考。
用于 NID1 检测的 SSS 相关运算
本节确定 5G 小区完整物理小区 ID(NcellID)所需的剩余分量(NID1)。做法是将之前提取的辅同步信号(SSS)接收符号(sssRx)与所有可能的参考 SSS 序列逐一比较。与接收 SSS 匹配最好的参考序列即揭示了正确的 NID1,再结合已知的 NID2 即可得到完整的 NcellID。
sssEst = np.zeros(336)
for NID1 in range(335):
ncellid = (3*NID1) + detected_NID2
sssRef = nrSSS(ncellid)
sssEst[NID1] = np.abs(np.vdot(sssRx, sssRef))
detected_NID1 = np.argmax(sssEst)
detected_NID = detected_NID1*3 + detected_NID2
- sssEst = np.zeros(336): 初始化一个名为 sssEst 的零数组,大小为 336,用于存储每个可能 NID1 假设(NID1 取值 0 到 335)的相关结果。
- for NID1 in range(335):: 该循环遍历候选的 NID1 取值。注意:range(335) 生成的值为 0 到 334。如果需要测试 NID1 的完整范围(0-335),此循环理想上应写成 range(336)。按现在的写法,它只测试 0 到 334。
- ncellid = (3*NID1) + detected_NID2: 在循环内,这一行基于当前测试的 NID1 和先前检测到的 detected_NID2 计算一个候选的完整物理小区 ID(ncellid)。这遵循 5G 标准公式:NcellID = 3 * NID1 + NID2。
- sssRef = nrSSS(ncellid): 生成与候选 ncellid 对应的理论参考 SSS 序列。每个 NcellID(0-1007)都有唯一的 SSS 序列。
- sssEst[NID1] = np.abs(np.vdot(sssRx, sssRef)): 这是核心的相关步骤:
- np.vdot(sssRx, sssRef) 计算接收 SSS 符号(sssRx)与参考 SSS 序列(sssRef)之间的复内积,衡量两者的匹配程度。
- np.abs(…) 取复相关结果的幅度。幅度越大表示匹配越强。
- 结果存储在 sssEst 数组中与当前 NID1 对应的索引位置。
- detected_NID1 = np.argmax(sssEst): 循环测试完所有 NID1 假设(本例中为 0-334)后,这一行找出 sssEst 中值最大的索引,它代表最可能的 NID1。
- detected_NID = detected_NID1*3 + detected_NID2: 这最后的计算用标准公式将 detected_NID1 与先前已知的 detected_NID2 合并,得到最终检测到的物理小区 ID(detected_NID)。
用于 ibar_SSB 检测的 DMRS 相关运算
本节确定接收到的同步信号块(SSB)在一个突发中相对其他潜在 SSB 的具体时间索引(ibar_SSB)。做法是将与物理广播信道(PBCH)相关的解调参考信号(DMRS)接收符号,与为不同可能 ibar_SSB 取值生成的参考 DMRS 序列进行比较。与接收 DMRS 匹配最好的参考序列所对应的 ibar_SSB 值即揭示了该 SSB 的索引,这对后续的 PBCH 译码步骤(尤其是解扰)至关重要。
dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’)
xcorrPBCHDMRS = np.empty(7)
for ibar_SSB in range(7):
PBCHDMRS = nrPBCHDMRS(detected_NID, ibar_SSB)
xcorrPBCHDMRS[ibar_SSB] = np.abs(np.vdot(nrExtractResources(dmrsIndices, rxGrid), PBCHDMRS))
ibar_SSB = np.argmax(np.abs(xcorrPBCHDMRS))
以下是代码解析与说明
- dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’): 该函数调用获取 4 符号 SSB 网格中 PBCH DMRS 符号所在的具体资源粒子索引。DMRS 的位置取决于物理小区 ID(detected_NID)。style=‘matlab’ 参数很可能用于确保索引遵循特定约定(例如 1 起始索引或特定排序),与 MATLAB 实现兼容。
- xcorrPBCHDMRS = np.empty(7): 初始化一个空的 NumPy 数组,用于存储正在测试的 7 个不同 ibar_SSB 假设(索引 0 到 6)的相关结果。
- for ibar_SSB in range(7):: 该循环遍历 ibar_SSB 假设,测试 0、1、2、3、4、5、6。注:ibar_SSB 的实际最大值(Lmax)随频段而异(4、8 或 64),但 PBCH 使用的加扰序列通常只取决于 ibar_SSB mod 8。测试 0-6 已覆盖相当大的可能范围。
- PBCHDMRS = nrPBCHDMRS(detected_NID, ibar_SSB): 在循环内,为当前 ibar_SSB 假设生成参考 PBCH DMRS 序列。序列本身取决于 NID,其加扰则取决于 ibar_SSB。
- xcorrPBCHDMRS[ibar_SSB] = np.abs(np.vdot(nrExtractResources(dmrsIndices, rxGrid), PBCHDMRS)): 执行相关运算:
- nrExtractResources(dmrsIndices, rxGrid): 从 rxGrid 中 dmrsIndices 指定的位置提取接收 DMRS 符号。
- np.vdot(…): 计算提取出的接收 DMRS 与生成的参考 DMRS(PBCHDMRS)之间的复内积(相关)。
- np.abs(…): 取相关结果的幅度。
- 幅度存储在 xcorrPBCHDMRS 数组中与当前 ibar_SSB 假设对应的索引位置。
- ibar_SSB = np.argmax(np.abs(xcorrPBCHDMRS)): 测试完 0 到 6 的假设后,这一行找出 xcorrPBCHDMRS 中相关幅度最大的索引(0-6),并将其赋给 ibar_SSB 变量,代表在被测可能性中检测到的 SSB 时间索引。
创建 PSS 与 SSS 的掩码
本节初始化若干布尔数组(掩码),其维度与 rxGrid(包含 SSB 的 4 个符号)相同。这些掩码(pss_mask、sss_mask、dmrs_mask、pbch_mask)的作用类似于模板,初始时全部为 False。后续步骤将用它们标记 rxGrid 中每类信号(PSS、SSS、DMRS、PBCH)所在的具体位置(资源粒子)。
pss_mask = np.zeros_like(rxGrid, dtype=bool)
sss_mask = np.zeros_like(rxGrid, dtype=bool)
dmrs_mask = np.zeros_like(rxGrid, dtype=bool)
pbch_mask = np.zeros_like(rxGrid, dtype=bool)
- pss_mask = np.zeros_like(rxGrid, dtype=bool): 创建一个与 rxGrid 形状完全相同的 NumPy 数组 pss_mask。dtype=bool 确保它包含布尔值,zeros_like 将所有元素初始化为 False。该掩码之后用于标识 PSS 的资源粒子。
- sss_mask = np.zeros_like(rxGrid, dtype=bool): 类似地创建 sss_mask,一个与 rxGrid 同形状、初始化为全 False 的布尔数组,用于标记 SSS 的位置。
- dmrs_mask = np.zeros_like(rxGrid, dtype=bool): 创建 dmrs_mask,另一个与 rxGrid 同形状、初始化为全 False 的布尔数组,用于标记 PBCH DMRS 的位置。
- pbch_mask = np.zeros_like(rxGrid, dtype=bool): 创建最后一个布尔数组 pbch_mask,与 rxGrid 同形状、初始化为全 False,用于标记 PBCH 数据符号的位置。
获取 SSB 网格中的 PSS 索引
这一代码块确定主同步信号(PSS)在 SSB 带宽内占用的确切频率位置(子载波索引),然后将此前创建的 pss_mask 中 SSB 网格第一个符号内的这些频率位置标记为 True。
pssIndices = nrPSSIndices()
pss_freq_indices = pssIndices % (nrbSSB * 12) # Convert to frequency indices for SSB grid
pss_mask[pss_freq_indices, 0] = True # PSS is in first symbol
- pssIndices = nrPSSIndices(): 该函数获取 PSS 所在的标准资源粒子索引。这些索引定义了 SSB 的 20 个资源块共 240 个子载波中哪些具体子载波承载 PSS 信号。
- pss_freq_indices = pssIndices % (nrbSSB * 12): 这一行确保索引被正确映射到 rxGrid 的频率维度内。
- nrbSSB * 12 计算 SSB 带宽内的子载波总数(20 × 12 = 240)。
- 取模运算符(%)将 pssIndices(若尚未是相对 SSB 的 0 起始索引)映射到 0-239 范围内,即 rxGrid 中的频率索引。结果保存在 pss_freq_indices 中。
- pss_mask[pss_freq_indices, 0] = True: 这条命令修改 pss_mask。
- 它用 pss_freq_indices 选择 PSS 对应的行(子载波)。
- 它用 0 选择 4 符号掩码中的第一列(索引为 0 的 OFDM 符号),因为 PSS 出现在 SSB 结构的第一个符号中。
- 它把 pss_mask 中这些特定行/列交点处的值设为 True,标记出 PSS 的位置。
获取 SSB 网格中的 SSS 索引
与 PSS 掩码类似,这一代码块确定辅同步信号(SSS)在 SSB 带宽内使用的具体频率位置(子载波索引),然后将 sss_mask 中 SSB 网格第三个符号(索引 2)内的这些频率位置标记为 True。
sss_freq_indices = sssIndices % (nrbSSB * 12) # Convert to frequency indices for SSB grid
sss_mask[sss_freq_indices, 2] = True # SSS is in third symbol (index 2)
- sss_freq_indices = sssIndices % (nrbSSB * 12): 计算 SSS 在 SSB 网格 0-239 子载波范围内的频率索引。
- sssIndices: 该变量(应在此前定义,例如通过 sssIndices = nrSSSIndices())包含 SSS 的标准资源粒子索引。
- nrbSSB * 12: 计算 SSB 带宽内的子载波总数(240)。
- 取模运算符(%)将 sssIndices 映射到 0-239 范围,对应 rxGrid 和各掩码的频率维度(行)。结果保存在 sss_freq_indices 中。
- sss_mask[sss_freq_indices, 2] = True: 这条命令修改 sss_mask。
- 它用 sss_freq_indices 选择 SSS 所在的行(子载波)。
- 它用 2 选择 4 符号掩码中的第三列(索引为 2 的 OFDM 符号),因为在标准 SSB 结构中 SSS 在第三个符号中发送。
- 它把 sss_mask 中这些特定 SSS 位置(sss_freq_indices 指定的行、第 2 列)的值设为 True。
获取 PBCH DMRS 索引
这一代码块确定 4 符号 SSB 网格(rxGrid)中 PBCH DMRS 发送所在的精确时频位置(资源粒子)。它基于检测到的物理小区 ID(detected_NID)计算每个 DMRS 符号对应的子载波和 OFDM 符号索引,并在 dmrs_mask 中把这些位置标记为 True。
symbol_size = nrbSSB * 12
symbol_indices = dmrsIndices // symbol_size # Get symbol indices
freq_indices = dmrsIndices % symbol_size # Get frequency indices
for i in range(len(freq_indices)):
dmrs_mask[freq_indices[i], symbol_indices[i]] = True
- dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’): 该函数调用获取 PBCH DMRS 资源粒子的标准索引。这些 DMRS 符号的位置取决于 detected_NID。函数很可能以线性索引(例如 240×4 网格的 0 到 959)形式返回它们,相对 SSB 网格起始位置。style=‘matlab’ 参数用于指定特定的索引约定。
- symbol_size = nrbSSB * 12: 计算 SSB 中一个 OFDM 符号内的子载波数(20 RB × 12 子载波/RB = 240)。该值代表频率维度的大小。
- symbol_indices = dmrsIndices // symbol_size: 将线性 dmrsIndices 对 symbol_size 做整数除法。这就把线性索引转换为 4 符号 SSB 结构中相应的 OFDM 符号索引(0、1、2 或 3)。
- freq_indices = dmrsIndices % symbol_size: 计算线性 dmrsIndices 除以 symbol_size 的余数。该余数给出该 OFDM 符号内相应的频率索引(子载波索引,范围 0 到 239)。
- for i in range(len(freq_indices)):: 该循环遍历所有计算出的 DMRS 索引(即 SSB 内的 DMRS 符号个数)。
- dmrs_mask[freq_indices[i], symbol_indices[i]] = True: 在循环内,对每个 DMRS 符号(i),这一行取其计算得到的频率索引(freq_indices[i])和符号索引(symbol_indices[i]),把 dmrs_mask 中相应的元素设为 True。循环结束后,所有 PBCH DMRS 位置都在 dmrs_mask 中被标记为 True。
获取 PBCH 索引
这一代码块识别 4 符号 SSB 网格(rxGrid)中所有分配用于承载实际物理广播信道(PBCH)数据的潜在时频位置(资源粒子)。它基于检测到的物理小区 ID(detected_NID)计算每个潜在 PBCH 位置对应的子载波和 OFDM 符号索引,并在 pbch_mask 中把这些位置标记为 True。注意,这一初始标记包含同时用于 DMRS 的资源粒子。
pbchIndices = nrPBCHIndices(detected_NID)
pbch_symbol_indices = pbchIndices // symbol_size
pbch_freq_indices = pbchIndices % symbol_size
for i in range(len(pbch_freq_indices)):
pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]] = True
- pbchIndices = nrPBCHIndices(detected_NID): 该函数调用获取分配给 PBCH 的所有资源粒子(包括此阶段可能与 DMRS 重叠的位置)的标准索引。具体位置取决于 detected_NID。它们很可能以线性索引(例如 240×4 SSB 网格的 0-959)形式返回。
- pbch_symbol_indices = pbchIndices // symbol_size: 将线性 pbchIndices 对 symbol_size(即每符号 240 个子载波)做整数除法,计算每个 PBCH 资源粒子索引对应的 OFDM 符号索引(0、1、2 或 3)。PBCH 数据主要位于 SSB 的符号 1 和符号 3。
- pbch_freq_indices = pbchIndices % symbol_size: 将线性 pbchIndices 对 symbol_size(240)取模,计算每个 PBCH 资源粒子索引的频率索引(子载波索引,0-239)。
- for i in range(len(pbch_freq_indices)):: 该循环遍历分配给 PBCH 的所有资源粒子索引。
- pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]] = True: 在循环内,对每个 PBCH 位置(i),它使用计算得到的频率索引(pbch_freq_indices[i])和符号索引(pbch_symbol_indices[i])把 pbch_mask 中相应元素设为 True。这标记了所有潜在的 PBCH 位置,包括稍后将被识别为仅 DMRS 的位置。
从 PBCH 掩码中移除 DMRS 位置以避免重叠
这一行通过逻辑运算细化 pbch_mask。其目的是确保最终的 pbch_mask 只标识承载实际 PBCH 数据的资源粒子,明确排除被 PBCH DMRS 占用的位置。
pbch_mask = pbch_mask & ~dmrs_mask
- pbch_mask = pbch_mask & ~dmrs_mask: 对两个布尔掩码执行逐元素的逻辑与运算:
- pbch_mask: 此时它对所有分配给 PBCH 的资源粒子为 True(包括可能与 DMRS 重叠的位置)。
- dmrs_mask: 仅在 DMRS 符号所在位置为 True。
- ~dmrs_mask: ~(波浪号)是逻辑非运算符。它将 dmrs_mask 取反,得到一个除 DMRS 位置外处处为 True 的掩码。
- &: 逻辑与运算符逐元素比较 pbch_mask 和 ~dmrs_mask。只有当元素在两个掩码中都为 True 时,结果才为 True。
- 如果一个元素在原始 pbch_mask 中为 True(属于 PBCH 分配),且在 ~dmrs_mask 中也为 True(即不是 DMRS 位置),结果为 True。
- 如果一个元素在原始 pbch_mask 中为 True,但在 ~dmrs_mask 中为 False(即是 DMRS 位置),结果为 False。
- 结果:pbch_mask 更新后只对承载 PBCH 数据符号的资源粒子为 True,排除了用作 DMRS 导频的位置。
提取接收信号
这一代码块从主 rxGrid 中提取主同步信号(PSS)、辅同步信号(SSS)和 PBCH 解调参考信号(DMRS)的实际接收复符号。它利用前面步骤确定的特定频率和符号索引,在 4 符号 SSB 网格结构中精确定位这些信号。得到的数组(pssRx、sssRx、dmrsRx)包含各信号对应的解调值。
pssRx = rxGrid[pss_freq_indices, 0]
sssRx = rxGrid[sss_freq_indices, 2]
dmrsRx = rxGrid[freq_indices, symbol_indices]
- pssRx = rxGrid[pss_freq_indices, 0]:
- 提取 PSS 符号。
- 它使用以下索引访问 rxGrid:
- pss_freq_indices: 保存 PSS 子载波索引的数组。
- 0: 第一个 OFDM 符号的索引(PSS 所在位置)。
- 得到的一维数组 pssRx 包含 PSS 位置处接收到的复数值。
- sssRx = rxGrid[sss_freq_indices, 2]:
- 提取 SSS 符号。
- sss_freq_indices: 保存 SSS 子载波索引的数组。
- 2: 第三个 OFDM 符号的索引(SSS 所在位置)。
- 得到的一维数组 sssRx 包含 SSS 位置处接收到的复数值。注:这很可能会覆盖之前用于检测的已归一化 sssRx,现在存储的是缩放后 rxGrid 中直接取出的值。
- dmrsRx = rxGrid[freq_indices, symbol_indices]:
- 使用 NumPy 高级索引提取 PBCH DMRS 符号。
- freq_indices: 包含每个 DMRS 符号子载波索引的数组。
- symbol_indices: 与 freq_indices 等长的数组,包含每个对应 DMRS 符号的 OFDM 符号索引。
- NumPy 使用这对数组从 rxGrid 中按每个指定的(频率,符号)坐标挑选出对应 DMRS 符号的复数值。
- 得到的一维数组 dmrsRx 保存 PBCH DMRS 位置处接收到的复数值。
提取 PBCH 信号(不含 DMRS 位置)
这一代码块谨慎地只提取对应实际物理广播信道(PBCH)数据的接收复符号,明确排除用于 PBCH 解调参考信号(DMRS)的符号。做法是遍历所有潜在 PBCH 资源粒子位置,但只选择在细化后的 pbch_mask(其中 DMRS 位置已被置为 False)中标记为 True 的那些位置。来自这些已确认 PBCH 数据位置的复符号随后从 rxGrid 收集到 pbchRx 数组中。
pbch_freq_indices_no_dmrs = []
pbch_symbol_indices_no_dmrs = []
if pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]]: # Only include if not overlapping with DMRS
pbch_freq_indices_no_dmrs.append(pbch_freq_indices[i])
pbch_symbol_indices_no_dmrs.append(pbch_symbol_indices[i])
pbchRx = rxGrid[pbch_freq_indices_no_dmrs, pbch_symbol_indices_no_dmrs]
- pbch_freq_indices_no_dmrs = []: 初始化一个空列表,用于收集仅承载 PBCH 数据的资源粒子的频率索引(子载波编号)。
- pbch_symbol_indices_no_dmrs = []: 初始化一个对应的空列表,用于收集这些 PBCH 数据资源粒子的 OFDM 符号索引。
- for i in range(len(pbch_freq_indices)):: 该循环遍历最初(移除 DMRS 之前)被确定为潜在 PBCH 位置的所有索引(pbch_freq_indices 和 pbch_symbol_indices)。
- if pbch_mask[pbch_freq_indices[i], pbch_symbol_indices[i]]:: 在循环内,这一条件检查细化后的 pbch_mask 中由当前频率索引(pbch_freq_indices[i])和符号索引(pbch_symbol_indices[i])定义的位置处的值。
- 由于 pbch_mask 此前已通过 pbch_mask & ~dmrs_mask 在 DMRS 位置被置为 False,该条件只有在当前位置不是 DMRS 位置(即包含实际 PBCH 数据)时才为 True。
- pbch_freq_indices_no_dmrs.append(pbch_freq_indices[i]): 如果条件满足(该位置确认为纯 PBCH 数据),则把当前频率索引加入 pbch_freq_indices_no_dmrs 列表。
- pbch_symbol_indices_no_dmrs.append(pbch_symbol_indices[i]): 同样,把相应的符号索引加入 pbch_symbol_indices_no_dmrs 列表。
- pbchRx = rxGrid[pbch_freq_indices_no_dmrs, pbch_symbol_indices_no_dmrs]: 循环过滤完所有索引后,这一行使用 NumPy 高级索引,以通过验证的频率和符号索引列表(pbch_freq_indices_no_dmrs、pbch_symbol_indices_no_dmrs)直接从 rxGrid 中提取相应的复数值。
- 最终的一维数组 pbchRx 只包含 PBCH 数据的接收复符号,可用于均衡和译码等下一阶段处理。 OFDM 解调
这一代码块对接收到的部分时域信号(waveform)执行 OFDM 解调。它实质上是把信号从时域变换回频域,组织成资源网格(rxGrid),其中每个元素表示特定 OFDM 符号期间特定子载波上的复数值。这一步是访问同步信号(如 PSS、SSS)和广播信道(PBCH)所必需的——它们发送在该网格结构中的特定资源粒子上。
| rxGrid = nrOFDMDemodulate( waveform = waveform[timingOffset:][:np.min((len(waveform), 2048*8))], nrb = nrbSSB, scs = scsSSB, initialNSlot = nSlot, SampleRate = rxSampleRate, CyclicPrefixFraction = 0.5 ) |
|---|
rxGrid = nrOFDMDemodulate(
waveform = waveform[timingOffset:][:np.min((len(waveform), 2048*8))],
nrb = nrbSSB,
scs = scsSSB,
initialNSlot = nSlot,
SampleRate = rxSampleRate,
CyclicPrefixFraction = 0.5
- rxGrid = nrOFDMDemodulate(…): 该函数调用执行 OFDM 解调过程。
- waveform = waveform[timingOffset:][:np.min((len(waveform), 2048*8))]: 选择要解调的输入时域波形的具体片段。
- waveform[timingOffset:]: 从 timingOffset 开始处理波形,该偏移此前(例如通过 PSS 相关)已计算得到,用于对齐同步信号块(SSB)的起点。
- [:np.min((len(waveform), 2048*8))]: 从偏移点开始取有限个采样点——足以覆盖约 8 个 OFDM 符号(假设 FFT 点数 Nfft=2048,20 MHz 信道的常见取值),但不超过波形剩余长度。这一时长足以容纳 SSB 的 4 个符号。
- nrb = nrbSSB: 以资源块数量指定解调带宽。nrbSSB 通常为 20,对应 SSB 的标准带宽。
- scs = scsSSB: 定义与被解调 SSB 相关联的子载波间隔(例如 15 kHz 或 30 kHz)。
- initialNSlot = nSlot: 指示解调的起始时隙编号上下文。
- SampleRate = rxSampleRate: 提供输入波形的采样率,这是解调器内部计算(如 FFT 加窗、符号定时)所必需的。
- CyclicPrefixFraction = 0.5: 该参数很可能与函数处理循环前缀移除的方式有关,可能定义了一个搜索窗口或符号有效部分的假设分数起点,有助于应对轻微的定时误差。 符号范围选择
| rxGrid = rxGrid[:,1:5] |
|---|
- 这选择 OFDM 符号 1 至 4,对应 SSB 的有效部分。
- SSB 的各成分(PSS、SSS、DMRS、PBCH)都位于这些符号中。 网格归一化
| rxGrid = rxGrid / (np.sqrt(Nfft) * 3.0) |
|---|
rxGrid = rxGrid / (np.sqrt(Nfft) * 3.0)
- 网格除以 FFT 点数进行归一化,以校正能量缩放。
- 额外的 3.0 因子是经验选取的,用于匹配预期的星座幅度(例如 ±1/√2 的 QPSK)。
- 若不做这一步,星座图的缩放将不正确,并可能影响解调精度。
SSB 资源网格 - 背景层
本节通过绘制不属于 PSS、SSS、DMRS 或 PBCH 的接收元素幅度,可视化 SSB 资源网格的背景层。它使用解调得到的频域网格 rxGrid,并应用 viridis 色图来突出显示未重叠的资源粒子。np.where 条件过滤掉所有已知信号位置,让观察者能够聚焦网格结构中未使用或残余的区域。
| ssb_data = np.abs(rxGrid) plt.imshow(np.where(~(pss_mask | sss_mask | dmrs_mask | pbch_mask), ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’, cmap=‘viridis’) |
|---|
ssb_data = np.abs(rxGrid)
plt.imshow(np.where(~(pss_mask | sss_mask | dmrs_mask | pbch_mask), ssb_data, np.nan),
aspect=‘auto’, interpolation=‘none’, cmap=‘viridis’)
- rxGrid 是从波形中提取的解调资源网格。
- ssb_data 包含接收资源粒子的幅度。
- 背景层使用 viridis 色图显示网格中所有未占用(非 PSS、非 SSS、非 DMRS、非 PBCH)的 RE。
- np.where(…) 确保该层只显示不重叠的 RE。
网格中的 PBCH 层
这部分可视化在 SSB 网格上以灰色色图叠加 PBCH(物理广播信道)的资源粒子。pbch_mask 标识 PBCH 符号在网格中的位置,这些值显示在已有的背景层之上。来自 ssb_data 的相应幅度只在掩码标记的位置渲染,从而清晰区分整体资源分配中的 PBCH 结构。
| plt.imshow(np.where(pbch_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’, cmap=‘gray’, vmin=0, vmax=1) |
|---|
plt.imshow(np.where(pbch_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’,
cmap=‘gray’, vmin=0, vmax=1)
- 该叠加层使用灰色色图突出 PBCH 的 RE。
- pbch_mask 是标识 PBCH RE 位置的布尔掩码。
- 它们连同各自的信号幅度一起渲染在背景层之上。
网格中的 DMRS、PSS、SSS 层
本节使用颜色编码的图层把 DMRS、PSS 和 SSS 的位置叠加到 SSB 资源网格上。DMRS 元素显示为红色,PSS 显示为蓝色(使用 ‘winter’ 色图),SSS 显示为黄橙色(使用 ‘YlOrBr’ 色图),各自由相应的布尔掩码标识。这些叠加层渲染在背景网格之上,使各参考信号成分在视觉上一目了然。np.where 条件确保只显示每种信号类型相关的资源粒子,从而在整体网格中有效隔离出它们的结构。
| plt.imshow(np.where(dmrs_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’, cmap=‘Reds’, vmin=0, vmax=1) plt.imshow(np.where(pss_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’, cmap=‘winter’, vmin=0, vmax=1) plt.imshow(np.where(sss_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’, cmap=‘YlOrBr’, vmin=0, vmax=1) |
|---|
plt.imshow(np.where(dmrs_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’,
cmap=‘Reds’, vmin=0, vmax=1)
plt.imshow(np.where(pss_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’,
cmap=‘winter’, vmin=0, vmax=1)
plt.imshow(np.where(sss_mask, ssb_data, np.nan), aspect=‘auto’, interpolation=‘none’,
cmap=‘YlOrBr’, vmin=0, vmax=1)
- 这些行为每个参考信号添加叠加图层:
- DMRS 为红色,
- PSS 标记为 (A),
- SSS 标记为 (C)。
- 各掩码(*_mask)定义 RE 位置,np.where 过滤掉无关的点。
PSS 星座图 - (D)
该图将接收符号与预期参考序列进行对比,可视化主同步信号(PSS)的星座。变量 pssRx 保存从解调资源网格中提取的接收 PSS 复值采样,pssRef 则是本地生成的参考 PSS 序列。散点图中,接收符号以红色半透明绘制,理想星座点用黑色 ‘x’ 标记。这样可以直观评估当前信道条件下接收机捕获 PSS 的准确程度。
| plt.scatter(pssRx.real, pssRx.imag, c=‘red’, alpha=0.6, s=30, marker=’.’, label=‘Received’) plt.scatter(pssRef.real, pssRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’) |
|---|
plt.scatter(pssRx.real, pssRx.imag, c=‘red’, alpha=0.6, s=30, marker=’.’, label=‘Received’)
plt.scatter(pssRef.real, pssRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’)
- pssRx 包含从 rxGrid 提取的接收 PSS 采样。
- pssRef 是本地生成的参考序列。
- 该散点图将接收 PSS 星座与理想星座进行对比。
SSS 星座图 - (E)
该子图显示辅同步信号(SSS)的星座,对比接收符号与参考符号。变量 sssRx 包含从解调网格提取的 SSS 采样,sssRef 是基于检测到的小区 ID 生成的理想 SSS 序列。图中用橙色圆点表示接收符号,黑色 ‘x’ 标记表示预期位置。通过对比两者,可以评估接收机在噪声和信道失真存在的情况下捕获并解调 SSS 的准确程度。
| plt.scatter(sssRx.real, sssRx.imag, c=‘orange’, alpha=0.6, s=30, marker=’.’, label=‘Received’) plt.scatter(sssRef.real, sssRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’) |
|---|
plt.scatter(sssRx.real, sssRx.imag, c=‘orange’, alpha=0.6, s=30, marker=’.’, label=‘Received’)
plt.scatter(sssRef.real, sssRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’)
- sssRx 是从网格提取的 SSS。
- sssRef 是相应的参考序列。
- 该图直观显示接收 SSS 与预期星座的吻合程度。
PBCH DMRS 星座图 - (F)
该图展示 PBCH DMRS(解调参考信号)的星座,对比接收符号与其期望值。数组 dmrsRx 保存用预定义 DMRS 索引从资源网格提取的 DMRS 采样,dmrsRef 则是基于检测到的 NID 和 ibar_SSB 生成的对应理想序列。接收点以红色绘制,参考点以黑色 ‘x’ 标记显示。这一对比对评估信道质量以及后续 PBCH 均衡中信道估计的准确性至关重要。
| plt.scatter(dmrsRx.real, dmrsRx.imag, c=‘red’, alpha=0.6, s=30, marker=’.’, label=‘Received’) plt.scatter(dmrsRef.real, dmrsRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’) |
|---|
plt.scatter(dmrsRx.real, dmrsRx.imag, c=‘red’, alpha=0.6, s=30, marker=’.’, label=‘Received’)
plt.scatter(dmrsRef.real, dmrsRef.imag, c=‘black’, s=20, marker=‘x’, label=‘Expected’)
- dmrsRx 包含用已知 DMRS 索引提取的接收 DMRS 采样。
- dmrsRef 基于检测到的 NID 和 ibar_SSB 生成。
- 对比两者有助于评估信道质量和估计性能。
PBCH 星座图 - (G)
该星座图显示排除 DMRS 位置后接收到的 PBCH 符号。pbchRx 中的数据点以灰色绘制,表示从资源网格捕获的原始 QPSK 调制 PBCH 值。这里没有绘制参考符号,因为发送的 PBCH 内容取决于编码后的系统信息比特,每次传输都可能不同。该图在不假设编码数据的情况下,直观呈现 PBCH 的调制质量及其受到的潜在损伤。
| plt.scatter(pbchRx.real, pbchRx.imag, c=‘gray’, alpha=0.6, s=30, marker=’.’, label=‘Received’) |
|---|
plt.scatter(pbchRx.real, pbchRx.imag, c=‘gray’, alpha=0.6, s=30, marker=’.’, label=‘Received’)
- pbchRx 包含接收的 PBCH 采样(不含 DMRS 的 RE)。
- 这里只绘制接收点(没有参考叠加),因为 QPSK 调制的 PBCH 符号随编码的系统信息比特而变化。 下一步是对作用于接收 5G NR PBCH 信号的信道估计与均衡过程进行详细的可视化。上排展示估计信道的关键特性:资源网格上的幅度和相位分布,以及反映信号质量的信道状态信息(CSI)值直方图。下排的星座图对比均衡前后的 PBCH 符号,展示符号清晰度及其与理想 QPSK 位置对齐程度的改善。最后的图突出显示均衡后的 DMRS 符号与其参考符号的对比,用于验证信道校正的准确性。总而言之,该图揭示了接收机对无线信道损伤的表征与补偿能力,从而恢复发送数据。

图注:(原页面未提供图示说明)
预处理与计算
| import matplotlib.patches as mpatches if not SKIP_EQUALIZATION: # Create reference grid with matching dimensions These lines prepare a template grid (refGrid) that mirrors the structure of the received SSB signal grid (rxGrid). This template grid will then be populated with the known reference signals (specifically the PBCH DMRS) at their correct locations. This refGrid, containing only the known DMRS pilots, is essential for performing channel estimation in the subsequent steps refGrid = np.zeros((nrbSSB12, 4), ‘complex’) dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’) Followings are the breakdown and description refGrid = np.zeros((nrbSSB12, 4), ‘complex’): This creates a new NumPy array named refGrid. (nrbSSB12, 4) specifies the shape of the grid: nrbSSB12: Calculates the number of rows (subcarriers), corresponding to the SSB bandwidth (20 RBs * 12 subcarriers/RB = 240). 4: Sets the number of columns to 4, matching the number of OFDM symbols in the processed rxGrid. ‘complex’ sets the data type of the array elements to complex numbers. np.zeros(…) initializes all elements in this 240x4 grid to zero (0+0j). This creates an empty grid ready to be filled with known reference symbols. dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’): This function call retrieves the resource element indices where the PBCH DMRS symbols are located within the SSB grid structure. The DMRS locations depend on the detected_NID. These dmrsIndices (likely linear indices) specify where in the refGrid the known DMRS sequence needs to be placed. The style=‘matlab’ argument pertains to the indexing format. # Set DMRS reference signals This line takes the known, ideal PBCH DMRS (Demodulation Reference Signal) sequence and places it into the correct time-frequency locations within the refGrid (which was previously initialized as an empty grid of zeros). This step creates a clean reference grid containing only the expected DMRS pilot symbols, which is crucial for comparing against the received grid (rxGrid) to estimate the radio channel conditions. nrSetResources(dmrsIndices, refGrid, nrPBCHDMRS(detected_NID, ibar_SSB)) Followings are the breakdown and description nrSetResources(dmrsIndices, refGrid, nrPBCHDMRS(detected_NID, ibar_SSB)): This function call performs the placement operation: nrPBCHDMRS(detected_NID, ibar_SSB): This part first generates the actual complex values of the ideal PBCH DMRS sequence. The sequence depends on the cell ID (detected_NID) and the SSB time index (ibar_SSB) which influences its scrambling. dmrsIndices: Provides the specific indices (resource element locations, determined earlier) where the generated DMRS symbols should be placed within the grid. refGrid: Specifies the target grid (the 240x4 grid of zeros) where the DMRS symbols will be inserted. nrSetResources(…): This function takes the generated DMRS symbols and inserts them into the refGrid at the locations specified by dmrsIndices. Locations not specified in dmrsIndices remain zero # Channel estimation using reference implementation method This code performs channel estimation, which is the process of figuring out how the radio channel altered the signal. It does this by comparing the received pilot symbols (DMRS) within rxGrid to the known, ideal DMRS symbols stored in refGrid. By analyzing the differences in amplitude and phase at these known points, the function estimates the channel’s effect (represented by H) across the entire time-frequency grid and also estimates the level of noise (nVar) present in the received signal. with np.errstate(divide=‘ignore’, invalid=‘ignore’): H, nVar = nrChannelEstimate(rxGrid=rxGrid, refGrid=refGrid) Followings are the breakdown and description with np.errstate(divide=‘ignore’, invalid=‘ignore’):: This is a Python context manager used to temporarily change how NumPy handles certain errors or warnings within the indented block. divide=‘ignore’: It tells NumPy to ignore warnings that would normally occur if division by zero happens during calculations. invalid=‘ignore’: It tells NumPy to ignore warnings related to invalid mathematical operations (like 0/0 which results in NaN - Not a Number). Reason: Channel estimation often involves dividing the received signal by the reference signal (rxGrid / refGrid). Since refGrid contains zeros everywhere except at DMRS locations, divisions by zero would occur. This context manager prevents NumPy from flooding the output with warnings, assuming the nrChannelEstimate function is designed to handle these zero divisions appropriately (e.g., by only performing the division where the reference is non-zero). H, nVar = nrChannelEstimate(rxGrid=rxGrid, refGrid=refGrid): This is the function call that performs the actual channel estimation. rxGrid=rxGrid: Provides the grid of received complex symbols (240x4). refGrid=refGrid: Provides the grid containing only the ideal DMRS symbols at their correct locations (and zeros elsewhere). nrChannelEstimate: This function takes the received and reference grids and calculates: H: An estimate of the channel frequency response. This is typically a complex array of the same shape as rxGrid (240x4). Each element H[f, t] represents the estimated multiplicative distortion (gain and phase shift) introduced by the channel on subcarrier f during OFDM symbol t. The function calculates the channel directly at the DMRS locations (e.g., H_dmrs = rxGrid[dmrs] / refGrid[dmrs]) and then interpolates/extrapolates this information across the rest of the grid. nVar: An estimate of the noise variance present in the received signal. This is often calculated by looking at the difference between the received signal and the expected signal (reference signal modified by the estimated channel H) at the pilot locations. # DMRS equalization This line performs a basic form of channel equalization specifically on the PBCH DMRS (Demodulation Reference Signal) symbols. It attempts to remove the distorting effects of the radio channel from the received DMRS symbols by dividing the received signal (rxGrid) by the estimated channel response (H). The resulting “channel-corrected” DMRS symbols are then extracted and stored. PBCHDMRS_wiped = nrExtractResources(dmrsIndices, rxGrid/H) Followings are the breakdown and description rxGrid / H: This performs element-wise division of the received signal grid (rxGrid) by the channel estimate grid (H) calculated in the previous step. Conceptually, if the received signal Y at a specific resource element is modeled as Y = H * X + Noise (where X is the transmitted symbol), then dividing Y by H gives Y / H = X + Noise / H. This division aims to reverse the channel’s multiplicative effect (H), thereby recovering an estimate of the originally transmitted symbol (X), albeit with potentially amplified noise (Noise / H). This technique is known as zero-forcing equalization. nrExtractResources(dmrsIndices, rxGrid / H): This function then takes the result of the element-wise division (rxGrid / H) and extracts the values only at the specific locations (dmrsIndices) corresponding to the PBCH DMRS symbols. PBCHDMRS_wiped = …: The extracted, equalized DMRS symbols are stored in the variable PBCHDMRS_wiped. These symbols should ideally resemble the original, known DMRS sequence, allowing for verification of the channel estimation and equalization process (e.g., by plotting their constellation). # PBCH equalization using MMSE This block performs channel equalization specifically on the symbols intended for the Physical Broadcast Channel (PBCH) data, using the Minimum Mean Square Error (MMSE) technique. Unlike simple zero-forcing, MMSE equalization considers both the estimated channel effect (H) and the estimated noise level (nVar) to calculate an equalization filter that optimally reverses the channel distortion while minimizing noise amplification. The outputs are the equalized PBCH symbols (pbch_eqed) ready for demodulation, and Channel State Information (csi) values indicating the quality/reliability of the channel at those locations. pbchIndices = nrPBCHIndices(detected_NID) pbch_eqed, csi = nrEqualizeMMSE(nrExtractResources(pbchIndices, rxGrid), nrExtractResources(pbchIndices, H), nVar) Followings are the breakdown and description pbchIndices = nrPBCHIndices(detected_NID): Retrieves the standard resource element indices corresponding to all locations allocated to the PBCH (including potential DMRS locations at this stage) based on the detected_NID. This is needed to extract the relevant received symbols and their corresponding channel estimates. pbch_eqed, csi = nrEqualizeMMSE(…): This is the function call that performs MMSE equalization and returns the results. nrExtractResources(pbchIndices, rxGrid): Extracts the complex values from the received grid (rxGrid) at all the potential PBCH locations specified by pbchIndices. This provides the input signal (Y) to the equalizer. nrExtractResources(pbchIndices, H): Extracts the complex channel estimates from the channel estimation grid (H) at the same potential PBCH locations. This provides the channel estimate (H_est) relevant to the PBCH symbols. nVar: Passes the previously estimated noise variance to the function. MMSE uses nVar to balance channel inversion against noise enhancement. nrEqualizeMMSE(…): This function implements the MMSE algorithm. For each PBCH resource element, it calculates an equalization coefficient (conceptually conj(H_est) / (|H_est|^2 + nVar)),并将相应的接收符号(Y)与之相乘。这一过程旨在有噪声存在时产生对原始发送符号的最佳估计。函数很可能在内部处理或忽略 pbchIndices 中包含的 DMRS 位置,以专注于数据符号。输出:pbch_eqed: 一维数组,包含均衡后 PBCH 数据符号的复数值,理想情况下应接近原始 QPSK 星座点。csi: 一维数组,包含每个对应均衡 PBCH 符号的信道状态信息(CSI)值。CSI 反映该特定资源粒子处信道的估计质量或可靠性(例如信噪比)。CSI 越高表示符号越可靠,这对后续的软判决译码很有价值。 # 计算误差矢量幅度(EVM) 这一行计算均衡后 PBCH 数据符号(pbch_eqed)的误差矢量幅度(EVM)。EVM 是量化数字调制信号质量的标准指标,通过测量实际接收星座点(均衡后)与理想目标位置之间的差异来衡量。EVM 值越低,表示信号越干净、失真和噪声越小。 evm = np.sum(np.abs(pbch_eqed - nrSymbolModulate(nrSymbolDemodulate(pbch_eqed, ‘QPSK’, 1, ‘hard’), ‘QPSK’))) / pbch_eqed.shape[0] 以下是解析与说明 nrSymbolDemodulate(pbch_eqed, ‘QPSK’, 1, ‘hard’): 对均衡后的 PBCH 符号(pbch_eqed)执行硬判决解调。对每个复符号,判断它与 4 个理想 QPSK 星座点中的哪一个最近,输出判决结果,很可能是表示所判符号的整数索引或比特对。 nrSymbolModulate(…, ‘QPSK’): 接收上一步的硬判决结果,将其映射回相应的理想复 QPSK 星座点值(例如假设标准归一化时的 (+/-1 +/- 1j)/sqrt(2) 这类点)。输出一个数组,包含每个接收符号对应的理想参考星座点。 pbch_eqed - nrSymbolModulate(…): 用实际接收并均衡后的符号(pbch_eqed)减去理想参考点(上文确定的),计算每个符号的误差矢量。结果是一个复数数组,每个元素表示一个误差矢量(幅度和相位差)。 np.abs(…): 计算每个复误差矢量的绝对值(幅度或长度)。 np.sum(…): 将所有误差矢量的幅度求和。 / pbch_eqed.shape[0]: 将误差幅度总和除以 PBCH 符号个数(pbch_eqed.shape[0] 给出数组大小)。 evm = …: 最终结果表示所有 PBCH 符号上误差矢量的平均幅度,赋给变量 evm。(注:EVM 通常以百分比或相对参考功率/幅度的 dB 值表示,但此计算得到的是平均绝对误差幅度。) |
|---|
import matplotlib.patches as mpatches
if not SKIP_EQUALIZATION:
创建尺寸匹配的参考网格
这些代码行准备一个模板网格(refGrid),使其结构与接收到的 SSB 信号网格(rxGrid)一致。随后将在该模板网格的正确位置填入已知的参考信号(具体是 PBCH DMRS)。这个只包含已知 DMRS 导频的 refGrid 是后续信道估计步骤的基础。
refGrid = np.zeros((nrbSSB*12, 4), ‘complex’)
以下是解析与说明
- refGrid = np.zeros((nrbSSB*12, 4), ‘complex’):
- 这创建了一个名为 refGrid 的新 NumPy 数组。
- (nrbSSB*12, 4) 指定网格的形状:
- nrbSSB*12: 计算行数(子载波数),对应 SSB 带宽(20 RB × 12 子载波/RB = 240)。
- 4: 列数设为 4,与处理后的 rxGrid 中的 OFDM 符号数一致。
- ‘complex’ 将数组元素的数据类型设为复数。
- np.zeros(…) 把这个 240×4 网格的所有元素初始化为零(0+0j)。这样便创建了一个待填充已知参考符号的空网格。
- dmrsIndices = nrPBCHDMRSIndices(detected_NID, style=‘matlab’):
- 该函数调用获取 PBCH DMRS 符号在 SSB 网格结构中的资源粒子索引。
- DMRS 的位置取决于 detected_NID。
- 这些 dmrsIndices(很可能是线性索引)指定了已知 DMRS 序列在 refGrid 中的放置位置。style=‘matlab’ 参数与索引格式有关。
设置 DMRS 参考信号
这一行把已知的理想 PBCH DMRS(解调参考信号)序列放置到 refGrid(此前初始化为零网格)中正确的时频位置上。这一步构造出一个只包含预期 DMRS 导频符号的干净参考网格,这对与接收网格(rxGrid)进行比较以估计无线信道状况至关重要。
nrSetResources(dmrsIndices, refGrid, nrPBCHDMRS(detected_NID, ibar_SSB))
- nrSetResources(dmrsIndices, refGrid, nrPBCHDMRS(detected_NID, ibar_SSB)): 该函数调用执行放置操作:
- nrPBCHDMRS(detected_NID, ibar_SSB): 这部分首先生成理想 PBCH DMRS 序列的实际复数值。该序列取决于小区 ID(detected_NID)以及影响其加扰的 SSB 时间索引(ibar_SSB)。
- dmrsIndices: 提供在网格中放置生成的 DMRS 符号的具体索引(资源粒子位置,此前已确定)。
- refGrid: 指定目标网格(240×4 的零网格),DMRS 符号将插入其中。
- nrSetResources(…): 该函数把生成的 DMRS 符号插入 refGrid 中 dmrsIndices 指定的位置。dmrsIndices 未覆盖的位置保持为零。
采用参考实现方法的信道估计
这段代码执行信道估计,即弄清无线信道对信号造成改变的过程。它把 rxGrid 中接收到的导频符号(DMRS)与 refGrid 中已知的理想 DMRS 符号进行比较。通过分析这些已知点上的幅度和相位差异,该函数估计信道在整个时频网格上的影响(用 H 表示),同时估计接收信号中的噪声水平(nVar)。
with np.errstate(divide=‘ignore’, invalid=‘ignore’):
H, nVar = nrChannelEstimate(rxGrid=rxGrid, refGrid=refGrid)
- with np.errstate(divide=‘ignore’, invalid=‘ignore’):: 这是一个 Python 上下文管理器,用于临时改变 NumPy 在缩进代码块内对某些错误或警告的处理方式。
- divide=‘ignore’: 告诉 NumPy 忽略计算过程中除以零时通常会出现的警告。
- invalid=‘ignore’: 告诉 NumPy 忽略与无效数学运算相关的警告(例如结果为 NaN——非数值——的 0/0)。
- 原因:信道估计通常需要用接收信号除以参考信号(rxGrid / refGrid)。由于 refGrid 除 DMRS 位置外处处为零,会发生除以零。该上下文管理器可避免 NumPy 用警告刷屏,前提是假设 nrChannelEstimate 函数已妥善处理这些除零情况(例如只在参考非零的位置执行除法)。
- H, nVar = nrChannelEstimate(rxGrid=rxGrid, refGrid=refGrid): 这是执行实际信道估计的函数调用。
- rxGrid=rxGrid: 提供接收复符号网格(240×4)。
- refGrid=refGrid: 提供只在其正确位置包含理想 DMRS 符号(其余为零)的网格。
- nrChannelEstimate: 该函数接收接收网格和参考网格,计算:
- H: 信道频率响应的估计值。通常是与 rxGrid 同形状(240×4)的复数数组。每个元素 H[f, t] 表示信道在 OFDM 符号 t 期间对子载波 f 引入的估计乘性失真(增益和相移)。函数直接在 DMRS 位置计算信道(例如 H_dmrs = rxGrid[dmrs] / refGrid[dmrs]),然后将这些信息插值/外推到网格的其余部分。
- nVar: 对接收信号中噪声方差的估计。通常通过观察导频位置上接收信号与期望信号(参考信号经估计信道 H 修正后)之间的差异来计算。
DMRS 均衡
这一行专门对 PBCH DMRS(解调参考信号)符号执行一种基本的信道均衡。它通过将接收信号(rxGrid)除以估计的信道响应(H),尝试从接收 DMRS 符号中消除无线信道的失真影响,然后提取并保存得到的”信道校正”DMRS 符号。
PBCHDMRS_wiped = nrExtractResources(dmrsIndices, rxGrid/H)
- rxGrid / H: 将接收信号网格(rxGrid)逐元素除以上一步计算得到的信道估计网格(H)。
- 概念上,若某个资源粒子处的接收信号 Y 建模为 Y = H * X + Noise(X 为发送符号),则 Y 除以 H 得到 Y / H = X + Noise / H。
- 这一除法旨在抵消信道的乘性影响(H),从而恢复原始发送符号(X)的估计值,尽管噪声可能被放大(Noise / H)。这种技术称为迫零均衡。
- nrExtractResources(dmrsIndices, rxGrid / H): 该函数随后对逐元素除法的结果(rxGrid / H)仅在 PBCH DMRS 符号对应的特定位置(dmrsIndices)提取数值。
- PBCHDMRS_wiped = …: 提取出的均衡后 DMRS 符号保存在变量 PBCHDMRS_wiped 中。理想情况下这些符号应接近原始已知 DMRS 序列,从而可对信道估计与均衡过程进行验证(例如绘制其星座图)。
采用 MMSE 的 PBCH 均衡
这一代码块使用最小均方误差(MMSE)技术,专门对物理广播信道(PBCH)数据符号执行信道均衡。与简单的迫零均衡不同,MMSE 均衡同时考虑估计的信道影响(H)和估计的噪声水平(nVar),计算出一个在最优地抵消信道失真的同时使噪声放大最小化的均衡滤波器。输出是可用于解调的均衡后 PBCH 符号(pbch_eqed),以及表示这些位置信道质量/可靠性的信道状态信息(csi)值。
pbch_eqed, csi = nrEqualizeMMSE(nrExtractResources(pbchIndices, rxGrid), nrExtractResources(pbchIndices, H), nVar)
- pbchIndices = nrPBCHIndices(detected_NID): 基于 detected_NID 获取分配给 PBCH 的所有位置(包括此阶段潜在的 DMRS 位置)对应的标准资源粒子索引。提取相关接收符号及其对应信道估计时需要用到它。
- pbch_eqed, csi = nrEqualizeMMSE(…): 这是执行 MMSE 均衡并返回结果的函数调用。
- nrExtractResources(pbchIndices, rxGrid): 从接收网格(rxGrid)中 pbchIndices 指定的所有潜在 PBCH 位置提取复数值,作为均衡器的输入信号(Y)。
- nrExtractResources(pbchIndices, H): 在信道估计网格(H)中相同潜在 PBCH 位置提取复信道估计值,为 PBCH 符号提供相关的信道估计(H_est)。
- nVar: 将先前估计的噪声方差传给函数。MMSE 用 nVar 在信道求逆与噪声放大之间取得平衡。
- nrEqualizeMMSE(…): 该函数实现 MMSE 算法。对每个 PBCH 资源粒子,它计算一个均衡系数(概念上为 conj(H_est) / (|H_est|^2 + nVar)),并将相应的接收符号(Y)与之相乘。这一过程旨在有噪声的情况下产生对原始发送符号的最佳估计。函数很可能在内部处理或忽略 pbchIndices 中包含的 DMRS 位置,以专注于数据符号。
- 输出:
- pbch_eqed: 一维数组,包含均衡后 PBCH 数据符号的复数值。理想情况下应接近原始 QPSK 星座点。
- csi: 一维数组,包含每个对应均衡 PBCH 符号的信道状态信息(CSI)值。CSI 反映该特定资源粒子处信道的估计质量或可靠性(例如信噪比)。CSI 越高表示符号越可靠,这对后续的软判决译码很有价值。
计算 EVM
这一行计算均衡后 PBCH 数据符号(pbch_eqed)的误差矢量幅度(EVM)。EVM 是量化数字调制信号质量的标准指标,通过测量实际接收星座点(均衡后)与理想目标位置之间的差异来衡量。EVM 值越低,表示信号越干净、失真和噪声越小。
evm = np.sum(np.abs(pbch_eqed - nrSymbolModulate(nrSymbolDemodulate(pbch_eqed, ‘QPSK’, 1, ‘hard’), ‘QPSK’))) / pbch_eqed.shape
- nrSymbolDemodulate(pbch_eqed, ‘QPSK’, 1, ‘hard’):
- 对均衡后的 PBCH 符号(pbch_eqed)执行硬判决解调。
- 对 pbch_eqed 中的每个复符号,判断它与 4 个理想 QPSK 星座点中的哪一个最近。
- 输出判决结果,很可能是表示所判符号的整数索引或比特对。
- nrSymbolModulate(…, ‘QPSK’):
- 接收上一步的硬判决结果。
- 将判决映射回相应的理想复 QPSK 星座点值(例如假设标准归一化时的 (+/-1 +/- 1j)/sqrt(2) 这类点)。
- 输出一个数组,包含每个接收符号对应的理想参考星座点。
- pbch_eqed - nrSymbolModulate(…):
- 用实际接收并均衡后的符号(pbch_eqed)减去理想参考点(上文确定的),计算每个符号的误差矢量。结果是一个复数数组,每个元素表示一个误差矢量(幅度和相位差)。
- np.abs(…):
- 计算每个复误差矢量的绝对值(幅度或长度)。
- np.sum(…):
- 将所有误差矢量的幅度求和。
- / pbch_eqed.shape:
- 将误差幅度总和除以 PBCH 符号个数(pbch_eqed.shape 给出数组大小)。
- evm = …:
- 最终结果表示所有 PBCH 符号上误差矢量的平均幅度,赋给变量 evm。(注:EVM 通常以百分比或相对参考功率/幅度的 dB 值表示,但此计算得到的是平均绝对误差幅度。)
信道估计幅度 - (A)
该图可视化估计信道矩阵的幅度,揭示每个资源粒子在信号经无线信道传播过程中经历的增益或衰减。信道矩阵 H 由 nrChannelEstimate 函数计算,它将接收网格与已知参考信号进行对比。对 H 取绝对值即可呈现时频网格上的信号强度变化,结果用色图渲染以突出接收强弱区域。这有助于评估 SSB 网格中不同区域的可靠性。
| ax_ch_mag = fig_eq.add_subplot(eq_grid[0, 0]) ch_mag_plot = ax_ch_mag.imshow(np.abs(H), origin=‘lower’, aspect=‘auto’, cmap=‘viridis’) |
|---|
ax_ch_mag = fig_eq.add_subplot(eq_grid[0, 0])
ch_mag_plot = ax_ch_mag.imshow(np.abs(H), origin=‘lower’, aspect=‘auto’, cmap=‘viridis’)
- H 是用以下方式计算的估计信道矩阵:
- np.abs(H) 给出每个复信道估计的幅度。
- 该图显示每个资源粒子经信道后的增益大小。
信道估计相位 - (B)
该图显示估计信道矩阵的相位分量,呈现信号在传输过程中相位被改变的情况。相位从复信道估计 H 中用 np.angle(H) 提取,并使用 HSV 色图可视化,以表示从 −π 到 π 的完整范围。网格上的相位变化可以揭示导致接收信号失真的频偏、多普勒频移或多径效应。这一可视化对理解无线信道引入的非幅度类损伤至关重要。
| ax_ch_phase = fig_eq.add_subplot(eq_grid[0, 1]) ch_phase_plot = ax_ch_phase.imshow(np.angle(H), origin=‘lower’, aspect=‘auto’, cmap=‘hsv’, vmin=-np.pi, vmax=np.pi) |
|---|
ax_ch_phase = fig_eq.add_subplot(eq_grid[0, 1])
ch_phase_plot = ax_ch_phase.imshow(np.angle(H), origin=‘lower’, aspect=‘auto’, cmap=‘hsv’,
vmin=-np.pi, vmax=np.pi)
- np.angle(H) 提取每个信道估计的相位。
- HSV 色图有助于可视化 −π 到 π 之间的相位谱。
- 相位失真可能意味着存在频偏或多径效应。
CSI 分布(信道状态信息)- (C)
该直方图可视化 MMSE 均衡过程中获得的信道状态信息(CSI)值分布。CSI 反映每个均衡后 PBCH 符号的可靠性或置信度,由 nrEqualizeMMSE 函数与均衡信号一同计算。通过绘制所有 PBCH 资源粒子上 CSI 值的频率分布,该图以统计视角展示信道估计的效果,以及当前条件下每个解调比特的可信程度。
| ax_csi = fig_eq.add_subplot(eq_grid[0, 2]) ax_csi.hist(csi, bins=30, color=‘green’, alpha=0.7) |
|---|
ax_csi = fig_eq.add_subplot(eq_grid[0, 2])
ax_csi.hist(csi, bins=30, color=‘green’, alpha=0.7)
- csi 在 MMSE 均衡过程中计算:
- pbch_eqed, csi = nrEqualizeMMSE(…)
- 直方图显示 PBCH 各 RE 上 CSI 值的分布,反映每个均衡后符号的可靠性或置信度。
均衡前的 PBCH 星座图 - (D)
该星座图展示未做任何信道均衡时的接收 PBCH 符号,直观呈现信号在传输中受到的原始失真。变量 pbchRx 保存从资源网格提取(排除 DMRS 位置)的 PBCH 采样,以蓝色绘制。作为对比,四个理想 QPSK 星座点以红色显示,作为参考以突出接收符号因衰落、噪声和干扰等信道效应而偏离的程度。
| ax_before = fig_eq.add_subplot(eq_grid[1, 0]) ax_before.scatter(pbchRx.real, pbchRx.imag, c=‘blue’, alpha=0.6, s=20, marker=’.’, label=‘Received’) ax_before.scatter(qpsk_points.real, qpsk_points.imag, c=‘red’, s=30, marker=‘x’, label=‘QPSK Points’) |
|---|
ax_before = fig_eq.add_subplot(eq_grid[1, 0])
ax_before.scatter(pbchRx.real, pbchRx.imag, c=‘blue’, alpha=0.6, s=20, marker=’.’, label=‘Received’)
ax_before.scatter(qpsk_points.real, qpsk_points.imag, c=‘red’, s=30, marker=‘x’, label=‘QPSK Points’)
- pbchRx 包含直接从 rxGrid 提取的原始 PBCH 采样(不含 DMRS)。
- qpsk_points 定义 QPSK 的四个理想星座点。
- 该图显示信道均衡前 PBCH 符号的失真程度。
均衡后的 PBCH 星座图 - (E)
该图显示经 MMSE 均衡后的 PBCH 符号星座,揭示信道补偿的有效性。变量 pbch_eqed 包含由 nrEqualizeMMSE 函数计算的均衡后 PBCH 采样,以绿色绘制其均衡后位置。理想 QPSK 星座点仍以红色叠加作为对比。接收符号在理想点周围的聚集明显改善,表明均衡成功抑制了信道影响,带来更干净、更可靠的解调。
| ax_after = fig_eq.add_subplot(eq_grid[1, 1]) ax_after.scatter(pbch_eqed.real, pbch_eqed.imag, c=‘green’, alpha=0.6, s=20, marker=’.’, label=‘Equalized’) ax_after.scatter(qpsk_points.real, qpsk_points.imag, c=‘red’, s=30, marker=‘x’, label=‘QPSK Points’) |
|---|
ax_after = fig_eq.add_subplot(eq_grid[1, 1])
ax_after.scatter(pbch_eqed.real, pbch_eqed.imag, c=‘green’, alpha=0.6, s=20, marker=’.’, label=‘Equalized’)
ax_after.scatter(qpsk_points.real, qpsk_points.imag, c=‘red’, s=30, marker=‘x’, label=‘QPSK Points’)
-
pbch_eqed 是经 MMSE 均衡的 PBCH 信号,来自:
-
这表明均衡后接收点与理想 QPSK 符号的吻合度更好,说明解调条件得到改善。 注:为什么 PBCH 的均衡结果不理想?
-
要点:为什么 PBCH 的均衡结果不理想? 如果你仔细观察结果,可能会注意到 PBCH 均衡前后的差别并不大。更严格地说,星座在均衡后看起来甚至更差了,而对 PBCH DMRS 的均衡结果却非常完美。起初我以为信道估计与均衡过程本身可能有问题,花了很多时间尝试各种能想到的办法来改进,但都无济于事。最终我才明白,出现这种结果是有原因的——问题不在信道估计与均衡方法,而在于加到信号上的噪声的特性。
尽管对 DMRS 的均衡效果很好,PBCH 的均衡性能却很差,这可以用我们仿真中加性高斯白噪声(AWGN)的特性来解释。下面解释原因:
-
AWGN 特性:
-
AWGN 在时间和频率上统计独立
-
均值为零,方差恒定
-
最重要的是,不同时间/频率位置之间没有相关性
-
我们当前的设置:
-
我们向波形中加入 TARGET_SNR_DB = 5 的 AWGN
-
信道估计基于 DMRS 位置
-
不存在实际的信道失真(无衰落、无频率选择性、无时变)
-
为什么 DMRS 均衡看起来不错:
-
DMRS 位置均衡效果好,是因为我们知道确切的参考符号
-
当我们把接收 DMRS 除以 DMRS 位置处的信道估计时,实际上就是在去除这些特定点上的 AWGN
-
DMRS 星座看起来好,是因为我们是与已知参考点作对比
-
为什么 PBCH 均衡没有帮助:
-
来自 DMRS 位置的信道估计无法帮助处理 PBCH 位置上的 AWGN,原因在于:
-
PBCH 位置上的 AWGN 与 DMRS 位置上的 AWGN 完全独立
-
根本没有实际信道可供估计(只有噪声)
-
当我们把信道估计应用到 PBCH 位置时,实际上:
-
没有校正任何真实的信道影响(因为根本不存在)
-
反而可能基于不相关的噪声施加校正,引入额外失真 这解释了为什么:
-
DMRS 均衡看起来不错(我们是与已知参考作对比)
-
PBCH 均衡无法改善信号(无法校正独立的 AWGN)
-
我们仍能成功译码(AWGN 水平在纠错能力可承受范围内) 要让均衡更有意义,我们需要:
-
加入实际的信道影响(例如频率选择性衰落)
-
加入相关噪声或干扰
-
引入定时或频率偏移 这样才能在资源网格上产生跨位置相关的失真,使信道估计与均衡变得更为有效和必要。
均衡后 PBCH 星座的劣化可以直接用 AWGN 的特性来解释。下面拆解为什么在这种情况下均衡反而让结果变糟:
- 我们的系统中发生了什么: 接收信号 = 原始信号 + AWGN
At DMRS positions: R_dmrs = D + N1
At PBCH positions: R_pbch = P + N2
其中 N1 和 N2 是相互独立的 AWGN 样本
- 信道估计过程:
- 在 DMRS 位置,我们估计 H = R_dmrs/D = (D + N1)/D ≈ 1 + N1/D
- 这个信道估计含有噪声,但并不包含真实的信道失真
- 为什么均衡让 PBCH 变得更差: 我们把这个含噪的信道估计应用到 PBCH 上:R_pbch/H
于是变为:(P + N2)/(1 + N1/D)
(P + N2)/(1 + N1/D) ≈ (P + N2)(1 - N1/D)
= P - PN1/D + N2 - N2N1/D
-
最终我们得到:
-
原始 PBCH 信号(P)
-
PBCH 位置原有的 AWGN(N2)
-
来自 DMRS 的额外噪声项(-PN1/D)
-
交叉噪声项(-N2N1/D)
-
结果:
-
本来只有一个噪声项(N2)
-
现在变成了三个噪声项(N2、-PN1/D、-N2N1/D)
-
这解释了为什么均衡后星座看起来更散 这是一个典型案例:试图校正根本不存在的信道失真,反而引入了更多失真。均衡过程实际上是在:
-
从 DMRS 位置构造含噪的信道估计
-
把这个含噪估计应用到噪声完全不相关的 PBCH 位置
-
将不相关的噪声项相乘,从而增大整体噪声功率 这就是为什么在只有 AWGN、没有实际信道失真的系统中,通常最好完全跳过均衡。均衡过程的设计初衷是校正相关的信道影响,而不是不相关的噪声。
均衡后的 DMRS 星座图 - (F)
该图显示信道均衡后 DMRS 符号的星座,直接验证信道估计的准确性。均衡后的 DMRS 采样保存在 dmrs_eq 中,由 rxGrid 中的接收值除以 H 中相应的估计信道值得到,以红色绘制。已知参考符号 dmrsRef 以黑色叠加,作为基准。均衡符号与参考符号紧密对齐表明信道估计准确,从而保证有效均衡和可靠的 PBCH 译码。
| ax_dmrs = fig_eq.add_subplot(eq_grid[1, 2]) dmrs_eq = rxGrid[freq_indices, symbol_indices] / H[freq_indices, symbol_indices] ax_dmrs.scatter(dmrs_eq.real, dmrs_eq.imag, c=‘red’, alpha=0.6, s=20, marker=’.’, label=‘Equalized DMRS’) ax_dmrs.scatter(dmrsRef.real, dmrsRef.imag, c=‘black’, s=30, marker=‘x’, label=‘Reference DMRS’) |
|---|
ax_dmrs = fig_eq.add_subplot(eq_grid[1, 2])
dmrs_eq = rxGrid[freq_indices, symbol_indices] / H[freq_indices, symbol_indices]
ax_dmrs.scatter(dmrs_eq.real, dmrs_eq.imag, c=‘red’, alpha=0.6, s=20, marker=’.’, label=‘Equalized DMRS’)
ax_dmrs.scatter(dmrsRef.real, dmrsRef.imag, c=‘black’, s=30, marker=‘x’, label=‘Reference DMRS’)
- dmrs_eq 的计算方式是直接将接收 DMRS 采样除以其估计信道值:
- dmrs_eq = rxGrid[dmrs_indices] / H[dmrs_indices]
- dmrsRef 是已知的参考序列。
- 通过将均衡后的 DMRS 符号与其理想值对比,验证信道估计的效果。 代码中的 PBCH 译码过程是 5G NR 同步与解调流水线的最后阶段。在检测、解调并均衡 PBCH 符号之后,该阶段尝试使用 3GPP 规定的信道译码技术,恢复 PBCH 载荷中广播的系统信息比特。
这一代码块尝试对承载关键系统信息的物理广播信道(PBCH)载荷进行解调与译码。它先根据标志位选择经信道均衡或原始的 PBCH 符号,然后进行软解调的初次尝试(把 QPSK 符号转换为对数似然比),用由检测到的小区 ID 和 SSB 时间索引(ibar_SSB)生成的序列对结果比特解扰,应用信道状态信息(CSI)进行可靠性加权,执行极化码特有的速率恢复,最后进行极化码译码。不过,考虑到初次 SSB 索引检测(ibar_SSB)在加扰环节可能有歧义或不正确,代码实现了一套稳健的恢复机制:在嵌套循环中系统性地重试整个过程,轮询硬判决与软判决两种解调方式,并在解扰步骤中测试所有可能的 SSB 索引(v 从 0 到 7),直到译码出的载荷通过 CRC 校验,表明 PBCH 信息被正确恢复。
| # Use either equalized or raw PBCH symbols based on flag pbch_for_demod = pbch_eqed if not SKIP_EQUALIZATION else pbchRx # PBCH demodulation and rate recovery pbchBits = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, nVar, ‘soft’) E = 864 v = ibar_SSB scrambling_seq = nrPBCHPRBS(detected_NID, v, E) scrambling_seq_bpsk = (-1)scrambling_seq2 + 1 pbchBits_descrambled = pbchBits * scrambling_seq_bpsk pbchBits_csi = pbchBits_descrambled * np.repeat(csi, 2) # Polar code parameters A = 32 # Information bits P = 24 # CRC bits K = A + P # Total bits including CRC N = 512 # Mother code size, from 3GPP TS 38.212 Section 5.3.1 # Rate recovery and polar decoding decIn = nrRateRecoverPolar(pbchBits_csi, K, N, False, discardRepetition=False) decoded = nrPolarDecode(decIn, K, 0, 0) # First instance - initial decoding # CRC check decoded3, crc_result = nrCRCDecode(decoded, ‘24C’) # Try both hard and soft demodulation demod_methods = [‘hard’, ‘soft’] for demod_method in demod_methods: print(f”\n--- Using {demod_method} demodulation ---”) # Try different SSB indices for v in range(8): # Try v = 0-7 print(f”\nTrying SSB index v = {v}”) # Adjust noise variance based on demodulation method if demod_method == ‘soft’: # Use the global nVar for soft demodulation - already defined at the top # Get PBCH bits through soft demodulation pbchBits = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, nVar, ‘soft’) else: # For hard demodulation, get binary decisions first pbchBits_hard = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, 1, ‘hard’) # Convert to ±1 format for descrambling pbchBits = pbchBits_hard * 2 - 1 # Convert 0/1 to -1/+1 # PBCH descrambling E = 864 # Number of channel bits scrambling_seq = nrPBCHPRBS(detected_NID, v, E) scrambling_seq_bpsk = (-1)scrambling_seq2 + 1 # Convert 0/1 to -1/+1 pbchBits_descrambled = pbchBits * scrambling_seq_bpsk # For soft demodulation, apply CSI (if available from equalization) if demod_method == ‘soft’: if not SKIP_EQUALIZATION: # If equalization was performed, use the CSI values pbchBits_csi = pbchBits_descrambled * np.repeat(csi, 2) else: # Use moderate confidence since we’re using fixed noise variance csi_fixed = np.ones(E//2) * 5 pbchBits_csi = pbchBits_descrambled * np.repeat(csi_fixed, 2) else: # For hard demodulation, we already have ±1 values pbchBits_csi = pbchBits_descrambled # Convert back to binary for nrRateRecoverPolar if using hard demodulation if demod_method == ‘hard’: pbchBits_csi = (pbchBits_csi + 1) / 2 # Convert -1/+1 to 0/1 # Polar decoding parameters A = 32 # Information bits P = 24 # CRC bits K = A + P # Total bits including CRC N = 512 # Mother code size, from 3GPP TS 38.212 Section 5.3.1 # Rate recovery and polar decoding decIn = nrRateRecoverPolar(pbchBits_csi, K, N, False, discardRepetition=False) decoded = nrPolarDecode(decIn, K, 0, 0) # Second instance - in the demodulation methods loop # CRC check decoded3, crc_result = nrCRCDecode(decoded, ‘24C’) if crc_result == 0: print(f”nrPolarDecode: PBCH CRC ok for v = {v} with {demod_method} demodulation”) print(f”Decoded bits: {[int(bit[0]) for bit in decoded3]}”) # If successful, no need to try other values break else: print(f”nrPolarDecode: PBCH CRC failed for v = {v} with {demod_method} demodulation”) |
|---|
根据标志位选择均衡后或原始的 PBCH 符号
pbch_for_demod = pbch_eqed if not SKIP_EQUALIZATION else pbchRx
PBCH 解调与速率恢复
pbchBits = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, nVar, ‘soft’)
E = 864
v = ibar_SSB
scrambling_seq = nrPBCHPRBS(detected_NID, v, E)
scrambling_seq_bpsk = (-1)scrambling_seq2 + 1
pbchBits_descrambled = pbchBits * scrambling_seq_bpsk
pbchBits_csi = pbchBits_descrambled * np.repeat(csi, 2)
极化码参数
A = 32 # Information bits
P = 24 # CRC bits
K = A + P # Total bits including CRC
N = 512 # Mother code size, from 3GPP TS 38.212 Section 5.3.1
速率恢复与极化码译码
decIn = nrRateRecoverPolar(pbchBits_csi, K, N, False, discardRepetition=False)
decoded = nrPolarDecode(decIn, K, 0, 0)
第一次:初始译码
CRC 校验
decoded3, crc_result = nrCRCDecode(decoded, ‘24C’)
同时尝试硬判决与软判决解调
demod_methods = [‘hard’, ‘soft’]
for demod_method in demod_methods:
print(f”\n--- Using {demod_method} demodulation ---”)
尝试不同的 SSB 索引
for v in range(8): # Try v = 0-7
print(f”\nTrying SSB index v = {v}”)
根据解调方式调整噪声方差
if demod_method == ‘soft’:
软解调使用全局 nVar —— 已在开头定义
通过软解调获得 PBCH 比特
else:
硬解调时先获得二进制判决结果
pbchBits_hard = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, 1, ‘hard’)
转换为 ±1 格式以便解扰
pbchBits = pbchBits_hard * 2 - 1 # Convert 0/1 to -1/+1
PBCH 解扰
E = 864 # Number of channel bits
scrambling_seq_bpsk = (-1)scrambling_seq2 + 1 # Convert 0/1 to -1/+1
软解调时应用 CSI(若均衡已提供)
若已执行均衡,则使用 CSI 值
由于使用固定噪声方差,采用中等置信度
csi_fixed = np.ones(E//2) * 5
pbchBits_csi = pbchBits_descrambled * np.repeat(csi_fixed, 2)
硬解调时已经是 ±1 值
pbchBits_csi = pbchBits_descrambled
若采用硬解调,需转换回二进制以便 nrRateRecoverPolar 处理
if demod_method == ‘hard’:
pbchBits_csi = (pbchBits_csi + 1) / 2 # Convert -1/+1 to 0/1
极化码译码参数
第二次:位于解调方式循环内
if crc_result == 0:
print(f”nrPolarDecode: PBCH CRC ok for v = {v} with {demod_method} demodulation”)
print(f”Decoded bits: {[int(bit) for bit in decoded3]}”)
若成功,则无需尝试其他取值
break
print(f”nrPolarDecode: PBCH CRC failed for v = {v} with {demod_method} demodulation”)
符号解调
PBCH 译码过程的这一部分执行符号解调,把接收到的 PBCH QPSK 符号转换为软比特。输入 pbch_for_demod 包含原始或均衡后的 PBCH 符号,取决于此前是否进行了信道均衡。函数 nrSymbolDemodulate 使用 QPSK 方式处理这些符号,输出对数值(软比特),表示每个比特为 0 或 1 的置信度。解调行为受噪声方差参数 nVar 影响,确保得到的软比特根据信号条件适当缩放。
| pbchBits = nrSymbolDemodulate(pbch_for_demod, ‘QPSK’, nVar, ‘soft’) |
|---|
- pbch_for_demod 包含 PBCH 符号——是原始还是均衡后的,取决于是否跳过了均衡。
- 函数 nrSymbolDemodulate 将 QPSK 符号转换为软比特(对数值),为每个比特提供置信度水平。
- 解调使用 nVar(噪声方差)来塑造软判决过程。
PBCH 解扰
这一步通过移除发送时施加的小区专属加扰来执行 PBCH 解扰。加扰序列由函数 nrPBCHPRBS 生成,基于检测到的物理小区 ID(detected_NID)、SSB 索引 v 以及 PBCH 比特流长度 E。随后将该二进制序列映射为 BPSK 格式(取值 +1 或 –1),得到 scrambling_seq_bpsk。将解调出的软比特与该序列相乘,接收机即可有效逆转加扰,恢复信道编码之前的原始编码 PBCH 数据。
| scrambling_seq = nrPBCHPRBS(detected_NID, v, E) scrambling_seq_bpsk = (-1) * scrambling_seq * 2 + 1 pbchBits_descrambled = pbchBits * scrambling_seq_bpsk |
|---|
scrambling_seq_bpsk = (-1) * scrambling_seq * 2 + 1
- PBCH 使用由检测到的物理小区 ID detected_NID 和 SSB 索引 v 生成的小区专属加扰序列。
- 二进制加扰序列被映射为 BPSK 格式(+1 或 –1),然后与解调出的比特逐元素相乘以完成解扰。
CSI 加权(可选但重要)
这一步对解扰后的 PBCH 比特施加信道状态信息(CSI)加权,提高译码可靠性。CSI 反映均衡后接收机对每个符号的置信度,将软比特与 CSI 值相乘后,译码器会更加看重可靠的符号,而弱化噪声大的符号。由于 QPSK 每个符号承载 2 个比特,CSI 向量用 np.repeat(csi, 2) 复制一份以匹配比特长度。虽然这一加权是可选的,但在恶劣信道条件下对提升极化码译码性能尤为重要。
| pbchBits_csi = pbchBits_descrambled * np.repeat(csi, 2) |
|---|
- 若执行了均衡,则使用信道状态信息(CSI)按每个接收符号的置信度对比特加权。
- CSI 重复两次以匹配 QPSK 每符号 2 比特的特性。
速率恢复
这一步执行速率恢复,把解扰并经 CSI 加权的比特流重组为极化码译码器所需的格式。使用 nrRateRecoverPolar 函数,它应用 3GPP TS 38.212 第 5.4 节规定的必要变换,包括填充、比特重复和交织的处理。输入 K 和 N 分别表示信息比特加 CRC 比特的数量和母码长度。这一变换确保极化码译码器接收到格式正确的输入,从而成功译码 PBCH 载荷。
| decIn = nrRateRecoverPolar(pbchBits_csi, K, N, False, discardRepetition=False) |
|---|
- 把解扰、经 CSI 加权的比特流转换为极化码译码器期望的格式。
- 按 TS 38.212 第 5.4 节的规定处理填充、重复和重排。
极化码译码
这一步应用极化码译码,从速率恢复后的比特流中恢复原始 PBCH 消息。函数 nrPolarDecode 实现标准极化码译码算法,输入为格式化后的软比特 decIn 以及总比特数 K(包括载荷和 CRC)。具体而言,K = A + P,其中 A = 32 表示 PBCH 载荷比特数,P = 24 为 CRC 长度。译码器使用 5G NR 规范中定义的冻结比特和译码步骤处理输入,输出最可能的发送比特序列。
| decoded = nrPolarDecode(decIn, K, 0, 0) |
|---|
- 使用极化码译码算法恢复原始消息。
- K = A + P,其中:
- A = 32 个实际 PBCH 载荷比特,
- P = 24 个 CRC 比特。
CRC 校验
最后一步通过 CRC 校验验证译码后的 PBCH 消息。函数 nrCRCDecode 接收极化码译码器的输出,并应用 24 位 CRC 算法(‘24C’)来判断消息是否被正确译码。它同时返回最终译码比特(decoded3)和 crc_result 标志。若 crc_result 等于 0,表示 CRC 匹配,PBCH 载荷译码成功;否则视为因比特错误而译码失败。
| decoded3, crc_result = nrCRCDecode(decoded, ‘24C’) |
|---|
- 检查译码出的消息是否具有有效 CRC。
- 若 crc_result == 0,则认为译码成功。
SSB 索引搜索循环
由于正确的 SSB 索引 v 无法预知,代码通过遍历所有八个可能的 SSB 索引执行暴力搜索。对每个 v 值,它重新生成解扰序列,对 PBCH 进行解调和译码,并检查 CRC。一旦检测到有效 CRC,循环立即停止,表明正确的 SSB 索引及相应的系统信息已被成功恢复。这种做法在多个 SSB 以不同配置发送时能保证鲁棒性。
| for v in range(8): … if crc_result == 0: print(f”nrPolarDecode: PBCH CRC ok for v = {v}”) break |
|---|
for v in range(8):
…
print(f”nrPolarDecode: PBCH CRC ok for v = {v}”)
- 这个暴力搜索循环尝试所有可能的 SSB 索引,通过检查哪个解扰密钥能带来有效 CRC 来找到正确索引。
参考文献
- py3gpp - github