A Discrete-Event Network Simulator
API
matrix-topology.cc
Go to the documentation of this file.
1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2010 Egemen K. Cetinkaya, Justin P. Rohrer, and Amit Dandekar
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Egemen K. Cetinkaya <ekc@ittc.ku.edu>
19 * Author: Justin P. Rohrer <rohrej@ittc.ku.edu>
20 * Author: Amit Dandekar <dandekar@ittc.ku.edu>
21 *
22 * James P.G. Sterbenz <jpgs@ittc.ku.edu>, director
23 * ResiliNets Research Group https://resilinets.org/
24 * Information and Telecommunication Technology Center
25 * and
26 * Department of Electrical Engineering and Computer Science
27 * The University of Kansas
28 * Lawrence, KS USA
29 *
30 * Work supported in part by NSF FIND (Future Internet Design) Program
31 * under grant CNS-0626918 (Postmodern Internet Architecture) and
32 * by NSF grant CNS-1050226 (Multilayer Network Resilience Analysis and Experimentation on GENI)
33 *
34 * This program reads an upper triangular adjacency matrix (e.g. adjacency_matrix.txt) and
35 * node coordinates file (e.g. node_coordinates.txt). The program also set-ups a
36 * wired network topology with P2P links according to the adjacency matrix with
37 * nx(n-1) CBR traffic flows, in which n is the number of nodes in the adjacency matrix.
38 */
39
40// ---------- Header Includes -------------------------------------------------
41#include <iostream>
42#include <fstream>
43#include <sstream>
44#include <string>
45#include <vector>
46#include <cstdlib>
47
48#include "ns3/core-module.h"
49#include "ns3/network-module.h"
50#include "ns3/internet-module.h"
51#include "ns3/point-to-point-module.h"
52#include "ns3/applications-module.h"
53#include "ns3/global-route-manager.h"
54#include "ns3/mobility-module.h"
55#include "ns3/netanim-module.h"
56#include "ns3/assert.h"
57#include "ns3/ipv4-global-routing-helper.h"
58
59using namespace ns3;
60
61// ---------- Prototypes ------------------------------------------------------
62
63std::vector<std::vector<bool>> readNxNMatrix (std::string adj_mat_file_name);
64std::vector<std::vector<double>> readCordinatesFile (std::string node_coordinates_file_name);
65void printCoordinateArray (const char* description, std::vector<std::vector<double>> coord_array);
66void printMatrix (const char* description, std::vector<std::vector<bool>> array);
67
68NS_LOG_COMPONENT_DEFINE ("GenericTopologyCreation");
69
70int main (int argc, char *argv[])
71{
72
73 // ---------- Simulation Variables ------------------------------------------
74
75 // Change the variables and file names only in this block!
76
77 double SimTime = 3.00;
78 double SinkStartTime = 1.0001;
79 double SinkStopTime = 2.90001;
80 double AppStartTime = 2.0001;
81 double AppStopTime = 2.80001;
82
83 std::string AppPacketRate ("40Kbps");
84 Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("1000"));
85 Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (AppPacketRate));
86 std::string LinkRate ("10Mbps");
87 std::string LinkDelay ("2ms");
88 // DropTailQueue::MaxPackets affects the # of dropped packets, default value:100
89 // Config::SetDefault ("ns3::DropTailQueue::MaxPackets", UintegerValue (1000));
90
91 srand ( (unsigned)time ( NULL ) ); // generate different seed each time
92
93 std::string tr_name ("n-node-ppp.tr");
94 std::string pcap_name ("n-node-ppp");
95 std::string flow_name ("n-node-ppp.xml");
96 std::string anim_name ("n-node-ppp.anim.xml");
97
98 std::string adj_mat_file_name ("examples/matrix-topology/adjacency_matrix.txt");
99 std::string node_coordinates_file_name ("examples/matrix-topology/node_coordinates.txt");
100
101 CommandLine cmd (__FILE__);
102 cmd.Parse (argc, argv);
103
104 // ---------- End of Simulation Variables ----------------------------------
105
106 // ---------- Read Adjacency Matrix ----------------------------------------
107
108 std::vector<std::vector<bool>> Adj_Matrix;
109 Adj_Matrix = readNxNMatrix (adj_mat_file_name);
110
111 // Optionally display 2-dimensional adjacency matrix (Adj_Matrix) array
112 // printMatrix (adj_mat_file_name.c_str (),Adj_Matrix);
113
114 // ---------- End of Read Adjacency Matrix ---------------------------------
115
116 // ---------- Read Node Coordinates File -----------------------------------
117
118 std::vector<std::vector<double>> coord_array;
119 coord_array = readCordinatesFile (node_coordinates_file_name);
120
121 // Optionally display node co-ordinates file
122 // printCoordinateArray (node_coordinates_file_name.c_str (),coord_array);
123
124 int n_nodes = coord_array.size ();
125 int matrixDimension = Adj_Matrix.size ();
126
127 if (matrixDimension != n_nodes)
128 {
129 NS_FATAL_ERROR ("The number of lines in coordinate file is: " << n_nodes << " not equal to the number of nodes in adjacency matrix size " << matrixDimension);
130 }
131
132 // ---------- End of Read Node Coordinates File ----------------------------
133
134 // ---------- Network Setup ------------------------------------------------
135
136 NS_LOG_INFO ("Create Nodes.");
137
138 NodeContainer nodes; // Declare nodes objects
139 nodes.Create (n_nodes);
140
141 NS_LOG_INFO ("Create P2P Link Attributes.");
142
144 p2p.SetDeviceAttribute ("DataRate", StringValue (LinkRate));
145 p2p.SetChannelAttribute ("Delay", StringValue (LinkDelay));
146
147 NS_LOG_INFO ("Install Internet Stack to Nodes.");
148
149 InternetStackHelper internet;
150 internet.Install (NodeContainer::GetGlobal ());
151
152 NS_LOG_INFO ("Assign Addresses to Nodes.");
153
154 Ipv4AddressHelper ipv4_n;
155 ipv4_n.SetBase ("10.0.0.0", "255.255.255.252");
156
157 NS_LOG_INFO ("Create Links Between Nodes.");
158
159 uint32_t linkCount = 0;
160
161 for (size_t i = 0; i < Adj_Matrix.size (); i++)
162 {
163 for (size_t j = 0; j < Adj_Matrix[i].size (); j++)
164 {
165
166 if (Adj_Matrix[i][j] == 1)
167 {
168 NodeContainer n_links = NodeContainer (nodes.Get (i), nodes.Get (j));
169 NetDeviceContainer n_devs = p2p.Install (n_links);
170 ipv4_n.Assign (n_devs);
171 ipv4_n.NewNetwork ();
172 linkCount++;
173 NS_LOG_INFO ("matrix element [" << i << "][" << j << "] is 1");
174 }
175 else
176 {
177 NS_LOG_INFO ("matrix element [" << i << "][" << j << "] is 0");
178 }
179 }
180 }
181 NS_LOG_INFO ("Number of links in the adjacency matrix is: " << linkCount);
182 NS_LOG_INFO ("Number of all nodes is: " << nodes.GetN ());
183
184 NS_LOG_INFO ("Initialize Global Routing.");
185 Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
186
187 // ---------- End of Network Set-up ----------------------------------------
188
189 // ---------- Allocate Node Positions --------------------------------------
190
191 NS_LOG_INFO ("Allocate Positions to Nodes.");
192
193 MobilityHelper mobility_n;
194 Ptr<ListPositionAllocator> positionAlloc_n = CreateObject<ListPositionAllocator> ();
195
196 for (size_t m = 0; m < coord_array.size (); m++)
197 {
198 positionAlloc_n->Add (Vector (coord_array[m][0], coord_array[m][1], 0));
199 Ptr<Node> n0 = nodes.Get (m);
201 if (nLoc == 0)
202 {
203 nLoc = CreateObject<ConstantPositionMobilityModel> ();
204 n0->AggregateObject (nLoc);
205 }
206 // y-coordinates are negated for correct display in NetAnim
207 // NetAnim's (0,0) reference coordinates are located on upper left corner
208 // by negating the y coordinates, we declare the reference (0,0) coordinate
209 // to the bottom left corner
210 Vector nVec (coord_array[m][0], -coord_array[m][1], 0);
211 nLoc->SetPosition (nVec);
212
213 }
214 mobility_n.SetPositionAllocator (positionAlloc_n);
215 mobility_n.Install (nodes);
216
217 // ---------- End of Allocate Node Positions -------------------------------
218
219 // ---------- Create n*(n-1) CBR Flows -------------------------------------
220
221 NS_LOG_INFO ("Setup Packet Sinks.");
222
223 uint16_t port = 9;
224
225 for (int i = 0; i < n_nodes; i++)
226 {
227 PacketSinkHelper sink ("ns3::UdpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), port));
228 ApplicationContainer apps_sink = sink.Install (nodes.Get (i)); // sink is installed on all nodes
229 apps_sink.Start (Seconds (SinkStartTime));
230 apps_sink.Stop (Seconds (SinkStopTime));
231 }
232
233 NS_LOG_INFO ("Setup CBR Traffic Sources.");
234
235 for (int i = 0; i < n_nodes; i++)
236 {
237 for (int j = 0; j < n_nodes; j++)
238 {
239 if (i != j)
240 {
241
242 // We needed to generate a random number (rn) to be used to eliminate
243 // the artificial congestion caused by sending the packets at the
244 // same time. This rn is added to AppStartTime to have the sources
245 // start at different time, however they will still send at the same rate.
246
247 Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
248 x->SetAttribute ("Min", DoubleValue (0));
249 x->SetAttribute ("Max", DoubleValue (1));
250 double rn = x->GetValue ();
251 Ptr<Node> n = nodes.Get (j);
252 Ptr<Ipv4> ipv4 = n->GetObject<Ipv4> ();
253 Ipv4InterfaceAddress ipv4_int_addr = ipv4->GetAddress (1, 0);
254 Ipv4Address ip_addr = ipv4_int_addr.GetLocal ();
255 OnOffHelper onoff ("ns3::UdpSocketFactory", InetSocketAddress (ip_addr, port)); // traffic flows from node[i] to node[j]
256 onoff.SetConstantRate (DataRate (AppPacketRate));
257 ApplicationContainer apps = onoff.Install (nodes.Get (i)); // traffic sources are installed on all nodes
258 apps.Start (Seconds (AppStartTime + rn));
259 apps.Stop (Seconds (AppStopTime));
260 }
261 }
262 }
263
264 // ---------- End of Create n*(n-1) CBR Flows ------------------------------
265
266 // ---------- Simulation Monitoring ----------------------------------------
267
268 NS_LOG_INFO ("Configure Tracing.");
269
270 AsciiTraceHelper ascii;
271 p2p.EnableAsciiAll (ascii.CreateFileStream (tr_name.c_str ()));
272 // p2p.EnablePcapAll (pcap_name.c_str());
273
274 // Ptr<FlowMonitor> flowmon;
275 // FlowMonitorHelper flowmonHelper;
276 // flowmon = flowmonHelper.InstallAll ();
277
278 // Configure animator with default settings
279
280 AnimationInterface anim (anim_name.c_str ());
281 NS_LOG_INFO ("Run Simulation.");
282
283 Simulator::Stop (Seconds (SimTime));
285 // flowmon->SerializeToXmlFile (flow_name.c_str(), true, true);
286 Simulator::Destroy ();
287
288 // ---------- End of Simulation Monitoring ---------------------------------
289
290 return 0;
291
292}
293
294// ---------- Function Definitions -------------------------------------------
295
296std::vector<std::vector<bool>> readNxNMatrix (std::string adj_mat_file_name)
297{
298 std::ifstream adj_mat_file;
299 adj_mat_file.open (adj_mat_file_name.c_str (), std::ios::in);
300 if (adj_mat_file.fail ())
301 {
302 NS_FATAL_ERROR ("File " << adj_mat_file_name.c_str () << " not found");
303 }
304 std::vector<std::vector<bool>> array;
305 int i = 0;
306 int n_nodes = 0;
307
308 while (!adj_mat_file.eof ())
309 {
310 std::string line;
311 getline (adj_mat_file, line);
312 if (line == "")
313 {
314 NS_LOG_WARN ("WARNING: Ignoring blank row in the array: " << i);
315 break;
316 }
317
318 std::istringstream iss (line);
319 bool element;
320 std::vector<bool> row;
321 int j = 0;
322
323 while (iss >> element)
324 {
325 row.push_back (element);
326 j++;
327 }
328
329 if (i == 0)
330 {
331 n_nodes = j;
332 }
333
334 if (j != n_nodes )
335 {
336 NS_LOG_ERROR ("ERROR: Number of elements in line " << i << ": " << j << " not equal to number of elements in line 0: " << n_nodes);
337 NS_FATAL_ERROR ("ERROR: The number of rows is not equal to the number of columns! in the adjacency matrix");
338 }
339 else
340 {
341 array.push_back (row);
342 }
343 i++;
344 }
345
346 if (i != n_nodes)
347 {
348 NS_LOG_ERROR ("There are " << i << " rows and " << n_nodes << " columns.");
349 NS_FATAL_ERROR ("ERROR: The number of rows is not equal to the number of columns! in the adjacency matrix");
350 }
351
352 adj_mat_file.close ();
353 return array;
354
355}
356
357std::vector<std::vector<double>> readCordinatesFile (std::string node_coordinates_file_name)
358{
359 std::ifstream node_coordinates_file;
360 node_coordinates_file.open (node_coordinates_file_name.c_str (), std::ios::in);
361 if (node_coordinates_file.fail ())
362 {
363 NS_FATAL_ERROR ("File " << node_coordinates_file_name.c_str () << " not found");
364 }
365 std::vector<std::vector<double>> coord_array;
366 int m = 0;
367
368 while (!node_coordinates_file.eof ())
369 {
370 std::string line;
371 getline (node_coordinates_file, line);
372
373 if (line == "")
374 {
375 NS_LOG_WARN ("WARNING: Ignoring blank row: " << m);
376 break;
377 }
378
379 std::istringstream iss (line);
380 double coordinate;
381 std::vector<double> row;
382 int n = 0;
383 while (iss >> coordinate)
384 {
385 row.push_back (coordinate);
386 n++;
387 }
388
389 if (n != 2)
390 {
391 NS_LOG_ERROR ("ERROR: Number of elements at line#" << m << " is " << n << " which is not equal to 2 for node coordinates file");
392 exit (1);
393 }
394
395 else
396 {
397 coord_array.push_back (row);
398 }
399 m++;
400 }
401 node_coordinates_file.close ();
402 return coord_array;
403
404}
405
406void printMatrix (const char* description, std::vector<std::vector<bool>> array)
407{
408 std::cout << "**** Start " << description << "********" << std::endl;
409 for (size_t m = 0; m < array.size (); m++)
410 {
411 for (size_t n = 0; n < array[m].size (); n++)
412 {
413 std::cout << array[m][n] << ' ';
414 }
415 std::cout << std::endl;
416 }
417 std::cout << "**** End " << description << "********" << std::endl;
418
419}
420
421void printCoordinateArray (const char* description, std::vector<std::vector<double>> coord_array)
422{
423 std::cout << "**** Start " << description << "********" << std::endl;
424 for (size_t m = 0; m < coord_array.size (); m++)
425 {
426 for (size_t n = 0; n < coord_array[m].size (); n++)
427 {
428 std::cout << coord_array[m][n] << ' ';
429 }
430 std::cout << std::endl;
431 }
432 std::cout << "**** End " << description << "********" << std::endl;
433
434}
435
436// ---------- End of Function Definitions ------------------------------------
void Run(ObjectFactory &factory, uint32_t pop, uint32_t total, uint32_t runs, Ptr< RandomVariableStream > eventStream, bool calRev)
Perform the runs for a single scheduler type.
Interface to network animator.
holds a vector of ns3::Application pointers.
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter.
void Stop(Time stop)
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
void EnableAsciiAll(std::string prefix)
Enable ascii trace output on each device (which is of the appropriate type) in the set of all nodes c...
Manage ASCII trace files for device models.
Definition: trace-helper.h:163
Ptr< OutputStreamWrapper > CreateFileStream(std::string filename, std::ios::openmode filemode=std::ios::out)
Create and initialize an output stream object we'll use to write the traced bits.
Parse command-line arguments.
Definition: command-line.h:229
Mobility model for which the current position does not change once it has been set and until it is se...
Class for representing data rates.
Definition: data-rate.h:89
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition: double.h:41
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Ipv4Address NewNetwork(void)
Increment the network number and reset the IP address counter to the base value provided in the SetBa...
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:41
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition: ipv4.h:77
a class to store IPv4 address information on an interface
Helper class used to assign positions and mobility models to nodes.
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
holds a vector of ns3::NetDevice pointers
keep track of a set of node pointers.
void SetAttribute(std::string name, const AttributeValue &value)
Set a single attribute, raising fatal errors if unsuccessful.
Definition: object-base.cc:256
Ptr< T > GetObject(void) const
Get a pointer to the requested aggregated Object.
Definition: object.h:470
void AggregateObject(Ptr< Object > other)
Aggregate two Objects together.
Definition: object.cc:252
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
Definition: on-off-helper.h:43
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Build a set of PointToPointNetDevice objects.
void SetDeviceAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each NetDevice created by the helper.
void SetChannelAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each Channel created by the helper.
NetDeviceContainer Install(NodeContainer c)
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:74
Hold variables of type string.
Definition: string.h:41
double GetValue(double min, double max)
Get the next random value, as a double in the specified range .
Vector3D Vector
Vector alias typedef for compatibility with mobility models.
Definition: vector.h:324
uint16_t port
Definition: dsdv-manet.cc:45
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:849
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:165
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition: log.h:257
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition: log.h:265
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:281
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1245
void printMatrix(const char *description, std::vector< std::vector< bool > > array)
std::vector< std::vector< double > > readCordinatesFile(std::string node_coordinates_file_name)
void printCoordinateArray(const char *description, std::vector< std::vector< double > > coord_array)
std::vector< std::vector< bool > > readNxNMatrix(std::string adj_mat_file_name)
nodes
Definition: first.py:28
Every class exported by the ns3 library is enclosed in the ns3 namespace.
cmd
Definition: second.py:43
Ptr< PacketSink > sink
Definition: wifi-tcp.cc:56