%% Modeling and Testing an NR RF Transmitter
% The example shows how to characterize the impact of RF
% impairments, such as in-phase and quadrature (IQ) imbalance, phase
% noise, and power amplifier (PA) nonlinearities in the performance of a
% new radio (NR) radio frequency (RF) transmitter. The NR RF transmitter is
% modeled in Simulink(R) using 5G Toolbox(TM) and RF Blockset(TM).
%
% Copyright 2019-2020 The MathWorks, Inc.

%% Introduction
% This example shows how to characterize the impact of RF impairments such
% as IQ imbalance, phase noise, and PA nonlinearities in the performance of
% an NR RF transmitter. To evaluate the performance, the example considers
% these measurements:
%
% * Error vector magnitude (EVM): vector difference at a given time
% between the ideal (transmitted) signal and the measured (received)
% signal.
% * Adjacent channel leakage ratio (ACLR): measure of the amount of power
% leaking into adjacent channels and is defined as the ratio of the
% filtered mean power centered on the assigned channel frequency to the
% filtered mean power centered on an adjacent channel frequency.
% * Occupied bandwidth: bandwidth that contains 99% of the total integrated 
% power of the signal, centered on the assigned channel frequency.
% * Channel power: filtered mean power centered on the assigned channel
% frequency.
% * Complementary cumulative distribution function (CCDF): probability of a
% signal's instantaneous power to be a level specified above its average
% power.
%
% The model works on a subframe by subframe basis. For each subframe, the
% workflow consists of these steps:
%
% # Generate the baseband waveform using 5G Toolbox functions.
% # Upconvert the generated waveform to the passband frequency and apply
% RF filtering and amplification using RF Blockset.
% # Downconvert the transmitted waveform to baseband frequency.
% # Calculate the ACLR/ACPR, occupied bandwidth, channel power, and CCDF
% using the Spectrum Analyzer block.
% # Demodulate the waveform at the receiver to measure EVM.
%
% The example uses a Simulink model to perform these operations. Baseband
% signal processing (steps 1 and 5) uses MATLAB(R) function blocks, whereas
% the RF transmitter modeling (steps 2-4) uses RF Blockset. This model only
% supports Normal and Accelerator simulation modes.

%% Simulink Model Structure
% The model contains three main components:
%
% * NR Baseband Generation: generates the baseband waveform.
% * RF Transmission: upconverts the waveform from baseband to passband,
% applies RF filtering, and amplification and performs downconversion.
% * NR Baseband Reception and Measurements: performs the RF measurements
% and demodulates the baseband waveform to calculate the EVM.
%
modelName = 'NRModelingAndTestingRFTransmitterModel';
open_system(modelName);

%% NR Baseband Generation
% The NR-TM Transmission block transmits standard-compliant 5G NR test
% model (NR-TM) waveforms for frequency range 1 (FR1) and frequency range 2
% (FR2) [ <#13 1> ].
% 
% For the NR-TM waveform generation, you can specify the NR-TM name, the
% channel bandwidth, the subcarrier spacing (SCS), the duplexing mode, the
% cell identity, and the TS 38.141 version using the Waveform Parameters
% block. Additionally, this block provides the option to enable or disable
% the ACLR test. When the ACLR measurement is enabled, the waveform is
% oversampled to visualize the spectral regrowth.
% 
% <<../RFTransmitterWaveformParametersMask.png>>
%
% For more information on how to generate NR-TMs, see
% <docid:5g_examples#mw_67a90eda-30fe-4572-bc66-91b382be5218 5G NR-TM and FRC Waveform Generation>.
%
% As the example works on a subframe by subframe basis, the NR-TM
% Transmission block sends one subframe at a time. Transmitting ten
% subframes, corresponding to one frame in the case of FDD duplexing mode,
% lasts 10 ms. If the simulation time is longer than 10 ms, the NR-TM
% Transmission block transmits the same frame cyclically. The Subframe
% Counter block stores the number of the currently transmitted subframe. If
% the simulation time is longer than a frame period, the Subframe Counter
% block resets to 0.

%% RF Transmission
% The RF Transmitter block is based on a superheterodyne transmitter
% architecture. This architecture upconverts the waveform to the passband
% frequency and applies RF filtering and amplification before transmitting
% the signal. Typical components of the superheterodyne transmitter are: 
%
% * IQ modulator consisting of mixers, phase shifter, and local oscillator
% * Bandpass filter
% * Power amplifier
%
% In addition to these components, this RF Transmitter block also includes a
% variable gain amplifier (VGA) to control the input back-off (IBO) level
% of the high power amplifier (HPA).
%
set_param(modelName,'Open','off');
set_param([modelName '/RF Transmitter'],'Open','on');

%%
% The Inport block converts the complex baseband waveform into an RF signal
% and the Outport block converts the RF signal back into complex baseband.
% Because the RF Transmitter accepts a maximum of 1024 samples per
% subframe, the Input Buffer, before the RF Transmitter block, reduces the
% number of samples sent to the RF Transmitter. In the current
% configuration, the Input Buffer sends one sample at a time, resulting in
% the RF Transmitter being sample-based. To configure the RF Transmitter
% for frame-based transmission, update the model:
%
% * Set the output buffer size parameter of the Input
% Buffer to a value less than or equal to 1024 samples. Make sure that this
% value is a factor of the number of samples per
% subframe, which depends on the selected NR-TM configuration. 
% * Inside the RF Transmitter, set the Samples per frame parameter of the
% RF Configuration block to the output buffer size value of the Input Buffer.
%
% Before sending the samples onto the Decode Subframe block, the Output
% Buffer (after the RF Transmitter) buffers all samples within a subframe.
%
% The Delay block accounts for buffer-induced delays. As the duration of
% the delay is equivalent to the transmission of a subframe, the Decode
% Subframe block does not demodulate the first information received during
% a subframe period. 
%
% You can configure the RF Transmitter components using the RF
% Transmitter block mask. 
%
% <<../RFTransmitterRFMask.png>>
%
% The RF Transmitter block exhibits typical impairments, including:
%
% * I/Q imbalance as a result of gain or phase mismatches between the
% parallel sections of the transmitter chain dealing with the IQ signal paths.
% * Phase noise as a secondary effect directly related to the thermal noise
% within the active devices of the oscillator.
% * HPA nonlinearities due to DC power limitation when the
% amplifier works in saturation region.
%
% This example highlights the effect of nonlinear behavior of the HPA.

%% NR Baseband Reception and Measurements
% The Decode Subframe block performs OFDM demodulation of the received
% subframe, channel estimation, and equalization to recover and plot the PDSCH
% symbols in the Constellation Diagram. This block also averages the EVM over 
% time and frequency and plots these values:
%
% * EVM per OFDM symbol: EVM averaged over each OFDM symbol.
% * EVM per slot: EVM averaged over the allocated PDSCH symbols within a slot.
% * EVM per subcarrier: EVM averaged over the allocated PDSCH symbols within
% a subcarrier.
% * Overall EVM: EVM averaged over the allocated PDSCH symbols transmitted.
% 
% According to TS 38.141-1 [ <#13 1> ], not all PDSCH symbols are
% considered for the EVM evaluation. Using the RNTI, the helper function
% |hListTargetPDSCHs| selects the target PDSCH symbols to analyze.
%
% The Spectrum Analyzer block provides frequency-domain measurements such
% as ACLR (referred to as ACPR), occupied bandwidth, channel power, and
% CCDF. To visualize the spectral regrowth, the ACLR test oversamples the
% waveform. The oversampling factor depends on the waveform configuration
% and should be set such that the generated signal is capable of
% representing first and second adjacent channels. The ACLR evaluation
% follows the specifications in TS 38.141-1 [ <#13 1> ].

%% Model Performance
% To characterize the impact of HPA nonlinearities in the EVM and ACLR
% evaluations, you can measure the amplitude-to-amplitude modulation
% (AM/AM) of the HPA. The AM/AM refers to the output power levels in terms
% of the input power levels. This figure shows the AM/AM characteristic of
% the HPA selected for this model.
%
hPlotHPACurve();
figHPA = gcf;

%%
% P1dB is the power at 1 dB compression point and is usually used as a
% reference when selecting the IBO level of the HPA. You can see the HPA
% impact on the RF transmitter by analyzing the EVM and ACLR results for
% different operating points of the HPA. For example, compare the case when
% IBO = 15 dB, corresponding to HPA operating in linear region, with the
% case when IBO = 2 dB, corresponding to HPA operating in full saturation.
% The gain of the VGA controls the IBO level. To keep a VGA linear
% behavior, select gain values lower than 20 dB.
% 
%
% * _Linear HPA (IBO = 15 dB)_. To operate at an IBO level of 15 dB, set
% the *Available power gain* parameter of the VGA block to 0 dB. To
% simulate a whole frame, run the simulation long enough to capture 10
% subframes (10 ms). During simulation, the model displays the EVM and ACLR
% measurements and the constellation diagram.
%
set_param([modelName '/RF Transmitter'],'vgaGain','0');
sim(modelName);

%%
% According to TS 38.104 [ <#13 2> ], the minimum required ACLR for
% conducted measurements is 45 dB and the maximum required EVM when the
% constellation is 64-QAM is 8%. As the ACLR values are higher than 45 dB,
% and the overall EVM, which is around 1.3%, is lower than 8%, both
% measurements fall within the requirements.
%
% * _Nonlinear HPA (IBO = 2 dB)_. To operate at an IBO level of 2 dB, set
% the *Available power gain* parameter of the VGA block to 12 dB.
%
set_param([modelName '/RF Transmitter'],'vgaGain','12');
sim(modelName);
slmsgviewer.DeleteInstance();

% Restore to default parameters
set_param([modelName '/RF Transmitter'],'vgaGain','0');

%%
% Compared to the previous case, the constellation diagram is distorted and
% the spectral regrowth is higher. In terms of the measurements, the
% first adjacent channel ACLR does not fall within
% the requirements of TS 38.104 [ <#13 2> ] and the overall
% EVM, around 7.3%, is higher.
%
% The RF Transmitter is configured to work with the default values of the
% Waveform Parameters block and with a carrier centered at 2140 MHz (FR1).
% If you change the carrier frequency or the values in the Waveform
% Parameters block, you may need to update the parameters of the RF
% Transmitter components as these parameters have been selected to work for
% the default configuration of the example. For more information, see the
% Summary and Further Exploration section of this example.

%% Summary and Further Exploration
% This example demonstrates how to model and test an NR RF transmitter in
% Simulink. The RF transmitter consists of an IQ modulator, a bandpass
% filter and amplifiers. To evaluate the performance, the Simulink model
% considers ACLR and EVM measurements. The example highlights the effect of
% HPA nonlinearities on the performance of the RF Transmitter. You can
% explore the impact of altering other impairments as well. For example:
%
% * Increase I/Q imbalance by using the *I/Q gain mismatch (dB)* and *I/Q
% phase mismatch (Deg)* parameters on the *IQ Modulator* tab of the RF
% Transmitter block.
% * Increase the phase noise by using *Phase noise offset (Hz)* and *Phase
% noise level (dBc/Hz)* parameters on the *IQ Modulator* tab of the RF
% Transmitter block.
%  
% Additionally, you can check the occupied bandwidth, the channel power,
% and the CCDF measurements by using the Spectrum Analyzer block.
%
% If you change the carrier frequency or the values in the Waveform
% Parameters block, you may need to update the parameters of the RF
% Transmitter components as these parameters have been selected to work for
% the default configuration of the example. For instance, a change in the
% carrier frequency requires revising the bandwidth of the filter. If you
% select a bandwidth wider than 20MHz, you may need to update the *Impulse
% response duration* and *Phase noise frequency offset (Hz)* parameters of
% the IQ Modulator block. The phase noise offset determines the lower limit
% of the impulse response duration. If the phase noise frequency offset
% resolution is too high for a given impulse response duration, a warning
% message appears, specifying the minimum duration suitable for the
% required resolution. For more information, see <docid:simrf_ref#bvlqsg1-1
% IQ Modulator>.
% 
% This example could be the basis for testing NR-TM waveforms for different
% RF configurations. You can try replacing the RF Transmitter block by
% another RF subsystem of your choice and configuring the model
% accordingly.

%% Appendix
% This example uses these helper functions:
%
% * <matlab:edit('hNRReferenceWaveformGenerator.m') hNRReferenceWaveformGenerator.m>
% * <matlab:edit('hNRDownlinkWaveformGenerator.m') hNRDownlinkWaveformGenerator.m>
% * <matlab:edit('hOFDMInfo.m') hOFDMInfo.m>
% * <matlab:edit('hOFDMModulate.m') hOFDMModulate.m>
% * <matlab:edit('hOFDMDemodulate.m') hOFDMDemodulate.m>
% * <matlab:edit('hPDSCHResources.m') hPDSCHResources.m>
% * <matlab:edit('hSSBurstInfo.m') hSSBurstInfo.m>
% * <matlab:edit('hVectorDataSource.m') hVectorDataSource.m>
% * <matlab:edit('hListTargetPDSCHs.m') hListTargetPDSCHs.m>
% * <matlab:edit('hSlotResources.m') hSlotResources.m>
% * <matlab:edit('hACLRMeasurementNR.m') hACLRMeasurementNR.m>
% * <matlab:edit('hACLRParametersNR.m') hACLRParametersNR.m>
% * <matlab:edit('hInitializeNRTMModel.m') hInitializeNRTMModel.m>
% * <matlab:edit('hDecodeSubframe.m') hDecodeSubframe.m>
% * <matlab:edit('hPlotHPACurve.m') hPlotHPACurve.m>

%% Selected Bibliography
% # 3GPP TS 38.141-1. "NR; Base Station (BS) conformance testing Part 1:
% Conducted conformance testing." _3rd Generation Partnership Project;
% Technical Specification Group Radio Access Network._
% # 3GPP TS 38.104. "NR; Base Station (BS) radio transmission and reception." 
% _3rd Generation Partnership Project; Technical Specification Group Radio
% Access Network._

