%% Enhanced Physical Downlink Control Channel (EPDCCH) Generation
%
% This example shows how to generate an Enhanced Physical Downlink Control 
% Channel (EPDCCH) transmission using the LTE Toolbox(TM). 

% Copyright 2014-2018 The MathWorks, Inc.

%% Introduction
% This example shows how to generate a downlink transmission including 
% EPDCCH, EPDCCH Demodulation Reference Signal (DMRS), Cell-Specific
% Reference Signal (CRS) and Channel State Information Reference Signal
% (CSI-RS). Beamforming of the EPDCCH is included for both Localized and
% Distributed transmission. The output of the example is a resource grid
% populated with the transmitted channels and an OFDM modulated time-domain
% waveform which transmits that resource grid. A plot is also produced
% which details the Resource Element (RE) usage for each of the channels.

%% eNodeB Configuration
% Cell-wide settings are configured with a structure |enb|. This structure
% contains parameters that belong to the eNodeB.

% Number of downlink resource blocks corresponding to 5MHz bandwidth
enb.NDLRB = 25;

% Duplexing mode: 'FDD' or 'TDD'
enb.DuplexMode = 'FDD';

% Number of Cell-specific Reference Signal (CRS) antenna ports
enb.CellRefP = 1;

% Subframe number
enb.NSubframe = 0;

% Cyclic prefix length: 'Normal' or 'Extended'
enb.CyclicPrefix = 'Normal';

% Frame number
enb.NFrame = 0;

% Cell identity
enb.NCellID = 0;

% Channel State Information Reference Signal (CSI-RS) subframe schedule
enb.CSIRSPeriod = 'On';

% Configuration index of the CSI-RS
enb.CSIRSConfig = 1;

% Number of CSI-RS antenna ports in use with this configuration
enb.CSIRefP = 2;

% Zero-Power CSI-RS subframe schedule
enb.ZeroPowerCSIRSPeriod = 'Off';

%% EPDCCH Configuration
% A structure |chs| is created, containing parameters relevant to the
% transmission of a DCI message which will be coded and modulated on the
% EPDCCH channel. Unlike the structure |enb| above which configures
% cell-wide settings, the structure here configures channel-specific
% settings for the transmission of a particular channel, in this case the
% EPDCCH. (The structure name |chs| is an abbreviation of
% "channel-specific".)

% DCI format to send on the EPDCCH
chs.DCIFormat = 'Format1A';

% Radio Network Temporary Identifier (RNTI)
chs.RNTI = 1;

% Transmission type: 'Localized' or 'Distributed'
chs.EPDCCHType = 'Localized';

% Zero-based indices of PRB pair set associated with EPDCCH search space
chs.EPDCCHPRBSet = 4:5;

% Initial transmission symbol for EPDCCH transmission
chs.EPDCCHStart = 2;

% Scrambling identity for the EPDCCH
chs.EPDCCHNID = 0;

% EPDCCH format
chs.EPDCCHFormat = 1;

%% Subframe Resource Grid Creation
% An empty resource grid |subframe| is created for one subframe. In this
% example, the 3rd dimension (planes) of this resource grid are intended to
% represent physical antennas. The mapping between antenna ports and
% physical antennas for the various channels and signals used in this
% example will be described when the channels and signals are mapped to
% this resource grid. The empty subframe resource grid is created using the
% <matlab:doc('lteDLResourceGrid') lteDLResourceGrid> function. The
% optional second input argument allows the 3rd dimension size (the number
% of planes) to be specified explicitly (by default the value of
% |enb.CellRefP|, the number of CRS ports, is used to determine the number
% of planes). Note that for distributed EPDCCH transmission, two antenna
% ports are used and therefore a minimum of two physical antennas are
% required; if the number of CRS ports or CSI-RS ports is greater than 2
% then the largest of these values is used, this allows the resource grid
% to contain all configured CRS or CSI-RS ports.

maxEpdcchPorts = 2;
nTxAnts = max([enb.CSIRefP enb.CellRefP maxEpdcchPorts]);
subframe = lteDLResourceGrid(enb,nTxAnts);

%% DCI Message Creation
% A DCI message of the format indicated by |chs.DCIFormat| is created using
% the function <matlab:doc('lteDCI') lteDCI>. The output structure |dci|
% represents the DCI message as described in TS36.212 Section 5.3.3.1 
% [ <#19 3> ]. The bit vector |dciBits| contains the actual message bits to
% be encoded. 

% Create a DCI message
[dci,dciBits] = lteDCI(enb,chs);

%% EPDCCH Candidate Selection
% The EPDCCH is transmitted in an "EPDCCH candidate", a set of Enhanced
% Control Channel Elements (ECCEs). Each ECCE maps onto a set of Enhanced
% Resource Element Groups (EREGs), which in turn map onto particular
% resource elements in the subframe resource grid. In order to create the
% resource element indices for a particular EPDCCH transmission, an EPDCCH
% candidate must be chosen. The function <matlab:doc('lteEPDCCHSpace')
% lteEPDCCHSpace> creates a matrix of valid EPDCCH candidates for the given
% configuration, with each row of the matrix giving the inclusive
% [begin,end] indices of a single EPDCCH candidate. Any row of this matrix
% can therefore be extracted and assigned to the |chs.EPDCCHECCE| parameter
% field which will be used by the function <matlab:doc('lteEPDCCHIndices')
% lteEPDCCHIndices> to determine the resource element indices for the
% EPDCCH transmission.

candidates = lteEPDCCHSpace(enb,chs);

chs.EPDCCHECCE = candidates(3,:);

%% EPDCCH Data Bit Capacity
% In order to determine the EPDCCH data bit capacity, the function
% <matlab:doc('lteEPDCCHIndices') lteEPDCCHIndices> is used, which creates
% the resource element indices for the EPDCCH, following TS36.211 Section
% 6.8A.5 [ <#19 3> ]; these indices will be used later for mapping the
% EPDCCH transmission to the subframe resource grid. This function also
% returns a structure containing useful EPDCCH "dimensionality information"
% values including |epdcchInfo.EPDCCHG|, the EPDCCH data bit capacity,
% which will be used to configure the rate matching when encoding the DCI
% message.

% Calculate EPDCCH resource element indices and associated dimensionality
% information including the EPDCCH data bit capacity epdcchInfo.EPDCCHG
[epdcchIndices,epdcchInfo] = lteEPDCCHIndices(enb,chs);

%% DCI Message Encoding
% Next, the bit vector |dciBits| is passed to the function
% <matlab:doc('lteDCIEncode') lteDCIEncode> which performs CRC insertion,
% tail-biting convolutional coding and rate matching, following TS36.212
% Sections 5.3.3.2 to 5.3.3.4 [ <#19 3> ]. Note that the third argument to
% <matlab:doc('lteDCIEncode') lteDCIEncode> specifies the rate matching
% capacity (for non-enhanced PDCCH transmissions, this third argument can
% be omitted and the rate matching capacity is derived internally from the
% PDCCH format).

% Perform DCI message encoding with a rate matching output size equal to
% the EPDCCH data bit capacity
codedDciBits = lteDCIEncode(chs,dciBits,epdcchInfo.EPDCCHG);

%% EPDCCH Modulation
% The EPDCCH modulation is performed using the function 
% <matlab:doc('lteEPDCCH') lteEPDCCH>, following TS36.211 Sections 6.8A-2
% to 6.8A-4 [ <#19 2> ]. The resulting symbols |epdcchSymbols| will be
% mapped to the subframe resource grid after appropriate beamforming. The
% EPDCCH is transmitted on a subset of the antenna ports 107...110:
%
% * For |chs.EPDCCHType='Localized'|, the EPDCCH is transmitted on a single
% antenna port chosen from 107...110 as a function of a number of
% parameters including the RNTI.
% * For |chs.EPDCCHType='Distributed'|, the EPDCCH is transmitted on two
% antenna ports, either {107,109} for normal cyclic prefix or {107,108} for
% extended cyclic prefix.
%
% The indices produced by <matlab:doc('lteEPDCCHIndices')
% lteEPDCCHIndices> map antenna ports 107...110 (0-based) to planes 1...4
% (1-based) of a subframe resource grid. A plane is the third dimension of
% a subframe resource grid as described in the 
% <docid:lte_gs#btwyxn8 Representing Resource Grids> 
% documentation. Typically LTE Toolbox functions separate the symbols and
% indices for different antenna ports into separate columns. However for 
% the EPDCCH the symbols and their indices are presented in a single 
% column and the indices therein correspond to the appropriate antenna port 
% for each resource element. This approach is taken for two reasons:
%
% * The number of EPDCCH symbols mapped to each antenna port may be
% different.
% * The mapping between symbols and antenna ports is dependent on many
% parameters and to represent this in <matlab:doc('lteEPDCCH') lteEPDCCH>
% would result in a very significant increase in the number of parameters
% required by this function. 
%
% Beamforming of the EPDCCH for transmission upon physical antennas will be
% described later.

epdcchSymbols = lteEPDCCH(enb,chs,codedDciBits);

%% EPDCCH DMRS Modulation
% The DMRS associated with the EPDCCH, |epdcchDmrsSymbols|, is created
% using the function <matlab:doc('lteEPDCCHDMRS') lteEPDCCHDMRS>,
% following TS36.211 Section 6.10.3A.1 [ <#19 2> ]. The associated
% resource element indices, |epdcchDmrsIndices|, are also created using the
% function <matlab:doc('lteEPDCCHDMRSIndices') lteEPDCCHDMRSIndices>,
% following TS36.211 Section 6.10.2.A.2 [ <#19 2> ]. The arrangement of
% DMRS symbols and their indices for different antenna ports mirrors that
% described for the EPDCCH symbols and indices above. Beamforming of the
% EPDCCH DMRS for transmission upon physical antennas will be described
% later.

epdcchDmrsSymbols = lteEPDCCHDMRS(enb,chs);
epdcchDmrsIndices = lteEPDCCHDMRSIndices(enb,chs);

%% Generate CRS and CSI-RS
% The CRS and CSI-RS signals and their corresponding resource element
% indices are created, and the signals are mapped into the subframe
% resource grid:
%
% * The indices produced by <matlab:doc('lteCellRSIndices')
% lteCellRSIndices> map antennas ports 0...3 (0-based) to planes 1...4
% (1-based) of the subframe resource grid. In this example, a single CRS
% port (|enb.CellRefP=1|) is configured and therefore the CRS will be
% mapped to the first plane of the subframe resource grid.
% * The indices produced by <matlab:doc('lteCSIRSIndices')
% lteCSIRSIndices> map antenna ports 15...22 (0-based) to planes 1...8
% (1-based) of the subframe resource grid. In this example, two CSI-RS
% ports (|enb.CSIRefP=2|) are configured and therefore the CSI-RS will be
% mapped to the first two planes of the subframe resource grid. 
%
% This mapping matches the generic beamforming model described in TS36.101
% Annex B.4.3 [ <#19 1> ].

% Create CSI-RS and map to the subframe resource grid
csirsIndices = lteCSIRSIndices(enb);
csirsSymbols = lteCSIRS(enb);
subframe(csirsIndices) = csirsSymbols;

% Create CRS and map to the subframe resource grid
crsIndices = lteCellRSIndices(enb);
crsSymbols = lteCellRS(enb);
subframe(crsIndices) = crsSymbols;

%% Beamforming of EPDCCH Transmission
% The EPDCCH and its DMRS must now be beamformed and mapped to physical
% antennas for transmission. The beamforming vectors here are chosen in
% accordance with TS36.101 Annex B.4.4 [ <#19 1> ] for distributed
% transmission and TS36.101 Annex B.4.5 [ <#19 1> ] for localized
% transmission. 

%%
% In preparation for beamforming, the EPDCCH symbols are concatenated with
% the EPDCCH DMRS symbols and the corresponding indices are also
% concatenated. The EPDCCH and its DMRS must undergo the same beamforming,
% therefore they can be processed together when applying the beamforming.

% Concatenate EPDCCH symbols/indices with EPDCCH DMRS symbols/indices to
% facilitate beamforming
allSymbols = [epdcchSymbols; epdcchDmrsSymbols];
allIndices = [epdcchIndices; epdcchDmrsIndices];

%%
% The complete set of indices |allIndices| is then converted to subscripts
% and the subscripts are processed to obtain a list of active EPDCCH
% antenna ports |ports| and active EPDCCH resource blocks |rbs|. |ports| 
% and |rbs| will be used to control two loops which carry out the
% beamforming on a per port and per resource block basis. 

% Determine the set of EPDCCH antenna ports 'ports' and resource blocks
% 'rbs' used by the EPDCCH and its DMRS; the value of 4 below is the
% number of EPDCCH antenna ports (107...110) on which an EPDCCH might be
% transmitted (i.e. 'allIndices' may generally contain indices for any of
% the 4 EPDCCH antenna ports).
[K,L,~] = size(subframe);
[resubs,~,portsubs] = ind2sub([K L 4],allIndices);
rbsubs = floor((resubs-1)/12)+1;
rbs = unique(rbsubs);
ports = unique(portsubs.');

%%
% For localized EPDCCH transmission, the beamforming described in TS36.101 
% Annex B.4.5 [ <#19 1> ] uses a single random beamforming vector across
% all resource blocks.

% For localized transmission, a single beamforming vector 'W' is used for
% the single EPDCCH port and across all resource blocks
if (strcmpi(chs.EPDCCHType,'Localized'))
    codebookIdx = randi([0 3],1);
    W = lteDLPrecode(1,nTxAnts,'SpatialMux',codebookIdx);
end

%%
% For distributed EPDCCH transmission, the beamforming described in
% TS36.101 Annex B.4.4 [ <#19 1> ] uses a different beamforming vector |W|
% for each resource block and each of the two antenna ports used. Therefore
% the beamforming vector selection is carried out in loops across the set
% of resource blocks and ports. Note that the loops below are applicable
% for both distributed and localized transmission: for localized
% transmission the beamforming vector selected above is applied to each
% resource block (for the single port used), whereas for distributed
% transmission the beamforming vector is both selected and applied for each
% resource block and antenna port. The code is structured as follows:
%
% For each antenna port and for each Resource Block (RB):
%
% * the vector of logical values |thisport| is true for EPDCCH/DMRS symbols
% which apply to the current antenna port.
% * the vector of logical values |thisrb| is true for EPDCCH/DMRS symbols
% which apply to the current RB.
% * For distributed transmission, select a beamforming vector |W|
% * Apply beamforming to the EPDCCH/DMRS symbols and EPDCCH/DMRS indices
% for the current antenna port and current RB. To assist with the
% beamforming of indices, the function 
% <matlab:doc('lteExtractResources') lteExtractResources> is used. The call
% to this function takes the resource elements indices for a given antenna
% port as the input. The first output of the function, which is skipped
% here, is the set of REs for all physical antennas in the subframe
% resource grid |subframe| in the same time/frequency locations as the
% input indices. The second output, which is used as our beamformed
% indices, contains the corresponding indices for the REs in the first
% output, essentially a projection of the input indices onto all physical
% antennas. The symbols and indices for the current antenna port and
% current RB are obtained by using the logical vectors |thisport| and
% |thisrb| to extract the appropriate elements of the EPDCCH/DMRS symbols
% |allSymbols| and EPDCCH/DMRS indices |allIndices|.
% * Map the beamformed EPDCCH/DMRS to the subframe resource grid. 

% Matrix to store the codebook index used for each resource block and
% antenna port
codebookIdxs = zeros(length(rbs),length(ports));

% For each EPDCCH antenna port in use:
for p=1:length(ports)
    thisport = (portsubs==ports(p));
    
    % For each RB in use:
    for r = 1:length(rbs)
        thisrb = (rbsubs==rbs(r));
        
        % For distributed transmission, a beamforming vector 'W' is
        % selected for each EPDCCH port and each resource block; the
        % beamforming vector chosen for a particular resource block must be
        % different on each of the antenna ports
        if (strcmpi(chs.EPDCCHType,'Distributed'))
            unusedIdxs = setxor(0:3,codebookIdxs(r,1:p-1));
            codebookIdx = unusedIdxs(randi(length(unusedIdxs),1));
            W = lteDLPrecode(1,nTxAnts,'SpatialMux',codebookIdx);
        end
        
        % Record the codebook index used for this resource block and
        % antenna port
        codebookIdxs(r,p) = codebookIdx;
        
        % Apply beamforming to the symbols and indices
        bfSymbols = allSymbols(thisport & thisrb) * W;
        [~,bfIndices] = ...
            lteExtractResources(allIndices(thisport & thisrb),subframe);
        
        % Map the beamformed symbols to the physical antennas. The symbols
        % must be added to the existing subframe resource grid because
        % different ports may share the same time/frequency locations and
        % therefore the beamformed symbols must be superposed.
        subframe(bfIndices) = subframe(bfIndices) + bfSymbols;
        
    end
    
end
 
%% Plot Resource Element Assignments
% The subframe resource grid is plotted to indicate the locations of the
% EPDCCH, EPDCCH DMRS, CRS and CSI-RS. If |chs.EPDCCHStart>0|, the location
% of the legacy control region is also shown.

hEPDCCHGenerationPlot(enb,chs);

%% OFDM Modulation
% Finally the subframe resource grid is OFDM modulated; the resulting
% matrix has two columns; each column contains the complex baseband
% time-domain waveform samples for each physical antenna.

waveform = lteOFDMModulate(enb,subframe);

%% Appendix
% This example uses the helper function:
%
% * <matlab:edit('hEPDCCHGenerationPlot.m') hEPDCCHGenerationPlot.m>

%% Selected Bibliography
% # 3GPP TS 36.101 "User Equipment (UE) radio transmission and reception"
% # 3GPP TS 36.211 "Physical channels and modulation"
% # 3GPP TS 36.212 "Multiplexing and channel coding"
