%% Spatial Reuse with BSS Coloring in 802.11ax Residential Scenario
% This example demonstrates how to simulate the impact of spatial reuse
% (SR) with basic service set (BSS) coloring on the throughput of an
% IEEE(R) 802.11ax(TM) residential scenario network using SimEvents(R),
% Stateflow(R), and WLAN Toolbox(TM). This example simulates non-spatial
% reuse groups overlapping BSS packet detect (OBSS PD) defined in IEEE(R)
% P802.11ax(TM)/D4.1 Amendment [ <#11 1> ]. The fundamental objective of
% this feature is to increase the network performance in a dense network
% scenario by maximizing the frequency reuse between BSSs. This is achieved
% by adjusting OBSS PD threshold in the range [-62, -82] dBm. Each BSS is
% assigned a unique color code called BSS color. The BSS color enables
% 802.11ax station (STA) to decide whether the simultaneous use of
% frequency spectrum along with the OBSS is allowed or not. This results in
% ignoring the frames from OBSS and enables concurrent transmission of data
% to multiple devices in a dense network scenario mitigating the exposed
% node problem. To demonstrate the SR with BSS coloring feature, the
% example models a network topology consisting of four BSSs in a
% residential apartment of two floors. Each floor contains two BSSs and
% each BSS consists of an access point (AP) and a STA. The model enables
% you to configure the OBSS PD threshold values in the range [-62, -82] dBm
% and study its impact on the throughput of each BSS. You can also write
% your own algorithm to control OBSS PD threshold levels dynamically during
% the simulation.

% Copyright 2020 The MathWorks, Inc.

%% IEEE 802.11ax OBSS PD-based Spatial Reuse Operation
% In dense network scenarios consisting of legacy IEEE(R) 802.11 devices,
% multiple APs operate in the same frequency due to limited spectrum. This
% resulted in an inefficient paradigm causing network congestion and
% slowdown. Also, the legacy devices were unable to efficiently communicate
% with each other to maximize channel resources. To address this issue, the
% IEEE(R) P802.11ax(TM)/D4.1 Amendment [ <#11 1> ] introduced the OBSS
% PD-based SR operation to optimize the efficient reutilization of
% frequency spectrum in dense network scenarios. To achieve this, the
% number of parallel transmissions that could potentially improve network
% performance of BSSs operating in the same frequency is increased. To
% increase the number of parallel transmissions, the clear channel
% assessment/carrier sense (CCA/CS) threshold for the detected OBSS
% transmissions is adjusted to a new value called OBSS PD threshold. The
% OBSS PD threshold is higher then the default CCA/CS threshold. This
% figure illustrates the SR operation in an OBSS. The network topology
% consists of two BSSs, each containing an AP and a STA.
%
% <<../srOperation.png>>
%
% The default CCA/CS threshold (denoted by blue dashed lines) does not
% enable simultaneous transmissions between AP1 and AP2. In this case,
% transmission in BSS-2 must be deferred if devices in BSS-1 occupy the
% channel for transmission. However, by optimally selecting the value of
% OBSS PD threshold (denoted by red dashed lines), both APs
% can simultaneously transmit to their corresponding STAs. This SR
% operation when used with BSS coloring technique improves channel
% utilization and gives better throughput.

%% BSS Coloring
% The SR operation uses BSS color identifier to enable 802.11ax devices
% to distinguish between different BSSs when other devices transmit on same
% channel. The BSS color is a numerical identifier of the BSS having a
% value in the range [1, 63]. BSS color information is present in a 6-bit
% BSS color field in the HE SIG-A which is present in the preamble of
% 802.11ax physical layer (PHY) header. If the color of the frame matches
% with the color of the BSS, it is an intra-BSS transmission as the
% transmitting device belongs to the same BSS as the receiver. If the
% detected frame has a different BSS color from its own, the frame is an
% inter-BSS frame. An 802.11ax AP can change its BSS color if it detects an
% OBSS using the same color. This flowchart shows the BSS coloring
% procedure.
%
% <<../srFlowChart.png>>
%
% When detecting a transmission, a 802.11ax device differentiates between
% intra and inter-BSS frames by inspecting the BSS color field. For
% intra-BSS frames, the 802.11ax devices use the default PD threshold of
% -82 dBm. For inter-BSS frames, more aggressive PD threshold values are
% applied to increase the number of parallel transmissions.
%
% This is the possible use case scenario of SR with BSS coloring.
%
% *Residential scenario* Consider a two-floored residential apartment.
%
% <<../srResidentialScenario.png>>
% 
% Each floor contains two BSSs and each BSS consists of an AP and an STA.
% In this scenario, SR with BSS coloring would improve the aggregate
% throughput of the network and throughput per BSS. This example models and
% simulates this use case scenario.

%% Model 802.11ax Residential Scenario with BSS Coloring
% This example demonstrates the communication in an 802.11ax network with
% four BSSs containing one AP and one station per BSS. These stations
% implement carrier-sense multiple access with collision avoidance
% (CSMA/CA) with physical carrier sense and virtual carrier sense. The
% physical carrier sensing uses the clear CCA mechanism to determine
% whether the medium is busy before transmitting. Whereas, the virtual
% carrier sensing uses the RTS/CTS handshake to prevent the hidden node
% problem. All the nodes implement virtual carrier sensing using dual
% network allocation vectors (NAVs) (Intra NAV and Basic NAV) defined in
% IEEE(R) P802.11ax(TM)/D4.1 Amendment [ <#11 1> ].
%
% <<../srNode.png>>
%
% *Node Configuration*
% 
% Specify a node as an AP or an STA through the |NodeType| mask parameter.
% To configure the node as an STA, you must specify the name of the AP node
% associated with it through the |AP Name| parameter. All the nodes
% configured as STA with the same |AP Name| belong to one BSS.
%
% In the Application Traffic Generator block, the |Destination Name|
% parameter of an AP is always configured to the STA nodes of the same BSS.
% Whereas, the |Destination Name| parameter of the STA node is always
% configured to the same value of the |AP Name| parameter.
%
% <<../srNodeConfig.png>>
%
% To view the components of the WLAN node, see the
% <docid:wlan_ug#example-WLANMultiNodeAbstractedPHYExample 802.11ax
% System-Level Simulation with Physical Layer Abstraction> example.
%
% *MAC Configuration*
% 
% Implement these steps to configure nodes to perform SR operation.
%
% # Set |PHY Tx Format| to HE format (|HE-SU| or |HE-EXT-SU| or
% |HE-MU-OFDMA|) in MAC configuration parameters.
% # To enable SR operation, select |Enable Spatial Reuse With BSS Color|
% option.
% # Specify the BSS color by setting the BSS Color field to a value in the
% range [1, 63]. All the nodes in a BSS must be configured to the same
% value of |BSS Color| field. Each BSS must have a unique BSS color.
% # Specify OBSS PD threshold by setting |OBSS PD Threshold| field to a
% value in the range [-62, -82].
%
% <<../srMACConfig.png>>

%% Simulations Results
% Run the simulation to visualize the parallel transmissions and get the
% aggregated throughput for BSS.
%
% * *Runtime visualization plot to show the time spent by each node on
% channel contention, transmission, and reception.*
%
% In this plot, the mapping of nodes to BSS is as shown:
%
% * BSS1 - Node1 and Node2
% * BSS2 - Node3 and Node4
% * BSS3 - Node5 and Node6 
% * BSS4 - Node7 and Node8 
%
% <<../srChannelOccupancy.png>>
%
% Observe that the nodes transmit the frames concurrently. Thus, the SR
% operation enables simultaneous transmission of data, resulting in
% efficient utilization of the channel.
%
% * *Per BSS aggregated throughput plot*
%
% <<../srPerBSSThroughput.png>>
%
% This plot shows the per BSS aggregated throughput of the network.
%
% You can analyze the impact of varying the OBSS PD threshold values on the
% aggregated network throughput by running the simulations detailed in the
% following sections.
%
% * *Impact of the offered load and OBSS PD threshold on the network
% throughput*
%
% In each BSS, specify the STA and AP, with the AP serving to its
% corresponding STA. To enable STA as transmitters, set |App State| of an
% Application Traffic Generator block to 'On'. For each BSS, configure the
% AP and STA with the values shown in this table.
%
% <html>
% <table border="1"><tr><th>Parameter</th><th>Value</th></tr>
% <tr><td> Packet size (bytes)</td><td> 1700 </td></tr>
% <tr><td> Packet Interval (seconds)</td><td> 0.0001 </td></tr>
% <tr><td> Access Category </td><td> Best Effort </td></tr>
% <tr><td> Max A-MPDU Subframes </td><td> 64 </td></tr>
% <tr><td> MCS </td><td> 0 </td></tr>
% <tr><td> PHY Tx Format </td><td> HE-SU </td></tr>
% <tr><td> Ack Policy </td><td> No Ack </td></tr>
% <tr><td> RTS Threshold (bytes) </td><td> 65535 </td></tr>
% <tr><td> Max Short Retries </td><td> 10 </td></tr>
% <tr><td> Max Long Retries </td><td> 10 </td></tr>
% <tr><td> Number of Transmit Chains </td><td> 1 </td></tr>
% <tr><td> Tx Queue Size (Per Destination and Per AC) </td><td> 64 </td></tr>
% <tr><td> Simulation time (sec) </td><td> 0.5 </td></tr>
% </table>
% </html>
%
% Vary the |OBSS PD Threshold| as -82, -72, -68, -65, -62, for each
% simulation. At the end of each simulation run, the obtained throughput
% value is retrieved from the |statistics.mat| file. Plot the impact of
% offered load and OBSS PD threshold on the network throughput.

%%
% This code plots the impact of offered load and OBSS PD threshold on the
% average network throughput, when AP is transmitting to its corresponding
% STA.

% Offered load (Mbps)
offeredLoad = [40 64 88 112 126 160];

% Throughput results for OBSS PD threshold -82 dBm at varying offered loads (Mbps)
throughput1 = [1.7640 1.7152 1.8524 1.8536 1.8020 1.8320];

% Throughput results for OBSS PD threshold -72 dBm at varying offered loads (Mbps)
throughput2 = [2.5900 2.3392 2.4860 2.4416 2.4820 2.5360];

% Throughput results for OBSS PD threshold -68 dBm at varying offered loads (Mbps)
throughput3 = [3.0040 2.9632 2.9964 2.8112 2.9036 3.0480];

% Throughput results for OBSS PD threshold -65 dBm at varying offered loads (Mbps)
throughput4 = [3.0400 3.2672 3.4012 3.2984 3.3388 3.4320];

% Throughput results for OBSS PD threshold -62 dBm at varying offered loads (Mbps)
throughput5 = [2.8780 2.9952 3.0140 3.3320 3.2708 3.2720];

% Get screen resolution
resolution = get(0, 'screensize');
screenWidth = resolution(3);
screenHeight = resolution(4);
figureWidth = screenWidth*0.7;
figureHeight = screenHeight*0.7;

% Create figure
figure('Position', [screenWidth*0.2, screenHeight*0.1, figureWidth, figureHeight])

% Retain plot
hold on

% Plot throughput obtained with OBSS PD threshold set to -82 dBm at varying
% offered loads (Mbps) and retain plot
plot(offeredLoad, throughput1,'-o')
hold on

% Plot throughput obtained with OBSS PD threshold set to -72 dBm at varying
% offered loads (Mbps) and retain plot
plot(offeredLoad, throughput2,'-x')
hold on

% Plot throughput obtained with OBSS PD threshold set to -68 dBm at varying
% offered loads (Mbps) and retain plot
plot(offeredLoad, throughput3,'-+')
hold on

% Plot throughput obtained with OBSS PD threshold set to -65 dBm at varying
% offered loads (Mbps) and retain plot
plot(offeredLoad, throughput4,'-s')
hold on

% Plot throughput obtained with OBSS PD threshold set to -62 dBm at varying
% offered loads (Mbps)
plot(offeredLoad, throughput5,'-d')
grid on

% Add X-label, Y-label, and legend
xlabel('Offered load (Mbps)')
ylabel('Throughput (Mbps)')
legend('No Spatial Reuse', 'Spatial Reuse OBSS PD -72 dBm', ...
    'Spatial Reuse OBSS PD -68 dBm', 'Spatial Reuse OBSS PD -65 dBm', ...
    'Spatial Reuse OBSS PD -62 dBm', 'Location', 'northeastoutside');

% Add title
title('Impact of offered load and OBSS PD threshold on the network throughput')

%%
% Observe that the network throughput is higher when SR operation is
% enabled. Also, throughput increases with an increase in the OBSS PD
% threshold.

%%
% * *Impact of OBSS PD threshold on the throughput of each BSS*
%
% Vary the OBSS PD threshold as -82, -77, -72, -67, and -62 dBm and plot
% the impact on the throughput of each BSS.

numOBSSPDValues = 5;

OBSSPDValues = {'-82', '-77', '-72', '-67', '-62'};

% Initial SR statistics
throughput = zeros(numOBSSPDValues, 1);

% Throughput results for BSS1 (Mbps)
throughputWithOutSpatialBSS1 = [2.1216 4.5696 4.5696 4.7328 3.318];

% Throughput results for BSS2 (Mbps)
throughputWithSpatialReuseBSS2 = [1.9040 1.0336 1.7952 1.1686 2.448];

% Throughput results for BSS3 (Mbps)
throughputWithSpatialReuseBSS3 = [2.0672 2.0128 1.1088 2.23 3.590];

% Throughput results for BSS4 (Mbps)
throughputWithSpatialReuseBSS4 = [1.1152 2.3120 4.1616 4.706 3.726];

% Create a plot matrix with different statistics.
PlotMatrix = [throughputWithOutSpatialBSS1' throughputWithSpatialReuseBSS2'...
    throughputWithSpatialReuseBSS3' throughputWithSpatialReuseBSS4'];

nextBarOffset = 1;

% Set colors for the bars
colors = [ 0.9294    0.6941    0.1255;
    0.4941    0.1843    0.5569;
    0.4667    0.6745    0.1882;
    0.3020    0.7451    0.9333;
    0.6353    0.0784    0.1843;];

% Get screen resolution
resolution = get(0, 'screensize');
screenWidth = resolution(3);
screenHeight = resolution(4);
figureWidth = screenWidth*0.7;
figureHeight = screenHeight*0.7;

% Create figure
figure('Name', 'MultiNode 802.11 Network (PHY and MAC) Statistics', ...
    'Position', [screenWidth*0.2, screenHeight*0.1, figureWidth, figureHeight]);

% Set figure axis.
figAxis = gca;
hold on

% Plot using the plot matrix created
for i = 1: 5
    bar(nextBarOffset, PlotMatrix(i,1), 'FaceColor', colors(1, :))
    nextBarOffset = nextBarOffset+1;
    bar(nextBarOffset, PlotMatrix(i,2), 'FaceColor', colors(2, :))
    nextBarOffset = nextBarOffset+1;
    bar(nextBarOffset, PlotMatrix(i,3), 'FaceColor', colors(3, :))
    nextBarOffset = nextBarOffset+1;
    bar(nextBarOffset, PlotMatrix(i,4), 'FaceColor', colors(4, :))
    nextBarOffset = nextBarOffset+6;
end
lastBarOffset = nextBarOffset;

% Set legend to the plot
legend('BSS1', 'BSS2', ...
    'BSS3', 'BSS4', 'Location', 'northeastoutside');

% Name X-axis of the plot
xlabel('OBSS PD Threshold (dBm)')

% Name Y-axis of the plot
ylabel('Throughput (Mbps)')

% Gap between each tick on X-axis
tickInterval = (lastBarOffset-1)/numOBSSPDValues;

% Create ticks for X-axis
xticks(1:tickInterval:numOBSSPDValues*tickInterval)

% Add created tick labels to axis
figAxis.XTickLabel = OBSSPDValues;

% Add title
title('Impact of OBSS PD threshold on the throughput of each BSS')

%%
% Observe the increase in the throughput with SR as compared to no SR (OBSS
% PD Threshold -82 dBm). As OBSS PD threshold increases, PHY discards more
% frames that are detected as inter-BSS, enabling the STAs to transmit the
% frames concurrently. Consequently, you can also see that the throughput
% increases with OBSS PD threshold.
%
% Running the simulation using the configuration parameters specified in
% the preceding table:
%
% * For BSS1 & BSS4, maximum throughput is achieved when OBSS PD threshold
% is set to -67 dBm.
% * For BSS2 & BSS3, maximum throughput is achieved when OBSS PD threshold
% is set to -62 dBm.
% 
% You can simulate the model for multiple runs to visualize the true impact
% of OBSS PD threshold values on the network throughput.
%
% This example enables you to model a residential scenario in a multinode
% IEEE 802.11ax network to study SR with BSS coloring. The spatial reuse
% with BSS coloring support is added to the PHY and MAC library blocks.The
% model uses the constant OBSS PD algorithm to select an OBSS PD threshold.
% The simulation results validate that the throughput performance and
% channel efficiency increases by using SR with BSS coloring.

%% Further Exploration
% This example uses the constant OBSS PD algorithm. This algorithm decides
% whether the incoming OBSS frame must be allowed for further processing
% or discarded based on a configured OBSS PD value. The OBSS PD value can
% be varied by custom user-specific algorithm that may use various PHY and
% MAC level measurements. You can modify the OBSS PD algorithm by updating
% the <matlab:edit('constantOBSSPDAlgorithm.m')
% constantOBSSPDAlgorithm> helper function used by the |EDCA MAC| block
% present in the MAC layer.
%
% In this example, multi-BSS configuration is possible only when SR is
% enabled. To compare the results of a multi-BSS scenario with and without
% SR operation, configure the same value for |OBSS PD Threshold| and |ED
% Threshold| parameters to simulate non-SR operation without actually
% disabling the |Enable Spatial Reuse with BSS Color| parameter.

%% Appendix
% The example uses these helpers:
%
% # <matlab:edit('edcaAssignBSSIDs.m') edcaAssignBSSIDs.m>: Assign BSS IDs 
% # <matlab:edit('edcagetBSSInfo.m') edcagetBSSInfo.m>: Return BSS
% information
% # <matlab:edit('edcaValidateBSS.m') edcaValidateBSS.m>: Validate the BSS
% # <matlab:edit('hDisplayNetworkStats.m') hDisplayNetworkStats.m>: Display
% per BSS aggregated throughput
% # <matlab:edit('constantOBSSPDAlgorithm.m') constantOBSSPDAlgorithm.m>:
% Create a constant OBSS PD algorithm object.
% # <matlab:edit('obssPDAlgorithm.m') obssPDAlgorithm.m>: Create a OBSS PD
% algorithm object.
% # <matlab:edit('edcaFrameFormats.m') edcaFrameFormats.m>: Create an
% enumeration for PHY frame formats.
% # <matlab:edit('edcaNodeInfo.m') edcaNodeInfo.m>: Return MAC address of
% a node.
% # <matlab:edit('edcaPlotQueueLengths.m') edcaPlotQueueLengths.m>: Plot
% MAC queue lengths in the simulation.
% # <matlab:edit('edcaPlotStats.m') edcaPlotStats.m>: Plot MAC state
% transitions with respect to simulation times.
% # <matlab:edit('edcaStats.m') edcaStats.m>: Create an enumeration for
% simulation statistics.
% # <matlab:edit('edcaUpdateStats.m') edcaUpdateStats.m>: Update simulation
% statistics.
% # <matlab:edit('helperSubframeBoundaries.m') helperSubframeBoundaries.m>
% : Return subframe  boundaries of an A-MPDU.
% # <matlab:edit('phyTxAbstracted.m') phyTxAbstracted>: Model PHY
% operations related to packet transmission
% # <matlab:edit('phyRxAbstracted.m') phyRxAbstracted>: Model PHY
% operations related to packet reception
% # <matlab:edit('channelBlock.m') channelBlock>: Model the channel for a
% node
% # <matlab:edit('addMUPadding.m') addMUPadding.m>: Add or remove the
% padding difference between an HE-SU and HE-MU PSDU
% # <matlab:edit('macQueueManagement.m') macQueueManagement.m>: Create a
% WLAN MAC queue management object
% # <matlab:edit('roundRobinScheduler.m') roundRobinScheduler.m>: Create
% round-robin scheduler object
% # <matlab:edit('calculateSubframesCount.m') calculateSubframesCount.m>:
% Calculate the number of subframes required to form MU-PSDU
% # <matlab:edit('hCreateWLANNetworkModel.m') hCreateWLANNetworkModel>:
% Create a WLAN network with given number of nodes
% # <matlab:edit('hSetupAbstractChannel.m') hSetupAbstractChannel>: TGax
% channel setup
% # <matlab:edit('rateAdaptationARF.m') rateAdaptationARF.m>: Create an
% auto rate fallback (ARF) algorithm object.
% # <matlab:edit('rateAdaptationMinstrelNonHT.m')
% rateAdaptationMinstrelNonHT.m>: Create a minstrel algorithm object.

%% References
% # IEEE P802.11ax(TM)/D4.1. "Amendment 6: Enhancements for High Efficiency
% WLAN" Draft Standard for Information technology - Telecommunications
% and information exchange between systems Local and metropolitan area
% networks - Specific requirements -Part 11: Wireless LAN Medium Access
% Control (MAC) and Physical Layer (PHY) Specifications.
% # IEEE Std 802.11ac(TM) -2016. "Wireless LAN Medium Access Control (MAC)
% and Physical Layer (PHY) Specifications." IEEE Standard for Information
% technology-Telecommunications and information exchange between systems,
% Local and metropolitan area networks-Specific requirements.
% # Wilhelmi, Francesc, Sergio Barrachina Munoz, Cristina Cano, Ioannis
% Selinis, and Boris Bellalta. "Spatial Reuse in IEEE 802.11ax WLANs."
% ArXiv:1907.04141 [Cs], November 29, 2019.
% # Wilhelmi, Francesc, Sergio Barrachina-Munoz, and Boris Bellalta. "On
% the Performance of the Spatial Reuse Operation in IEEE 802.11ax WLANs."
% In 2019 _IEEE Conference on Standards for Communications and Networking
% (CSCN)_ , 1-6, 2019.