Gnuplot Helper
Gnuplot Helper
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
www.nsnam.org
$ wget https://www.nsnam.org/release/ns-allinone-3.28.tar.bz2
$ tar jxfv ns-allinone-3.28.tar.bz2
$ cd ns-allinone-3.28/ns-3.28
$ ./waf configure --enable-examples
$ ./waf
●
For eclipse: see
https://www.nsnam.org/wiki/HOWTO_configure_Eclipse_
with_ns-3
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
Ns-3 Objects
● Very important information to use and extend Ns-3
● Most objects inherit from ns3::Object
● Provides a range of useful properties for simulation
– Smart pointers SimpleRefCount
– Object aggregation
– Run-time type information Object
ObjectBase
– Attributes
– Trace sources
● Ns-3 objects are created with
CreateObject<Class> (constructor arguments)
Smart Pointers
● Provides a form of “garbage-collection”
● Enables object aggregation
● CreateObject returns smart pointer:
Ptr<PacketSocketFactory> factory =
CreateObject<PacketSocketFactory> ();
Ptr<MobilityModel> mob =
node>GetObject<MobilityModel> ();
node mobility
Run-Time Type Information
● All Ns-3 objects must implement TypeId GetTypeId(void)
● TypeId informs about attributes, runtime type information and
trace sources
TypeId
RoutingProtocol::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::olsr::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName ("Olsr")
.AddConstructor<RoutingProtocol> ()
.AddAttribute ("HelloInterval", "HELLO messages emission interval.",
TimeValue (Seconds (2)),
MakeTimeAccessor (&RoutingProtocol::m_helloInterval),
MakeTimeChecker ())
...
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
;
return tid;
}
Run-Time Type Information
● Objects, attributes and trace sources can be located
via textual paths via functions in the Config
namespace (objects):
TypeId
RoutingProtocol::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::olsr::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName ("Olsr")
.AddConstructor<RoutingProtocol> ()
...
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
...
Typecasting via object->GetObject<Class>
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
Config::SetDefault("ns3::olsr::RoutingProtocol::HelloInterval", TimeValue (Seconds(2)));
Config::Set("/NodeList/*/$ns3::olsr::RoutingProtocol/HelloInterval",
TimeValue(Seconds(5)));
routingProtocolObject>SetAttribute("HelloInterval", TimeValue(Seconds(1)));
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
Using Ns-3 – Via Example
● MANET with 25 nodes
– Based on 802.11g wifi
● Routing protocol: OLSR
● Workload: uniform UDP
traffic
– 500-byte packets, 20 pps OLSR UDP
– No background traffic
● Mobility: random walk
– Initial placement: 5 x ceil(5 / y)
grid
– y is the number of nodes
– 100 meters between nodes
● Duration 10 minutes
9 Steps of an ns-3 Simulation Script
1) Handle command line arguments
2) Set default attribute values and random
seed
3) Create nodes
4) Configure physical and MAC layers
5) Set up network stack, routing and
addresses
6) Configure and install applications
7) Set up initial positions and mobility
8) Set up data collection
9) Schedule user-defined events and
start simulation
Step 1: Command Line Arguments
● Enables parameterization of simulation from command line
int main (int argc, char *argv[])
{
...
// Obtain command line arguments
CommandLine cmd;
cmd.AddValue ("cols", "Columns of nodes", cols);
cmd.AddValue ("numnodes", "Number of nodes", numNodes);
cmd.AddValue ("spacing", "Spacing between neighbouring nodes", nodeSpacing);
cmd.AddValue ("duration", "Duration of simulation", duration);
cmd.AddValue ("seed", "Random seed for simulation", seed);
cmd.AddValue ("run", "Simulation run", run);
cmd.AddValue ("packetrate", "Packets transmitted per second", packetRate);
cmd.AddValue ("packetsize", "Packet size", packetSize);
cmd.AddValue ("sourcenode", "Number of source node", sourceNode);
cmd.AddValue ("destinationnode", "Number of destination node", destinationNode);
cmd.AddValue ("showtime", "show ... time ... (default = true)", showSimTime);
cmd.Parse (argc,argv);
...
For instance:
./waf –run “manet nodespacing=50 pktsize=100 packetrate=500”
Step 2: Set Attribute Values and
Random Seed
● Use Config::functions to set default
parameter values
● Remember to change run number between runs!
// Set default parameter values
Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
StringValue ("2200"));
Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold",
StringValue ("2200"));
// Set random seed and run number
SeedManager::SetSeed (seed);
SeedManager::SetRun (run);
$ for run in "1 2 3"; do ./waf –run “manet run=$run”; done
Step 3: Create Nodes
● Most objects in Ns-3 managed by containers
– Simulations consist of many objects of the same
type
– Later used by helper classes to install components
– Entities in containers obtained with
container>get()
c
// Create notes
NodeContainer c; …
c.Create (numNodes);
... 0 1 numNodes - 1
apps = client.Install (c.Get (sourceNode));
Step 4-7: Configure Nodes
● Nodes are initially empty hulls
Applications
Protocols
// Set up physical and mac layers
WifiHelper wifi = WifiHelper::Default ();
wifi.SetStandard (WIFI_PHY_STANDARD_80211g);
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
phy.SetChannel (wifiChannel.Create ());
NetDeviceContainer devices = wifi.Install (phy, wifiMac, c);
Step 4: Physical Layer
● New container:
devices
… …
// Set up physical and mac layers
WifiHelper wifi = WifiHelper::Default ();
wifi.SetStandard (WIFI_PHY_STANDARD_80211g);
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = wifiPhy;
phy.SetChannel (wifiChannel.Create ());
NetDeviceContainer devices = wifi.Install (phy, wifiMac, c);
Step 5: Install Internet Stack and
Routing Protocol
● Select routing protocol
– Ns-3 currently supports many routing protocols
(e.g., OLSR, AODV, DSDV, ...)
– Used in example: OLSR
● Internet stack: IP, TCP, UDP, ARP and ICMP
// Routing and Internet stack
ns3::OlsrHelper olsr;
InternetStackHelper internet;
internet.SetRoutingHelper(olsr);
…
internet.Install (c);
Step 5: Assign Addresses
● c>Get(X) gets
IP address 10.0.0.(X+1)
and
MAC address 00:00:00:00:00:(X+1)
// Assign addresses
Ipv4AddressHelper address;
address.SetBase ("10.0.0.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
Step 6: Install Applications
● In example: simple UDP server and client
● Set attributes
● Specify when applications start and stop
// Server/Receiver
UdpServerHelper server (4000);
ApplicationContainer apps = server.Install (c.Get(destinationNode));
apps.Start (Seconds (1));
apps.Stop (Seconds (duration 1));
// Client/Sender
UdpClientHelper client (interfaces.GetAddress (destinationNode), 4000);
client.SetAttribute ("MaxPackets", UintegerValue (100000000));
client.SetAttribute ("Interval", TimeValue (Seconds(1 / ((double) packetRate))));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
apps = client.Install (c.Get (sourceNode));
apps.Start (Seconds (1));
apps.Stop (Seconds (duration 1));
The Ns-3 Node
● Node provides pointers to devices and
applications
Ptr<Application> app = node>GetApplication(0);
Ptr<NetDevice> nic = node>GetDevice(0);
// Set up mobility
MobilityHelper mobility;
mobility.SetPositionAllocator (
"ns3::GridPositionAllocator",
"MinX", DoubleValue (1.0),
"MinY", DoubleValue (1.0),
"DeltaX", DoubleValue (nodeSpacing),
"DeltaY", DoubleValue (nodeSpacing),
"GridWidth", UintegerValue (cols));
cols
Step 7: Set Up Mobility Model
● Several alternatives
– Random waypoint, random walk, user defined, …
● Used in Example: Random walk
– Walk in random direction with random speed across fixed distance
● Reflect upon hitting scenario boundaries
– Speed defined with random variable
– Select new random direction
mobility.SetMobilityModel (
"ns3::RandomWalk2dMobilityModel",
"Bounds", RectangleValue
(Rectangle (0,(cols * nodeSpacing) + 1,
0,(rows * nodeSpacing) + 1)),
"Speed",
StringValue("ns3::UniformRandomVariable[Min=5.0,Max=10.0]"),
"Distance", DoubleValue(30));
mobility.Install (c);
Example Mobility, 10 minutes
Step 9: Schedule Initial Events and
Start Simulation
● Can schedule our own events before simulation
– Example: print virtual time once every simulated second
● Simulation duration should be set
void PrintSeconds(void) {
std::cerr << Simulator::Now() << std::endl;
Simulator::Schedule(Seconds(1), &PrintSeconds);
}
// Print simulated time
if(showSimTime)
Simulator::Schedule(Seconds(1), &PrintSeconds);
Simulator::Stop(Seconds(duration));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Step 8: Data Collection
● Collect results = important step!
● Several alternatives
1) std::cout << “Manual collection” << std::endl;
2) Packet tracing
3) Tracing subsystem
● Low-Level: Trace sources and sinks
● Medium/High-level: Data Collection Framework (DCF)
● Highest-level: Statistics framework
4) Logging via the logging facility (see doc.)
● Intended for testing, debugging and verification
Step 8: Data Collection
● Collect results = important step!
● Several alternatives
1) std::cout << “Manual collection” << std::endl;
2) Packet tracing
Covered here
3) Tracing subsystem
● Low-Level: Trace sources and sinks
● Medium/High-level: Data Collection Framework (DCF)
● Highest-level: Statistics framework
4) Logging via the logging facility (see doc.)
● Intended for testing, debugging and verification
Packet Tracing
● Highly detailed packet models = enables real-
world packet formats
● Popular packet capture format: PCAP
● One .pcap-file per node
● Pass device container from Step 4
● Set prefix (here “MANET”)
if(enablePcap)
wifiPhy.EnablePcap ("MANET", devices);
Packet Tracing
● Resulting files: <prefix>-<node>-<device>.pcap
AUTHORS MANET170.pcap routingtablewireless.xml
bindings MANET180.pcap scratch
build MANET190.pcap src
CHANGES.html MANET200.pcap test.py
doc MANET20.pcap testpy.supp
dumbbell.xml MANET210.pcap utils
examples MANET220.pcap utils.py
LICENSE MANET230.pcap utils.pyc
Makefile MANET240.pcap VERSION
MANET00.pcap MANET30.pcap waf
MANET100.pcap MANET40.pcap waf.bat
MANET10.pcap MANET50.pcap waftools
MANET110.pcap MANET60.pcap wirelessanimation.xml
MANET120.pcap MANET70.pcap wscript
MANET130.pcap MANET80.pcap wutils.py
MANET140.pcap MANET90.pcap wutils.pyc
MANET150.pcap README
MANET160.pcap RELEASE_NOTES
Can be opened in, e.g., Wireshark
Tracing Subsystem
● Based Ns-3 callbacks and attributes
● De-couples trace sources and sinks
class MyObject : public Object
{
Example trace source
public: (from Ns-3 manual)
static TypeId GetTypeId (void)
{
static TypeId tid = TypeId ("MyObject")
.SetParent (Object::GetTypeId ())
.AddConstructor<MyObject> ()
.AddTraceSource ("MyInteger",
"An integer value to trace.",
MakeTraceSourceAccessor (&MyObject::m_myInt))
;
return tid;
}
MyObject () {}
TracedValue<uint32_t> m_myInt;
};
Tracing Subsystem
● Based Ns-3 callbacks and attributes
● De-couples trace sources and sinks
int
main (int argc, char *argv[])
{
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject>TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
myObject>m_myInt = 1234;
}
Tracing Subsystem
● Based Ns-3 callbacks and attributes
● De-couples trace sources and sinks
int
main (int argc, char *argv[])
{Traced 0 to 1234
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject>TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
myObject>m_myInt = 1234;
}
Tracing Subsystem
● Objects, attributes and trace sources can be located
via textual paths using functions in the Config
namespace (trace sources):
TypeId
RoutingProtocol::GetTypeId (void)
{
...
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
...
void RouteChange(std::string source, uint32_t size) {
std::cout << "Routechange at " << source << ", new size: " << size << std::endl;
}
Config::Connect("/NodeList/*/$ns3::olsr::RoutingProtocol/RoutingTableChanged",
MakeCallback (&RouteChange));
routingProtocolObject>TraceConnect(“RoutingTableChanged”, “Context info”,
MakeCallback(&RouteChange));
Tracing Subsystem
● Objects, attributes and trace sources can be located
via textual paths via functions in the Config
namespace (trace sources):
TypeId
RoutingProtocol::GetTypeId (void)
Routechange at /NodeList/2/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 8
{
Routechange at /NodeList/11/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 13
...
Routechange at /NodeList/15/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 9
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
...
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
...
void RouteChange(std::string source, uint32_t size) {
Routechange at Source node, new size: 5
std::cout << "Routechange at " << source << ", new size: " << size << std::endl;
...
}
Config::Connect("/NodeList/*/$ns3::olsr::RoutingProtocol/RoutingTableChanged",
MakeCallback (&RouteChange));
routingProtocolObject>TraceConnect(“RoutingTableChanged”, “Source node”,
MakeCallback(&RouteChange));
Data Collection Framework (DCF)
● Based on tracing subsystem
● On-line data reduction and processing
● Output format marshaling
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
Data Collection Framework (DCF)
● Two helpers currently implemented:
– FileHelper
– GnuplotHelper
● Additional supported: SQLList and OMNet++
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
DCF Example: FileHelper
FileHelper fileHelper; ns-allinone-3.28/ns-
fileHelper.ConfigureFile ("seventh-packet-byte-count", 3.28/examples/tutorial
FileAggregator::FORMATTED); /seventh.cc
fileHelper.Set2dFormat ("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
fileHelper.WriteProbe (“ns3::Ipv4PacketProbe”,
“/NodeList/*/$ns3::Ipv4L3Protocol/Tx”,
"OutputBytes");
plotHelper.PlotProbe (“ns3::Ipv4PacketProbe”,
“/NodeList/*/$ns3::Ipv4L3Protocol/Tx”,
"OutputBytes",
"Packet Byte Count",
GnuplotAggregator::KEY_BELOW);
● Output:
seventh-packet-byte-count.dat (data file)
seventh-packet-byte-count.plt (gnuplot script)
seventh-packet-byte-count.sh (runs .plt)
Statistics Framework
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
Extending Ns-3 ns-allinone-3.28
$ createmodule.py ym
create-module.py
ym
● Creates five folders
– Your model in “model”
● MUST reconfigure before
re-compilation doc examples helper model test
$ ./waf configure enableexamples
$ ./waf ...
ym.cc ym.h
Resulting .cc and .h files in
model
... ...
#include "ym.h" #ifndef YM_H
#define YM_H
namespace ns3 {
namespace ns3 {
/* ... */
/* ... */
} }
#endif /* YM_H */
ym.cc ym.h
Resulting .cc and .h files in
helper
... ...
#include "ymhelper.h" #ifndef INF5090_HELPER_H
#define INF5090_HELPER_H
namespace ns3 {
#include "ns3/ym.h"
/* ... */
namespace ns3 {
} /* ... */
#endif /* INF5090_HELPER_H */
ym-helper.cc ym-helper.h
Resulting .cc and .h files in examples
example.cc:
/* * Mode:C++; cfilestyle:"gnu"; indenttabsmode:nil; * */
#include "ns3/coremodule.h"
#include "ns3/ymhelper.h"
using namespace ns3;
int
main (int argc, char *argv[])
{
bool verbose = true;
CommandLine cmd;
cmd.AddValue ("verbose", "Tell application to log if true", verbose);
cmd.Parse (argc,argv);
/* ... */
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
When Adding Files, Update wscript
...
def build(bld):
module = bld.create_ns3_module('ym', ['core']) ym
module.source = [
'model/ym.cc',
'helper/ymhelper.cc',
]
module_test = bld.create_ns3_module_test_library('ym')
module_test.source = [
'test/ymtestsuite.cc',
]
wscript
headers = bld(features='ns3header')
headers.module = 'ym'
headers.source = [
'model/ym.h',
'helper/ymhelper.h',
]
if bld.env.ENABLE_EXAMPLES:
bld.recurse('examples')
# bld.ns3_python_bindings()
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
● www.nsnam.org
● www.nsnam.org/wiki
● www.nsnam.org/documentation
– Ns-3 manual
– Ns-3 tutorial
https://www.nsnam.org/docs/release/3.28/tutorial/html/index.html
– Doxygen
– Slides
– Videos
– ...
● Examples in the source code
Appendix
Ipv4StaticRoutingHelper staticRouting;
InternetStackHelper internet;
internet.SetRoutingHelper(staticRouting);
internet.Install (nodes);
Step 6: Static Routing
Setting static routes
◦Use Ipv4StaticRoutingHelper
We provide a function to manipulate table
// Set addresses
// Set addresses
// Set addresses
[0,0,0] [nodeSpacing,0,0]
MobilityHelper mobility;
MobilityHelper mobility;
// Set positions
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install(nodes);
The logging facility
Ns-3 has an extensive logging facility
Seven levels: error, warn, debug, info,
function, logic, all
NS_LOG_COMPONENT_DEFINE ("MANET");
$ wget https://www.nsnam.org/release/ns-allinone-3.28.tar.bz2
$ tar jxfv ns-allinone-3.28.tar.bz2
$ cd ns-allinone-3.28/ns-3.28
$ ./waf configure --enable-examples
$ ./waf
Ptr<MobilityModel> mob =
node>GetObject<MobilityModel> ();
node mobility
Run-Time Type Information
● All Ns-3 objects must implement TypeId GetTypeId(void)
● TypeId informs about attributes, runtime type information and
trace sources
TypeId
RoutingProtocol::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::olsr::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName ("Olsr")
.AddConstructor<RoutingProtocol> ()
.AddAttribute ("HelloInterval", "HELLO messages emission interval.",
TimeValue (Seconds (2)),
MakeTimeAccessor (&RoutingProtocol::m_helloInterval),
MakeTimeChecker ())
...
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
;
return tid;
}
Run-Time Type Information
● Objects, attributes and trace sources can be located
via textual paths via functions in the Config
namespace (objects):
TypeId
RoutingProtocol::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::olsr::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName ("Olsr")
.AddConstructor<RoutingProtocol> ()
...
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
/NodeList/*
TypeId matches all nodes
RoutingProtocol::GetTypeId (void)
{ /NodeList/3/$ns3::Ipv4
matches object of type ns3::Ipv4 aggregated to node number 3
static TypeId tid = TypeId ("ns3::olsr::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName ("Olsr") /NodeList/3/DeviceList/*/$ns3::CsmaNetDevice
matches all devices of type ns3::CsmaNetDevice in node number 3
.AddConstructor<RoutingProtocol> ()
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
...
Typecasting via object->GetObject<Class>
Config::MatchContainer m =
Config::LookupMatches("NodeList/*/$ns3::olsr::RoutingProtocol”);
Ptr<Olsr::RoutingProtocol> olsr =
m.Get(0)>GetObject<Olsr::RoutingProtocol> ();
Config::SetDefault("ns3::olsr::RoutingProtocol::HelloInterval", TimeValue (Seconds(2)));
Config::Set("/NodeList/*/$ns3::olsr::RoutingProtocol/HelloInterval",
TimeValue(Seconds(5)));
routingProtocolObject>SetAttribute("HelloInterval", TimeValue(Seconds(1)));
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
Using Ns-3 – Via Example
● MANET with 25 nodes
– Based on 802.11g wifi
● Routing protocol: OLSR
● Workload: uniform UDP
traffic
– 500-byte packets, 20 pps OLSR UDP
– No background traffic
● Mobility: random walk
– Initial placement: 5 x ceil(5 / y)
grid
– y is the number of nodes
– 100 meters between nodes
● Duration 10 minutes
9 Steps of an ns-3 Simulation Script
1) Handle command line arguments
2) Set default attribute values and random
seed
3) Create nodes
4) Configure physical and MAC layers
5) Set up network stack, routing and
addresses
6) Configure and install applications
7) Set up initial positions and mobility
8) Set up data collection
9) Schedule user-defined events and
start simulation
Step 1: Command Line Arguments
● Enables parameterization of simulation from command line
int main (int argc, char *argv[])
{
...
// Obtain command line arguments
CommandLine cmd;
cmd.AddValue ("cols", "Columns of nodes", cols);
cmd.AddValue ("numnodes", "Number of nodes", numNodes);
cmd.AddValue ("spacing", "Spacing between neighbouring nodes", nodeSpacing);
cmd.AddValue ("duration", "Duration of simulation", duration);
cmd.AddValue ("seed", "Random seed for simulation", seed);
cmd.AddValue ("run", "Simulation run", run);
cmd.AddValue ("packetrate", "Packets transmitted per second", packetRate);
cmd.AddValue ("packetsize", "Packet size", packetSize);
cmd.AddValue ("sourcenode", "Number of source node", sourceNode);
cmd.AddValue ("destinationnode", "Number of destination node", destinationNode);
cmd.AddValue ("showtime", "show ... time ... (default = true)", showSimTime);
cmd.Parse (argc,argv);
...
For instance:
./waf –run “manet nodespacing=50 pktsize=100 packetrate=500”
Step 2: Set Attribute Values and
Random Seed
● Use Config::functions to set default
parameter values
● Remember to change run number between runs!
// Set default parameter values
Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
StringValue ("2200"));
Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold",
StringValue ("2200"));
// Set random seed and run number
SeedManager::SetSeed (seed);
SeedManager::SetRun (run);
$ for run in "1 2 3"; do ./waf –run “manet run=$run”; done
Step 3: Create Nodes
● Most objects in Ns-3 managed by containers
– Simulations consist of many objects of the same
type
– Later used by helper classes to install components
– Entities in containers obtained with
container>get()
c
// Create notes
NodeContainer c; …
c.Create (numNodes);
... 0 1 numNodes - 1
apps = client.Install (c.Get (sourceNode));
Step 4-7: Configure Nodes
● Nodes are initially empty hulls
Applications
Protocols
// Set up physical and mac layers
WifiHelper wifi = WifiHelper::Default ();
wifi.SetStandard (WIFI_PHY_STANDARD_80211g);
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
phy.SetChannel (wifiChannel.Create ());
NetDeviceContainer devices = wifi.Install (phy, wifiMac, c);
Step 4: Physical Layer
●
New container:
devices
… …
// Set up physical and mac layers
WifiHelper wifi = WifiHelper::Default ();
wifi.SetStandard (WIFI_PHY_STANDARD_80211g);
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = wifiPhy;
phy.SetChannel (wifiChannel.Create ());
NetDeviceContainer devices = wifi.Install (phy, wifiMac, c);
Step 5: Install Internet Stack and
Routing Protocol
● Select routing protocol
– Ns-3 currently supports many routing protocols
(e.g., OLSR, AODV, DSDV, ...)
– Used in example: OLSR
● Internet stack: IP, TCP, UDP, ARP and ICMP
// Routing and Internet stack
ns3::OlsrHelper olsr;
InternetStackHelper internet;
internet.SetRoutingHelper(olsr);
…
internet.Install (c);
Step 5: Assign Addresses
● c>Get(X) gets
IP address 10.0.0.(X+1)
and
MAC address 00:00:00:00:00:(X+1)
// Assign addresses
Ipv4AddressHelper address;
address.SetBase ("10.0.0.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
Step 6: Install Applications
● In example: simple UDP server and client
● Set attributes
● Specify when applications start and stop
// Server/Receiver
UdpServerHelper server (4000);
ApplicationContainer apps = server.Install (c.Get(destinationNode));
apps.Start (Seconds (1));
apps.Stop (Seconds (duration 1));
// Client/Sender
UdpClientHelper client (interfaces.GetAddress (destinationNode), 4000);
client.SetAttribute ("MaxPackets", UintegerValue (100000000));
client.SetAttribute ("Interval", TimeValue (Seconds(1 / ((double) packetRate))));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
apps = client.Install (c.Get (sourceNode));
apps.Start (Seconds (1));
apps.Stop (Seconds (duration 1));
The Ns-3 Node
● Node provides pointers to devices and
applications
Ptr<Application> app = node>GetApplication(0);
Ptr<NetDevice> nic = node>GetDevice(0);
// Set up mobility
MobilityHelper mobility;
mobility.SetPositionAllocator (
"ns3::GridPositionAllocator",
"MinX", DoubleValue (1.0),
"MinY", DoubleValue (1.0),
"DeltaX", DoubleValue (nodeSpacing),
"DeltaY", DoubleValue (nodeSpacing),
"GridWidth", UintegerValue (cols));
cols
Step 7: Set Up Mobility Model
● Several alternatives
– Random waypoint, random walk, user defined, …
● Used in Example: Random walk
– Walk in random direction with random speed across fixed distance
● Reflect upon hitting scenario boundaries
– Speed defined with random variable
– Select new random direction
mobility.SetMobilityModel (
"ns3::RandomWalk2dMobilityModel",
"Bounds", RectangleValue
(Rectangle (0,(cols * nodeSpacing) + 1,
0,(rows * nodeSpacing) + 1)),
"Speed",
StringValue("ns3::UniformRandomVariable[Min=5.0,Max=10.0]"),
"Distance", DoubleValue(30));
mobility.Install (c);
Example Mobility, 10 minutes
Step 9: Schedule Initial Events and
Start Simulation
● Can schedule our own events before simulation
– Example: print virtual time once every simulated second
● Simulation duration should be set
void PrintSeconds(void) {
std::cerr << Simulator::Now() << std::endl;
Simulator::Schedule(Seconds(1), &PrintSeconds);
}
// Print simulated time
if(showSimTime)
Simulator::Schedule(Seconds(1), &PrintSeconds);
Simulator::Stop(Seconds(duration));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Step 8: Data Collection
● Collect results = important step!
● Several alternatives
1) std::cout << “Manual collection” << std::endl;
2) Packet tracing
3) Tracing subsystem
● Low-Level: Trace sources and sinks
● Medium/High-level: Data Collection Framework (DCF)
● Highest-level: Statistics framework
4) Logging via the logging facility (see doc.)
● Intended for testing, debugging and verification
Step 8: Data Collection
● Collect results = important step!
● Several alternatives
1) std::cout << “Manual collection” << std::endl;
2) Packet tracing
Covered here
3) Tracing subsystem
● Low-Level: Trace sources and sinks
● Medium/High-level: Data Collection Framework (DCF)
● Highest-level: Statistics framework
4) Logging via the logging facility (see doc.)
● Intended for testing, debugging and verification
Packet Tracing
● Highly detailed packet models = enables real-
world packet formats
● Popular packet capture format: PCAP
● One .pcap-file per node
● Pass device container from Step 4
● Set prefix (here “MANET”)
if(enablePcap)
wifiPhy.EnablePcap ("MANET", devices);
Packet Tracing
● Resulting files: <prefix>-<node>-<device>.pcap
AUTHORS MANET170.pcap routingtablewireless.xml
bindings MANET180.pcap scratch
build MANET190.pcap src
CHANGES.html MANET200.pcap test.py
doc MANET20.pcap testpy.supp
dumbbell.xml MANET210.pcap utils
examples MANET220.pcap utils.py
LICENSE MANET230.pcap utils.pyc
Makefile MANET240.pcap VERSION
MANET00.pcap MANET30.pcap waf
MANET100.pcap MANET40.pcap waf.bat
MANET10.pcap MANET50.pcap waftools
MANET110.pcap MANET60.pcap wirelessanimation.xml
MANET120.pcap MANET70.pcap wscript
MANET130.pcap MANET80.pcap wutils.py
MANET140.pcap MANET90.pcap wutils.pyc
MANET150.pcap README
MANET160.pcap RELEASE_NOTES
Can be opened in, e.g., Wireshark
Tracing Subsystem
● Based Ns-3 callbacks and attributes
● De-couples trace sources and sinks
class MyObject : public Object
{
Example trace source
public: (from Ns-3 manual)
static TypeId GetTypeId (void)
{
static TypeId tid = TypeId ("MyObject")
.SetParent (Object::GetTypeId ())
.AddConstructor<MyObject> ()
.AddTraceSource ("MyInteger",
"An integer value to trace.",
MakeTraceSourceAccessor (&MyObject::m_myInt))
;
return tid;
}
MyObject () {}
TracedValue<uint32_t> m_myInt;
};
int
main (int argc, char *argv[])
{
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject>TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
myObject>m_myInt = 1234;
}
Tracing Subsystem
● Based Ns-3 callbacks and attributes
● De-couples trace sources and sinks
int
main (int argc, char *argv[])
{Traced 0 to 1234
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject>TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
myObject>m_myInt = 1234;
}
Tracing Subsystem
● Objects, attributes and trace sources can be located
via textual paths using functions in the Config
namespace (trace sources):
TypeId
RoutingProtocol::GetTypeId (void)
{
...
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
...
void RouteChange(std::string source, uint32_t size) {
std::cout << "Routechange at " << source << ", new size: " << size << std::endl;
}
Config::Connect("/NodeList/*/$ns3::olsr::RoutingProtocol/RoutingTableChanged",
MakeCallback (&RouteChange));
routingProtocolObject>TraceConnect(“RoutingTableChanged”, “Context info”,
MakeCallback(&RouteChange));
Tracing Subsystem
● Objects, attributes and trace sources can be located
via textual paths via functions in the Config
namespace (trace sources):
TypeId
RoutingProtocol::GetTypeId (void)
Routechange at /NodeList/2/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 8
{
Routechange at /NodeList/11/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 13
...
Routechange at /NodeList/15/$ns3::olsr::RoutingProtocol/RoutingTableChanged, new size: 9
.AddTraceSource ("RoutingTableChanged", "The OLSR routing table has changed.",
...
MakeTraceSourceAccessor (&RoutingProtocol::m_routingTableChanged),
"ns3::olsr::RoutingProtocol::TableChangeTracedCallback")
...
void RouteChange(std::string source, uint32_t size) {
Routechange at Source node, new size: 5
std::cout << "Routechange at " << source << ", new size: " << size << std::endl;
...
}
Config::Connect("/NodeList/*/$ns3::olsr::RoutingProtocol/RoutingTableChanged",
MakeCallback (&RouteChange));
routingProtocolObject>TraceConnect(“RoutingTableChanged”, “Source node”,
MakeCallback(&RouteChange));
Data Collection Framework (DCF)
● Based on tracing subsystem
● On-line data reduction and processing
● Output format marshaling
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
Data Collection Framework (DCF)
● Two helpers currently implemented:
– FileHelper
– GnuplotHelper
● Additional supported: SQLList and OMNet++
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
DCF Example: FileHelper
FileHelper fileHelper; ns-allinone-3.28/ns-
fileHelper.ConfigureFile ("seventh-packet-byte-count", 3.28/examples/tutorial
FileAggregator::FORMATTED); /seventh.cc
fileHelper.Set2dFormat ("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
fileHelper.WriteProbe (“ns3::Ipv4PacketProbe”,
“/NodeList/*/$ns3::Ipv4L3Protocol/Tx”,
"OutputBytes");
plotHelper.PlotProbe (“ns3::Ipv4PacketProbe”,
“/NodeList/*/$ns3::Ipv4L3Protocol/Tx”,
"OutputBytes",
"Packet Byte Count",
GnuplotAggregator::KEY_BELOW);
● Output:
seventh-packet-byte-count.dat (data file)
seventh-packet-byte-count.plt (gnuplot script)
seventh-packet-byte-count.sh (runs .plt)
https://www.nsnam.org/docs/release/3.28/manual/singlehtml/index.html#document-data-collection
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
Extending Ns-3 ns-allinone-3.28
$ createmodule.py ym
create-module.py
ym
●
Creates five folders
– Your model in “model”
● MUST reconfigure before
re-compilation doc examples helper model test
$ ./waf configure enableexamples
$ ./waf ...
ym.cc ym.h
Resulting .cc and .h files in
model
... ...
#include "ym.h" #ifndef YM_H
#define YM_H
namespace ns3 {
namespace ns3 {
/* ... */
/* ... */
} }
#endif /* YM_H */
ym.cc ym.h
Resulting .cc and .h files in
helper
... ...
#include "ymhelper.h" #ifndef INF5090_HELPER_H
#define INF5090_HELPER_H
namespace ns3 {
#include "ns3/ym.h"
/* ... */
namespace ns3 {
} /* ... */
#endif /* INF5090_HELPER_H */
ym-helper.cc ym-helper.h
Resulting .cc and .h files in examples
example.cc:
/* * Mode:C++; cfilestyle:"gnu"; indenttabsmode:nil; * */
#include "ns3/coremodule.h"
#include "ns3/ymhelper.h"
using namespace ns3;
int
main (int argc, char *argv[])
{
bool verbose = true;
CommandLine cmd;
cmd.AddValue ("verbose", "Tell application to log if true", verbose);
cmd.Parse (argc,argv);
/* ... */
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
When Adding Files, Update wscript
...
def build(bld):
module = bld.create_ns3_module('ym', ['core']) ym
module.source = [
'model/ym.cc',
'helper/ymhelper.cc',
]
module_test = bld.create_ns3_module_test_library('ym')
module_test.source = [
'test/ymtestsuite.cc',
]
wscript
headers = bld(features='ns3header')
headers.module = 'ym'
headers.source = [
'model/ym.h',
'helper/ymhelper.h',
]
if bld.env.ENABLE_EXAMPLES:
bld.recurse('examples')
# bld.ns3_python_bindings()
● About ns-3
● Installing ns-3
● Core concepts
– Ns-3 Objects
– Smart pointers
– Object aggregation
– Run-time type information
● Using Ns-3: step-by-step example
● Extending Ns-3
● Resources
● www.nsnam.org
● www.nsnam.org/wiki
● www.nsnam.org/documentation
– Ns-3 manual
– Ns-3 tutorial
https://www.nsnam.org/docs/release/3.28/tutorial/html/index.html
– Doxygen
– Slides
– Videos
– ...
● Examples in the source code
Appendix
Ipv4StaticRoutingHelper staticRouting;
InternetStackHelper internet;
internet.SetRoutingHelper(staticRouting);
internet.Install (nodes);
Step 6: Static Routing
Setting static routes
◦Use Ipv4StaticRoutingHelper
We provide a function to manipulate table
// Set addresses
// Set addresses
// Set addresses
[0,0,0] [nodeSpacing,0,0]
MobilityHelper mobility;
MobilityHelper mobility;
// Set positions
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install(nodes);
The logging facility
Ns-3 has an extensive logging facility
Seven levels: error, warn, debug, info,
function, logic, all
NS_LOG_COMPONENT_DEFINE ("MANET");