%% Application of FFT 1536 block in LTE OFDM Demodulation

%%
% This example shows how to use the FFT 1536 block in LTE OFDM 
% demodulation.

%   Copyright 2019 The MathWorks, Inc.

%%
% # Generate transmitter waveform.
% # Remove cyclic prefix.
% # Prepare inputs for FFT 1536 simulation.
% # Form resource grid.
% # Compare the CellRS symbols from the grid with that of |lteCellRS| function.
% # Generate HDL code.

%%
% Generate transmitter waveform.

cfg = lteTestModel('1.1','15MHz');
cfg.TotSubframes = 1;
tx = lteTestModelTool(cfg);

%%
% The above transmitter waveform generation uses a 2048-point FFT, which 
% results in a scaling factor of $\frac{1}{2048}$ in OFDM modulation. If
% a 1536-point FFT were used, the waveform would have a scaling factor of
% $\frac{1}{1536}$. This example multiplies the waveform by a factor 
% of $\frac{2048}{1536}$ to achieve the correct scaling.

tx = tx*(2048/1536);

%%
% To achieve a 23.04 Msps sampling rate, resample the |tx| samples 
% by $\frac{3}{4} = \frac{23.04e6}{30.72e6}$

rx = resample(tx,3,4); % rate conversion from 30.72Msps to 23.04Msps

%%
% Remove cyclic prefix. The first symbol of each slot has 12 additional 
% CP samples.

rx(11520+1:11520+12) = []; % discard 12 CP samples in slot 2
rx(1:12) = []; % discard 12 CP samples in slot 1
rx = reshape(rx,108+1536,14); % reshape to form 14 OFDM symbols
rx(1:108,:) = []; % discard remaining 108 CP samples from all symbols

%%
% Prepare inputs for FFT 1536 simulation.

SampleTime = 4.3e-8; % 1/23.04e6;
data = rx(:);
valid = true(1536*14,1);
data = fi(data,1,22,20);

dataIn = timeseries(data,(0:length(data)-1).'*SampleTime);
validIn = timeseries(valid,(0:length(valid)-1).'*SampleTime);

FFT1536Latency = 3180;

NofClks = FFT1536Latency+length(data); % number of simulation clock cycles
StopTime = (NofClks)*SampleTime;

open_system HDLFFT1536model;
sim HDLFFT1536model;

%%
simOut = dataOut(validOut);
simOut = double(simOut(:)*1536);

%%
% Form the resource grid and remove the DC subcarrier.

fftOut = fftshift(reshape(simOut,1536,14));
resourceGrid = fftOut(318+1:318+1+900,:);
resourceGrid(900/2+1,:) = []; 
%%
% Compare the CellRS symbols from the grid with the symbols returned from
% the |lteCellRS| function.

cellRS = lteCellRS(cfg);
cellRSIndices = lteCellRSIndices(cfg);
simCellRS = resourceGrid(cellRSIndices);
figure;
plot(real(simCellRS),imag(simCellRS),'o','MarkerSize',15);
hold on;
plot(real(cellRS),imag(cellRS),'*','MarkerSize',10)
legend('CellRS symbols from the FFT 1536 simulation grid'...
    ,'CellRS symbols from lteCellRS function','Location','southoutside')
axis([-1 1 -1 1]);


%%
% To generate HDL code for the FFT 1536 block, you must have
% an HDL Coder(TM) license. To generate HDL code from the FFT 1536 block
% in this model, right-click the block and select Create Subsystem from 
% Selection. Then right-click the subsystem and select HDL Code > Generate
% HDL Code for Subsystem.

