A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
thompson-sampling-wifi-manager.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2021 IITP RAS
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Alexander Krotov <krotov@iitp.ru>
7 */
8
10
11#include "ns3/double.h"
12#include "ns3/log.h"
13#include "ns3/packet.h"
14#include "ns3/wifi-phy.h"
15
16#include <cstdint>
17#include <cstdlib>
18#include <fstream>
19#include <iostream>
20#include <string>
21
22namespace ns3
23{
24
25/**
26 * A structure containing parameters of a single rate and its
27 * statistics.
28 */
30{
31 WifiMode mode; ///< MCS
32 MHz_u channelWidth; ///< channel width
33 uint8_t nss; ///< Number of spatial streams
34
35 double success{0.0}; ///< averaged number of successful transmissions
36 double fails{0.0}; ///< averaged number of failed transmissions
37 Time lastDecay{0}; ///< last time exponential decay was applied to this rate
38};
39
40/**
41 * Holds station state and collected statistics.
42 *
43 * This struct extends from WifiRemoteStation to hold additional
44 * information required by ThompsonSamplingWifiManager.
45 */
47{
48 size_t m_nextMode; //!< Mode to select for the next transmission
49 size_t m_lastMode; //!< Most recently used mode, used to write statistics
50
51 std::vector<RateStats> m_mcsStats; //!< Collected statistics
52};
53
55
56NS_LOG_COMPONENT_DEFINE("ThompsonSamplingWifiManager");
57
60{
61 static TypeId tid =
62 TypeId("ns3::ThompsonSamplingWifiManager")
64 .SetGroupName("Wifi")
65 .AddConstructor<ThompsonSamplingWifiManager>()
66 .AddAttribute(
67 "Decay",
68 "Exponential decay coefficient, Hz; zero is a valid value for static scenarios",
69 DoubleValue(1.0),
72 .AddTraceSource("Rate",
73 "Traced value for rate changes (b/s)",
75 "ns3::TracedValueCallback::Uint64");
76 return tid;
77}
78
86
91
94{
95 NS_LOG_FUNCTION(this);
96 auto station = new ThompsonSamplingWifiRemoteStation();
97 station->m_nextMode = 0;
98 station->m_lastMode = 0;
99 return station;
100}
101
102void
104{
105 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
106 if (!station->m_mcsStats.empty())
107 {
108 return;
109 }
110
111 // Add HT, VHT or HE MCSes
112 for (const auto& mode : GetPhy()->GetMcsList())
113 {
114 for (MHz_u j{20}; j <= GetPhy()->GetChannelWidth(); j *= 2)
115 {
116 WifiModulationClass modulationClass = WIFI_MOD_CLASS_HT;
117 if (GetVhtSupported())
118 {
119 modulationClass = WIFI_MOD_CLASS_VHT;
120 }
121 if (GetHeSupported())
122 {
123 modulationClass = WIFI_MOD_CLASS_HE;
124 }
125 if (mode.GetModulationClass() == modulationClass)
126 {
127 for (uint8_t k = 1; k <= GetPhy()->GetMaxSupportedTxSpatialStreams(); k++)
128 {
129 if (mode.IsAllowed(j, k))
130 {
131 RateStats stats;
132 stats.mode = mode;
133 stats.channelWidth = j;
134 stats.nss = k;
135
136 station->m_mcsStats.push_back(stats);
137 }
138 }
139 }
140 }
141 }
142
143 if (station->m_mcsStats.empty())
144 {
145 // Add legacy non-HT modes.
146 for (uint8_t i = 0; i < GetNSupported(station); i++)
147 {
148 RateStats stats;
149 stats.mode = GetSupported(station, i);
152 {
153 stats.channelWidth = MHz_u{22};
154 }
155 else
156 {
157 stats.channelWidth = MHz_u{20};
158 }
159 stats.nss = 1;
160 station->m_mcsStats.push_back(stats);
161 }
162 }
163
164 NS_ASSERT_MSG(!station->m_mcsStats.empty(), "No usable MCS found");
165
166 UpdateNextMode(st);
167}
168
169void
171{
172 NS_LOG_FUNCTION(this << station << rxSnr << txMode);
173}
174
175void
180
181void
183{
184 NS_LOG_FUNCTION(this << st);
186 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
187 Decay(st, station->m_lastMode);
188 station->m_mcsStats.at(station->m_lastMode).fails++;
189 UpdateNextMode(st);
190}
191
192void
194 double ctsSnr,
195 WifiMode ctsMode,
196 double rtsSnr)
197{
198 NS_LOG_FUNCTION(this << st << ctsSnr << ctsMode.GetUniqueName() << rtsSnr);
199}
200
201void
203{
205 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
206
207 double maxThroughput = 0.0;
208 double frameSuccessRate = 1.0;
209
210 NS_ASSERT(!station->m_mcsStats.empty());
211
212 // Use the most robust MCS if frameSuccessRate is 0 for all MCS.
213 station->m_nextMode = 0;
214
215 for (uint32_t i = 0; i < station->m_mcsStats.size(); i++)
216 {
217 Decay(st, i);
218 const auto mode{station->m_mcsStats.at(i).mode};
219
220 const auto guardInterval = GetModeGuardInterval(st, mode);
221 const auto rate = mode.GetDataRate(station->m_mcsStats.at(i).channelWidth,
222 guardInterval,
223 station->m_mcsStats.at(i).nss);
224
225 // Thompson sampling
226 frameSuccessRate = SampleBetaVariable(1.0 + station->m_mcsStats.at(i).success,
227 1.0 + station->m_mcsStats.at(i).fails);
228 NS_LOG_DEBUG("Draw success=" << station->m_mcsStats.at(i).success
229 << " fails=" << station->m_mcsStats.at(i).fails
230 << " frameSuccessRate=" << frameSuccessRate
231 << " mode=" << mode);
232 if (frameSuccessRate * rate > maxThroughput)
233 {
234 maxThroughput = frameSuccessRate * rate;
235 station->m_nextMode = i;
236 }
237 }
238}
239
240void
242 double ackSnr,
243 WifiMode ackMode,
244 double dataSnr,
245 MHz_u dataChannelWidth,
246 uint8_t dataNss)
247{
248 NS_LOG_FUNCTION(this << st << ackSnr << ackMode.GetUniqueName() << dataSnr);
250 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
251 Decay(st, station->m_lastMode);
252 station->m_mcsStats.at(station->m_lastMode).success++;
253 UpdateNextMode(st);
254}
255
256void
258 uint16_t nSuccessfulMpdus,
259 uint16_t nFailedMpdus,
260 double rxSnr,
261 double dataSnr,
262 MHz_u dataChannelWidth,
263 uint8_t dataNss)
264{
265 NS_LOG_FUNCTION(this << st << nSuccessfulMpdus << nFailedMpdus << rxSnr << dataSnr);
267 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
268
269 Decay(st, station->m_lastMode);
270 station->m_mcsStats.at(station->m_lastMode).success += nSuccessfulMpdus;
271 station->m_mcsStats.at(station->m_lastMode).fails += nFailedMpdus;
272
273 UpdateNextMode(st);
274}
275
276void
281
282void
287
288Time
290{
292 {
293 return std::max(GetGuardInterval(st), GetGuardInterval());
294 }
295 else if ((mode.GetModulationClass() == WIFI_MOD_CLASS_HT) ||
297 {
299 return NanoSeconds(useSgi ? 400 : 800);
300 }
301 else
302 {
303 return NanoSeconds(800);
304 }
305}
306
309{
310 NS_LOG_FUNCTION(this << st << allowedWidth);
312 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
313
314 auto& stats = station->m_mcsStats.at(station->m_nextMode);
315 const auto mode = stats.mode;
316 const auto channelWidth = std::min(stats.channelWidth, allowedWidth);
317 const auto nss = stats.nss;
318 const auto guardInterval = GetModeGuardInterval(st, mode);
319
320 station->m_lastMode = station->m_nextMode;
321
322 NS_LOG_DEBUG("Using mode=" << mode << " channelWidth=" << channelWidth << " nss=" << +nss
323 << " guardInterval=" << guardInterval);
324
325 const auto rate = mode.GetDataRate(channelWidth, guardInterval, nss);
326 if (m_currentRate != rate)
327 {
328 NS_LOG_DEBUG("New datarate: " << rate);
329 m_currentRate = rate;
330 }
331
332 return WifiTxVector(
333 mode,
335 GetPreambleForTransmission(mode.GetModulationClass(), GetShortPreambleEnabled()),
336 GetModeGuardInterval(st, mode),
338 nss,
339 0, // NESS
340 GetPhy()->GetTxBandwidth(mode, channelWidth),
341 GetAggregation(station),
342 false);
343}
344
347{
348 NS_LOG_FUNCTION(this << st);
350 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
351
352 // Use the most robust MCS for the control channel.
353 auto& stats = station->m_mcsStats.at(0);
354 WifiMode mode = stats.mode;
355 uint8_t nss = stats.nss;
356
357 // Make sure control frames are sent using 1 spatial stream.
358 NS_ASSERT(nss == 1);
359
360 return WifiTxVector(
361 mode,
364 GetModeGuardInterval(st, mode),
366 nss,
367 0, // NESS
368 GetPhy()->GetTxBandwidth(mode, stats.channelWidth),
369 GetAggregation(station),
370 false);
371}
372
373double
374ThompsonSamplingWifiManager::SampleBetaVariable(uint64_t alpha, uint64_t beta) const
375{
376 double X = m_gammaRandomVariable->GetValue(alpha, 1.0);
377 double Y = m_gammaRandomVariable->GetValue(beta, 1.0);
378 return X / (X + Y);
379}
380
381void
383{
384 NS_LOG_FUNCTION(this << st << i);
386 auto station = static_cast<ThompsonSamplingWifiRemoteStation*>(st);
387
388 Time now = Simulator::Now();
389 auto& stats = station->m_mcsStats.at(i);
390 if (now > stats.lastDecay)
391 {
392 const double coefficient = std::exp(m_decay * (stats.lastDecay - now).GetSeconds());
393
394 stats.success *= coefficient;
395 stats.fails *= coefficient;
396 stats.lastDecay = now;
397 }
398}
399
400int64_t
402{
403 NS_LOG_FUNCTION(this << stream);
404 m_gammaRandomVariable->SetStream(stream);
405 return 1;
406}
407
408} // namespace ns3
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:191
Thompson Sampling rate control algorithm.
void DoReportRxOk(WifiRemoteStation *station, double rxSnr, WifiMode txMode) override
This method is a pure virtual method that must be implemented by the sub-class.
void InitializeStation(WifiRemoteStation *station) const
Initializes station rate tables.
void DoReportDataFailed(WifiRemoteStation *station) override
This method is a pure virtual method that must be implemented by the sub-class.
TracedValue< uint64_t > m_currentRate
Trace rate changes.
Time GetModeGuardInterval(WifiRemoteStation *st, WifiMode mode) const
Returns guard interval for the given mode.
double SampleBetaVariable(uint64_t alpha, uint64_t beta) const
Sample beta random variable with given parameters.
WifiRemoteStation * DoCreateStation() const override
Ptr< GammaRandomVariable > m_gammaRandomVariable
Variable used to sample beta-distributed random variables.
void DoReportFinalRtsFailed(WifiRemoteStation *station) override
This method is a pure virtual method that must be implemented by the sub-class.
void DoReportFinalDataFailed(WifiRemoteStation *station) override
This method is a pure virtual method that must be implemented by the sub-class.
double m_decay
Exponential decay coefficient, Hz.
void DoReportRtsFailed(WifiRemoteStation *station) override
This method is a pure virtual method that must be implemented by the sub-class.
void DoReportDataOk(WifiRemoteStation *station, double ackSnr, WifiMode ackMode, double dataSnr, MHz_u dataChannelWidth, uint8_t dataNss) override
This method is a pure virtual method that must be implemented by the sub-class.
void DoReportAmpduTxStatus(WifiRemoteStation *station, uint16_t nSuccessfulMpdus, uint16_t nFailedMpdus, double rxSnr, double dataSnr, MHz_u dataChannelWidth, uint8_t dataNss) override
Typically called per A-MPDU, either when a Block ACK was successfully received or when a BlockAckTime...
void UpdateNextMode(WifiRemoteStation *station) const
Draws a new MCS and related parameters to try next time for this station.
int64_t AssignStreams(int64_t stream) override
Assign a fixed random variable stream number to the random variables used by this model.
WifiTxVector DoGetDataTxVector(WifiRemoteStation *station, MHz_u allowedWidth) override
WifiTxVector DoGetRtsTxVector(WifiRemoteStation *station) override
void DoReportRtsOk(WifiRemoteStation *station, double ctsSnr, WifiMode ctsMode, double rtsSnr) override
This method is a pure virtual method that must be implemented by the sub-class.
void Decay(WifiRemoteStation *st, size_t i) const
Applies exponential decay to MCS statistics.
Simulation virtual time values and global simulation resolution.
Definition nstime.h:95
a unique identifier for an interface.
Definition type-id.h:50
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1003
represent a single transmission mode
Definition wifi-mode.h:39
const std::string & GetUniqueName() const
Definition wifi-mode.cc:136
WifiModulationClass GetModulationClass() const
Definition wifi-mode.cc:172
Time GetGuardInterval() const
Return the shortest supported HE guard interval duration.
uint8_t GetNSupported(const WifiRemoteStation *station) const
Return the number of modes supported by the given station.
Ptr< WifiPhy > GetPhy() const
Return the WifiPhy.
bool GetAggregation(const WifiRemoteStation *station) const
Return whether the given station supports A-MPDU.
bool GetShortGuardIntervalSupported() const
Return whether the device has SGI support enabled.
bool GetVhtSupported() const
Return whether the device has VHT capability support enabled on the link this manager is associated w...
bool GetShortPreambleEnabled() const
Return whether the device uses short PHY preambles.
WifiMode GetSupported(const WifiRemoteStation *station, uint8_t i) const
Return whether mode associated with the specified station at the specified index.
bool GetHeSupported() const
Return whether the device has HE capability support enabled.
This class mimics the TXVECTOR which is to be passed to the PHY in order to define the parameters whi...
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:76
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Time NanoSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1364
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
WifiModulationClass
This enumeration defines the modulation classes per (Table 10-6 "Modulation classes"; IEEE 802....
@ WIFI_MOD_CLASS_HR_DSSS
HR/DSSS (Clause 16).
@ WIFI_MOD_CLASS_HT
HT (Clause 19).
@ WIFI_MOD_CLASS_VHT
VHT (Clause 22).
@ WIFI_MOD_CLASS_HE
HE (Clause 27).
@ WIFI_MOD_CLASS_DSSS
DSSS (Clause 15).
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeDoubleChecker()
Definition double.h:82
double MHz_u
MHz weak type.
Definition wifi-units.h:31
Ptr< const AttributeAccessor > MakeDoubleAccessor(T1 a1)
Definition double.h:32
WifiPreamble GetPreambleForTransmission(WifiModulationClass modulation, bool useShortPreamble)
Return the preamble to be used for the transmission.
A structure containing parameters of a single rate and its statistics.
uint8_t nss
Number of spatial streams.
double success
averaged number of successful transmissions
double fails
averaged number of failed transmissions
Time lastDecay
last time exponential decay was applied to this rate
Holds station state and collected statistics.
size_t m_nextMode
Mode to select for the next transmission.
std::vector< RateStats > m_mcsStats
Collected statistics.
size_t m_lastMode
Most recently used mode, used to write statistics.
hold per-remote-station state.