%% 802.11ax Multinode System-Level Simulation of Residential Scenario Using MATLAB
% This example shows how to model performance of an IEEE® 802.11ax™ [1] network in a residential scenario by using WLAN Toolbox™.
% Using this example, you can:
% Model a residential scenario by configuring the network and channel parameters.
% Simulate a multinode WLAN system and visualize the network-related statistics.
% Simulate the network by switching between the abstracted and full model of medium access control (MAC) and physical layer (PHY).
% The simulation results show the performance metrics such as throughput, latency, and packet loss.
% Table of Contents
% Residential Scenario Description
% Configuration Parameters
%     Simulation Parameters
%     Residential Scenario Parameters
%     Node Parameters
% Create Network
% Simulation
% Results
% Further Exploration
% References
%
%% Residential Scenario Description
% This example demonstrates a system-level simulation to evaluate the performance of an 802.11ax network in a residential scenario. The residential scenario consists of a building with 3 floors. These are the characteristics of the residential scenario:
% The spacing between the floors is 1.5 meters.
% Each floor consists of four rooms, each having dimensions 10m x 10m x 3m.
%  Each room has an access point (AP) and two stations (STAs) placed in random x- and y- locations at a height of 1.5 meters from the floor.
% Each AP has data for STAs present in the same room.
% The simulation scenario specifies a path loss model based on the distance between the nodes, and the number of walls and floors traversed by the WLAN signal. This figure shows the residential scenario simulated in this example.
%
% This example models the MAC layer and PHY of all the nodes (APs and STAs) using abstractions. The MAC layer implements enhanced distributed channel access (EDCA) functionality. The MAC layer uses abstraction for frame generation and decoding. Abstraction refers to the fact that MAC layer sends and receives frame metadata instead of sending or receiving encoded MAC frame bytes. Similarly, the PHY uses abstraction for WLAN signal generation and decoding. For more information on PHY abstraction, see Physical Layer Abstraction for System-Level Simulation example.
% This example is calibrated against Box-3 and Box-5 scenarios specified in TGax evaluation methodology [2]. The network throughput calculated for the scenarios mentioned in TGax simulation scenarios document [3] are validated against the published calibration results from the TGax Task Group, to confirm compliance with IEEE 802.11.
%
%% Configuration Parameters
%% Simulation Parameters
% Specify the simulation time (in milliseconds) by using the simulationTime variable. To visualize a live state transition plot for all nodes, set the showLiveStateTransitionPlot variable to true. To visualize the table containing network statistics at the end of simulation, set displayStatistics variable to true.
% Set the seed for the random number generator to 1. The seed value controls the pattern of random number generation. The random number generated by the seed value impacts the backoff counter selection at the MAC and path loss modeling at the PHY. For high fidelity simulation results, change the seed value and average the results over multiple simulations.

rng(1, 'combRecursive');                % Seed for random number generator
simulationTime = 100;                   % Simulation time in milliseconds
showLiveStateTransitionPlot = true;     % Show live state transition plot for all nodes
displayStatistics = true;               % Display statistics at the end of the simulation

% Add the folder to the path for access to all helper files
addpath(genpath(fullfile(pwd, 'mlWLANSystemSimulation')));

%% Residential Scenario Parameters
% The ScenarioParameters structure defines the size and layout of the residential building using these parameters.
% BuildingLayout: Specifies the building layout in terms of number of rooms in each of the three directions
% RoomSize: Specifies the size of each room in meters
% NumRxPerRoom: Specifies the number of stations per room
% The example assumes one transmitting AP and two receiving STAs in each room. The hDropNodes function randomly generates the positions of the AP and STAs within each room.

ScenarioParameters = struct;
% Number of rooms in [x,y,z] directions
ScenarioParameters.BuildingLayout = [2 2 3];
% Size of each room in meters [x,y,z]
ScenarioParameters.RoomSize = [10 10 3];
% Number of STAs per room
ScenarioParameters.NumRxPerRoom = 2;

% Obtain random positions for placing nodes
[apPositions, staPositions] = hDropNodes(ScenarioParameters);

%% Node Parameters
% The hLoadConfiguration function loads the MAC and PHY configurations for the nodes specified by nodeConfigs and loads the application traffic configuration for the transmitting nodes specified by trafficConfigs. This function assigns identifiers (IDs) and positions to all the nodes in the network.

% Get the IDs and positions of each node
[nodeConfigs, trafficConfigs] = hLoadConfiguration(ScenarioParameters, apPositions, staPositions);

% The wlanNodeConfig.mat file defines the structure for specifying the MAC and PHY configuration of a node. For more information about the detailed configuration parameters in this MAT file, use the command hConfigurationHelp('wlanNodeConfig'). The nodeConfigs output of the hLoadConfiguration function is an array of these structures. You can modify the MAC configuration parameters such as format, channel bandwidth, modulation and coding scheme (MCS) index, for the transmitted packets. You can also modify the physical layer parameters such as transmit power, transmit gain, receive gain, noise power. For example, this code configures node-1 to transmit packets with a fixed MCS-6.

nodeConfigs(1).TxMCS = 6

% The wlanTrafficConfig.mat file defines the structure for specifying the application traffic configuration. For more information about the detailed configuration parameters in this MAT file, use the command hConfigurationHelp('wlanTrafficConfig'). The trafficConfigs output of the hLoadConfiguration function is an array of these structures. Each structure corresponds to a specific destination STA node. You can modify parameters like packet size, data rate, or access category for each application in the array. The simulation scenario in this example configures the Best Effort (AC0) traffic from APs to STAs. For example, the first structure in the array specifies application traffic for node-1 (AP) to node-13 (STA). For example, this code configures the transmission of 1000 byte-sized application packets from node-1 to node-13. All other transmitters use a default packet size of 1500 bytes.

trafficConfigs(1).PacketSize = 1000

%
%% Create Network
% Create transmitter and receiver sites from the node configurations. Create the building geometry from the scenario parameters.

% Create transmitter and receiver sites
[txs,rxs] = hCreateSitesFromNodes(nodeConfigs);

% Create triangulation object and visualize the scenario
tri = hTGaxResidentialTriangulation(ScenarioParameters);
hVisualizeScenario(tri,txs,rxs,apPositions);

% This example uses the TGax residential propagation model to determine pathloss between nodes. Path loss is a function of the number of walls, number of floors, and the distance between nodes. Create a path loss model by using hTGaxResidentialPathLoss function.

propModel = hTGaxResidentialPathLoss('Triangulation',tri,'ShadowSigma',0,'FacesPerWall',1);

% Obtain the path loss between each pair of nodes in the network by using the hCreatePathlossTable helper function.

[pl,tgaxIndoorPLFn] = hCreatePathlossTable(txs,rxs,propModel);

% The hCreateWLANNodes helper function enables you to:
% Create WLAN nodes with the APP, MAC, and PHY layers configured with preceding parameters
% Add custom algorithms at the APP, MAC, and PHY layers by modifying the code related to algorithm configuration in hCreateWLANNodes
% By default, the hCreateWLANNodes helper function configures abstracted MAC and PHY at each WLAN node.
% At transmitter and receiver, modeling full MAC processing involves complete MAC frame generation at the MAC layer. Similarly, modeling full PHY processing involves complete operations related to waveform transmission and reception through a fading channel. When simulating large networks, full MAC and PHY processing is computationally expensive.
% In abstracted MAC, the node does not generate or decode any frames at the MAC layer. Similarly, in abstracted PHY, the node does not generate or decode any waveforms at the PHY. MAC and PHY abstraction enable you to minimize the complexity and duration of the system-level simulations. For more information on PHY abstraction, see Physical Layer Abstraction for System-Level Simulation example.
% The hCreateWLANNodes helper function enables you to switch between abstracted and full MAC or PHY by configuring the MACFrameAbstraction and PHYAbstractionType input parameters. The valid values for these parameters are:
% MACFrameAbstraction: true or false
% PHYAbstractionType: ‘TGax Evaluation Methodology Appendix 1’ (default), ‘TGax Simulation Scenarios MAC Calibration’ or ‘None’
% If you set the the PHYAbstractionType to 'TGax Evaluation Methodology Appendix 1', the PHY estimates the performance of a link with the TGax channel model by using an effective signal-to-interference-plus-noise ratio (SINR) mapping. Alternatively, the 'TGax Simulation Scenarios MAC Calibration' value of PHYAbstractionType assumes a packet failure on interference without actually calculating the link performance. To use full PHY set the value of PHYAbstractionType to 'None'.

MACFrameAbstraction = true;
PHYAbstractionType  = "TGax Evaluation Methodology Appendix 1";

wlanNodes = hCreateWLANNodes(nodeConfigs, trafficConfigs, ...
'CustomPathLoss', tgaxIndoorPLFn, 'MACFrameAbstraction', MACFrameAbstraction, 'PHYAbstractionType', PHYAbstractionType);

% This table shows you how to switch between the abstracted and full MAC or PHY by configuring the values of the MACFrameAbstraction and PHYAbstractionType input parameters.
%
%
%% Simulation
% To initialize the visualization parameters and simulate the WLAN scenario, use hStatsLogger and hWirelessNetworkSimulator helper functions, respectively.

% Initialize visualization parameters
visualizationInfo = struct;
visualizationInfo.Nodes = wlanNodes;
statsLogger = hStatsLogger(visualizationInfo);

if showLiveStateTransitionPlot
    hPlotStateTransition(visualizationInfo); % Configure state transition visualization
end

% Initialize wireless network simulator
networkSimulator = hWirelessNetworkSimulator(wlanNodes);

% The network simulator provides flexibility to schedule custom events in the simulation by using the scheduleEvent object function.
% For example, every time when you invoke the simulator you can schedule an event to refresh the state transition visualization. Specify the function handle, input argument, invocation time, and periodicity of the call back. For more information on scheduling events, enter this command at the MATLAB command prompt.
% help hWirelessNetworkSimulator.scheduleEvent

% When you run the script from the MATLAB command prompt, pause the
% execution to refresh visualization after  every 5 milliseconds
scheduleEvent(networkSimulator, @() pause(0.001), [], 0, 5);

% Run all the nodes in the network for the specified simulationTime time. Visualize the state transition periods of the nodes.

% Simulate wireless network
run(networkSimulator, simulationTime);

% Cleanup the persistent variables used in functions
clear hPlotStateTransition;

%
%% Results
% Retrieve the statistics and store them in a mat file. The UI table shows all the statistics collected during the simulation.

% Retrieve the statistics and store them in a mat file
statistics = getStatistics(statsLogger, displayStatistics);

% You can access all the statistics from the above table by exploring the statistics.mat file.

% Save the statistics to a mat file
save('statistics.mat', 'statistics');

% The hPlotNetworkStats helper function parses the collected statistics and plots the throughput, packet loss ratio, and average packet latency values at each node. The plot shows throughput and packet loss ratio at each transmitter (APs). The plot also shows the average packet latency experienced at each receiver node (STAs). The throughput shows the achieved data rate at each AP in units of megabits per second (Mbps). The packet loss ratio shows the ratio of unsuccessful data transmissions to the total data transmissions. The average packet latency shows the average latency experienced at each STA to receive its downlink traffic from the AP.

% Plot the throughput, packet loss ratio, and average packet latency at each node
hPlotNetworkStats(statistics, wlanNodes);
% Remove the folder from the path
rmpath(genpath(fullfile(pwd, 'mlWLANSystemSimulation')));

%
%% Further Exploration
% To observe the variation of throughput when a STA moves within a room, you can run the simulation for different positions of a STA with a fixed AP. You can observe the variation of throughput with respect to distance from its AP. The set of throughputs captured at all different positions can be used to plot a heatmap like the one shown here.
%
%
%% References
% IEEE P802.11ax™/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.
% “TGax simulation scenarios”, doc. IEEE 802.11-14/0980r16.
% “11ax evaluation methodology”, doc. IEEE 802.11-14/0571r12.
%
% Copyright 2021 The MathWorks, Inc.