def main(argv): cmd = ns.core.CommandLine() cmd.NumNodesSide = None cmd.AddValue( "NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)" ) cmd.Results = None cmd.AddValue("Results", "Write XML results to file") cmd.Plot = None cmd.AddValue("Plot", "Plot the results using the matplotlib python module") cmd.Parse(argv) wifi = ns.wifi.WifiHelper.Default() wifiMac = ns.wifi.NqosWifiMacHelper.Default() wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) ssid = ns.wifi.Ssid("wifi-default") wifi.SetRemoteStationManager("ns3::ArfWifiManager") wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) internet = ns.internet.InternetStackHelper() list_routing = ns.internet.Ipv4ListRoutingHelper() olsr_routing = ns.olsr.OlsrHelper() static_routing = ns.internet.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns.internet.Ipv4AddressHelper() ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) port = 9 # Discard port(RFC 863) onOffHelper = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address( ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps"))) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) addresses = [] nodes = [] if cmd.NumNodesSide is None: num_nodes_side = NUM_NODES_SIDE else: num_nodes_side = int(cmd.NumNodesSide) for xi in range(num_nodes_side): for yi in range(num_nodes_side): node = ns.network.Node() nodes.append(node) internet.Install(ns.network.NodeContainer(node)) mobility = ns.mobility.ConstantPositionMobilityModel() mobility.SetPosition( ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0)) node.AggregateObject(mobility) devices = wifi.Install(wifiPhy, wifiMac, node) ipv4_interfaces = ipv4Addresses.Assign(devices) addresses.append(ipv4_interfaces.GetAddress(0)) for i, node in enumerate(nodes): destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)] #print i, destaddr onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) #internet.EnablePcapAll("wifi-olsr") flowmon_helper = ns.flow_monitor.FlowMonitorHelper() #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31))) monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() def print_stats(os, st): print >> os, " Tx Bytes: ", st.txBytes print >> os, " Rx Bytes: ", st.rxBytes print >> os, " Tx Packets: ", st.txPackets print >> os, " Rx Packets: ", st.rxPackets print >> os, " Lost Packets: ", st.lostPackets if st.rxPackets > 0: print >> os, " Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets) print >> os, " Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets - 1)) print >> os, " Mean{Hop Count}: ", float( st.timesForwarded) / st.rxPackets + 1 if 0: print >> os, "Delay Histogram" for i in range(st.delayHistogram.GetNBins()): print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \ st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i) print >> os, "Jitter Histogram" for i in range(st.jitterHistogram.GetNBins()): print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \ st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i) print >> os, "PacketSize Histogram" for i in range(st.packetSizeHistogram.GetNBins()): print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \ st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i) for reason, drops in enumerate(st.packetsDropped): print " Packets dropped by reason %i: %i" % (reason, drops) #for reason, drops in enumerate(st.bytesDropped): # print "Bytes dropped by reason %i: %i" % (reason, drops) monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() if cmd.Results is None: for flow_id, flow_stats in monitor.GetFlowStats(): t = classifier.FindFlow(flow_id) proto = {6: 'TCP', 17: 'UDP'}[t.protocol] print "FlowID: %i (%s %s/%s --> %s/%i)" % \ (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort) print_stats(sys.stdout, flow_stats) else: print monitor.SerializeToXmlFile(cmd.Results, True, True) if cmd.Plot is not None: import pylab delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) pylab.hist(delays, 20) pylab.xlabel("Delay (s)") pylab.ylabel("Number of Flows") pylab.show() return 0
nodes.Create(2) mac = ns3.NqosWifiMacHelper.Default() mac.SetType("ns3::AdhocWifiMac") wifiHelper.SetRemoteStationManager( "ns3::ConstantRateWifiManager", "DataMode", ns3.StringValue("DsssRate1Mbps"), "ControlMode", ns3.StringValue("DsssRate1Mbps")) devices = wifiHelper.Install(wifiPhy,mac,nodes) olsr = ns3.OlsrHelper() #Add the IPv4 protocol stack to the nodes in our container internet=ns3.InternetStackHelper() internet.SetRoutingHelper (olsr) internet.Install (nodes) ipAddrss= ns3.Ipv4AddressHelper() ipAddrss.SetBase( ns3.Ipv4Address("192.168.0.0"), ns3.Ipv4Mask("255.255.255.0")); ipContainer = ipAddrss.Assign(devices); mobility = ns3.MobilityHelper() positionAlloc = ns3.ListPositionAllocator() positionAlloc.Add(ns3.Vector (100,100,0.0)) positionAlloc.Add(ns3.Vector (100,200,0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
def main(argv): # # First, we initialize a few local variables that control some # simulation parameters. # cmd = ns.core.CommandLine() cmd.backboneNodes = 10 cmd.infraNodes = 2 cmd.lanNodes = 2 cmd.stopTime = 20 # # Simulation defaults are typically set next, before command line # arguments are parsed. # ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("1472")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("100kb/s")) # # For convenience, we add the local variables to the command line argument # system so that they can be overridden with flags such as # "--backboneNodes=20" # cmd.AddValue("backboneNodes", "number of backbone nodes") cmd.AddValue("infraNodes", "number of leaf nodes") cmd.AddValue("lanNodes", "number of LAN nodes") cmd.AddValue("stopTime", "simulation stop time(seconds)") # # The system global variables and the local values added to the argument # system can be overridden by command line arguments by using this call. # cmd.Parse(argv) backboneNodes = int(cmd.backboneNodes) infraNodes = int(cmd.infraNodes) lanNodes = int(cmd.lanNodes) stopTime = int(cmd.stopTime) if (stopTime < 10): print("Use a simulation stop time >= 10 seconds") exit(1) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the backbone # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # Create a container to manage the nodes of the adhoc(backbone) network. # Later we'll create the rest of the nodes we'll need. # backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) # # Create the backbone wifi net devices and install them into the nodes in # our container # wifi = ns.wifi.WifiHelper() mac = ns.wifi.WifiMacHelper() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) backboneDevices = wifi.Install(wifiPhy, mac, backbone) # # Add the IPv4 protocol stack to the nodes in our container # print("Enabling OLSR routing on all backbone nodes") internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr) # has effect on the next Install () internet.Install(backbone) # re-initialize for non-olsr routing. # internet.Reset() # # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. # ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) # # The ad-hoc network nodes need a mobility model so we aggregate one to # each of the nodes we just finished building. # mobility = ns.mobility.MobilityHelper() mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(20.0), "MinY", ns.core.DoubleValue(20.0), "DeltaX", ns.core.DoubleValue(20.0), "DeltaY", ns.core.DoubleValue(20.0), "GridWidth", ns.core.UintegerValue(5), "LayoutType", ns.core.StringValue("RowFirst")) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500, 500)), "Speed", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"), "Pause", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]")) mobility.Install(backbone) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the LANs # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the CSMA networks will be in # the "172.16 address space ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print("Configuring local area network for backbone node ", i) # # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes # newLanNodes = ns.network.NodeContainer() newLanNodes.Create(lanNodes - 1) # Now, create the container with all nodes on this link lan = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), newLanNodes) # # Create the CSMA net devices and install them into the nodes in our # collection. # csma = ns.csma.CsmaHelper() csma.SetChannelAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2))) lanDevices = csma.Install(lan) # # Add the IPv4 protocol stack to the new LAN nodes # internet.Install(newLanNodes) # # Assign IPv4 addresses to the device drivers(actually to the # associated IPv4 interfaces) we just created. # ipAddrs.Assign(lanDevices) # # Assign a new network prefix for the next LAN, according to the # network mask initialized above # ipAddrs.NewNetwork() # # The new LAN nodes need a mobility model so we aggregate one # to each of the nodes we just finished building. # mobilityLan = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() for j in range(newLanNodes.GetN()): positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0)) mobilityLan.SetPositionAllocator(positionAlloc) mobilityLan.PushReferenceMobilityModel(backbone.Get(i)) mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobilityLan.Install(newLanNodes) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the mobile networks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the 802.11 networks will be in # the "10.0" address space ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print("Configuring wireless network for backbone node ", i) # # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes # stas = ns.network.NodeContainer() stas.Create(infraNodes - 1) # Now, create the container with all nodes on this link infra = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), stas) # # Create another ad hoc network and devices # ssid = ns.wifi.Ssid('wifi-infra' + str(i)) wifiInfra = ns.wifi.WifiHelper() wifiPhy.SetChannel(wifiChannel.Create()) wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager') macInfra = ns.wifi.WifiMacHelper() macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) # setup stas staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) # setup ap. macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i)) # Collect all of these new devices infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices) # Add the IPv4 protocol stack to the nodes in our container # internet.Install(stas) # # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. # ipAddrs.Assign(infraDevices) # # Assign a new network prefix for each mobile network, according to # the network mask initialized above # ipAddrs.NewNetwork() # # The new wireless nodes need a mobility model so we aggregate one # to each of the nodes we just finished building. # subnetAlloc = ns.mobility.ListPositionAllocator() for j in range(infra.GetN()): subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0)) mobility.PushReferenceMobilityModel(backbone.Get(i)) mobility.SetPositionAllocator(subnetAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10, 10)), "Speed", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"), "Pause", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]")) mobility.Install(stas) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Application configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Create the OnOff application to send UDP datagrams of size # 210 bytes at a rate of 448 Kb/s, between two nodes print("Create Applications.") port = 9 # Discard port(RFC 863) appSource = ns.network.NodeList.GetNode(backboneNodes) lastNodeIndex = backboneNodes + backboneNodes * ( lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1 appSink = ns.network.NodeList.GetNode(lastNodeIndex) # Let's fetch the IP address of the last node, which is on Ipv4Interface 1 remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress( 1, 0).GetLocal() onoff = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port))) apps = onoff.Install(ns.network.NodeContainer(appSource)) apps.Start(ns.core.Seconds(3)) apps.Stop(ns.core.Seconds(stopTime - 1)) # Create a packet sink to receive these packets sink = ns.applications.PacketSinkHelper( "ns3::UdpSocketFactory", ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port)) apps = sink.Install(ns.network.NodeContainer(appSink)) apps.Start(ns.core.Seconds(3)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Tracing configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / print("Configure Tracing.") csma = ns.csma.CsmaHelper() # # Let's set up some ns-2-like ascii traces, using another helper class # ascii = ns.network.AsciiTraceHelper() stream = ascii.CreateFileStream("mixed-wireless.tr") wifiPhy.EnableAsciiAll(stream) csma.EnableAsciiAll(stream) internet.EnableAsciiIpv4All(stream) # Csma captures in non-promiscuous mode csma.EnablePcapAll("mixed-wireless", False) # Let's do a pcap trace on the backbone devices wifiPhy.EnablePcap("mixed-wireless", backboneDevices) wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0) # #ifdef ENABLE_FOR_TRACING_EXAMPLE # Config.Connect("/NodeList/*/$MobilityModel/CourseChange", # MakeCallback(&CourseChangeCallback)) # #endif # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Run simulation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # print("Run Simulation.") ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy()
def main(argv): cmd = ns.core.CommandLine() cmd.NumNodesSide = None cmd.AddValue( "NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)" ) cmd.Results = None cmd.AddValue("Results", "Write XML results to file") cmd.Plot = None cmd.AddValue("Plot", "Plot the results using the matplotlib python module") cmd.Parse(argv) wifi = ns.wifi.WifiHelper.Default() wifiMac = ns.wifi.NqosWifiMacHelper.Default() wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) ssid = ns.wifi.Ssid("wifi-default") wifi.SetRemoteStationManager("ns3::ArfWifiManager") wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) internet = ns.internet.InternetStackHelper() list_routing = ns.internet.Ipv4ListRoutingHelper() olsr_routing = ns.olsr.OlsrHelper() static_routing = ns.internet.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns.internet.Ipv4AddressHelper() ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) port = 9 onOffHelper = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address( ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps"))) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) addresses = [] nodes = [] num_nodes_side = NUM_NODES_SIDE for xi in range(num_nodes_side): for yi in range(num_nodes_side): node = ns.network.Node() nodes.append(node) internet.Install(ns.network.NodeContainer(node)) mobility = ns.mobility.ConstantPositionMobilityModel() mobility.SetPosition( ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0)) node.AggregateObject(mobility) devices = wifi.Install(wifiPhy, wifiMac, node) ipv4_interfaces = ipv4Addresses.Assign(devices) addresses.append(ipv4_interfaces.GetAddress(0)) for e in range(500): for i, node in enumerate(nodes): destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)] onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() monitor.SerializeToXmlFile("wififlow.xml", True, True) flow_stats_inputs = monitor.GetFlowStats() flow_array = [ ] # this is original array which store the original inputs to the model # this are the inputs to the model which will stored in flow_array flow_array.append(flow_stat_inputs.txBytes) flow_array.append(flow_stat_inputs.rxBytes) flow_array.append(flow_stat_inputs.txPackets) flow_array.append(flow_stat_inputs.rxPackets) flow_array.append(flow_stat_inputs.lostPackets) if st.rxPackets > 0: mean_delay = (flow_stat_inputs.delaySum.GetSeconds() / flow_stat_inputs.rxPackets) flow_array.append(mean_delay) mean_jitter = (flow_stat_inputs.jitterSum.GetSeconds() / (flow_stat_inputs.rxPackets - 1)) flow_array.append(mean_jitter) np.array( flow_array ) # then convert the flow array to numpy array reason to convert is numpy array will be a matrix and our model will only accept matrix inputs # data preprocessing part here we normalized the dataset into range between 1 and 0 and then convert to time sequence dataset since our model is recurrent network it only accept time sequence data df = DataFrame(data=d, index=index) min_max_scaler = preprocessing.MinMaxScaler() np_scaled = min_max_scaler.fit_transform(df) df_normalized = pd.DataFrame(np_scaled) X_train = sequence.pad_sequences(df_normalized, 10) actor = DQNAgent(X_train.shape[1], num_nodes_side) for t in range(500): action = actor.act(X_train) for i, node in enumerate(nodes): destaddr = addresses[action] onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() monitor.SerializeToXmlFile("wififlow.xml", True, True) # similar process describe in ahead happens here inside the loop flow_stats_inputs_next = monitor.GetFlowStats() flow_array_next = [] flow_array_next.append(flow_stat_inputs_next.txBytes) flow_array_next.append(flow_stat_inputs_next.rxBytes) flow_array_next.append(flow_stat_inputs_next.txPackets) flow_array_next.append(flow_stat_inputs_next.rxPackets) flow_array_next.append(flow_stat_inputs_next.lostPackets) if st.rxPackets > 0: mean_delay = (flow_stat_inputs_next.delaySum.GetSeconds() / flow_stat_inputs.rxPackets) flow_array.append(mean_delay) mean_jitter = (flow_stat_inputs_next.jitterSum.GetSeconds() / (flow_stat_inputs.rxPackets - 1)) flow_array_next.append(mean_jitter) np.array(flow_array_next) df_next = DataFrame(data=d, index=index) min_max_scaler_next = preprocessing.MinMaxScaler() np_scaled_next = min_max_scaler_next.fit_transform(df_next) df_normalized_next = pd.DataFrame(np_scaled_next) X_next = sequence.pad_sequences(df_normalized_next, 10) # here we calculate the reward this has to be improve here i calculate the reward based only on loss packets which is not good way another few factors to be added it has to be discussed if (flow_stat_inputs_next.lostPackets > 10): reward = -10 else: reward = 20 actor.remember( X_train, action, X_next ) # finally saved the current step in model memory for experience replay module print("episode: {}/{}, score: {}".format(e, 500, t)) actor.replay( 32 ) # after 500 times of training then apply the experiece replay task to use what it learn so far import pylab delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) pylab.hist(delays, 20) pylab.xlabel("Delay (s)") pylab.ylabel("Number of Flows") pylab.show() return 0
def main(argv): # # First, we declare and initialize a few local variables that control some # simulation parameters. # backboneNodes = 10 infraNodes = 5 lanNodes = 5 stopTime = 10 # # Simulation defaults are typically set next, before command line # arguments are parsed. # ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("210")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("448kb/s")) # # For convenience, we add the local variables to the command line argument # system so that they can be overridden with flags such as # "--backboneNodes=20" # cmd = ns.core.CommandLine() #cmd.AddValue("backboneNodes", "number of backbone nodes", backboneNodes) #cmd.AddValue("infraNodes", "number of leaf nodes", infraNodes) #cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes) #cmd.AddValue("stopTime", "simulation stop time(seconds)", stopTime) # # The system global variables and the local values added to the argument # system can be overridden by command line arguments by using this call. # cmd.Parse(argv) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the backbone # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # Create a container to manage the nodes of the adhoc(backbone) network. # Later we'll create the rest of the nodes we'll need. # backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) # # Create the backbone wifi net devices and install them into the nodes in # our container # wifi = ns.wifi.WifiHelper() mac = ns.wifi.NqosWifiMacHelper.Default() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) backboneDevices = wifi.Install(wifiPhy, mac, backbone) # # Add the IPv4 protocol stack to the nodes in our container # print "Enabling OLSR routing on all backbone nodes" internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr) # has effect on the next Install () internet.Install(backbone) # re-initialize for non-olsr routing. internet.Reset() # # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. # ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) # # The ad-hoc network nodes need a mobility model so we aggregate one to # each of the nodes we just finished building. # mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() x = 0.0 for i in range(backboneNodes): positionAlloc.Add(ns.core.Vector(x, 0.0, 0.0)) x += 5.0 mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(0, 1000, 0, 1000)), "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(2000)), "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.2))) mobility.Install(backbone) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the LANs # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the CSMA networks will be in # the "172.16 address space ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print "Configuring local area network for backbone node ", i # # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes # newLanNodes = ns.network.NodeContainer() newLanNodes.Create(lanNodes - 1) # Now, create the container with all nodes on this link lan = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), newLanNodes) # # Create the CSMA net devices and install them into the nodes in our # collection. # csma = ns.csma.CsmaHelper() csma.SetChannelAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2))) lanDevices = csma.Install(lan) # # Add the IPv4 protocol stack to the new LAN nodes # internet.Install(newLanNodes) # # Assign IPv4 addresses to the device drivers(actually to the # associated IPv4 interfaces) we just created. # ipAddrs.Assign(lanDevices) # # Assign a new network prefix for the next LAN, according to the # network mask initialized above # ipAddrs.NewNetwork() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the mobile networks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the 802.11 networks will be in # the "10.0" address space ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print "Configuring wireless network for backbone node ", i # # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes # stas = ns.network.NodeContainer() stas.Create(infraNodes - 1) # Now, create the container with all nodes on this link infra = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), stas) # # Create another ad hoc network and devices # ssid = ns.wifi.Ssid('wifi-infra' + str(i)) wifiInfra = ns.wifi.WifiHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager') macInfra = ns.wifi.NqosWifiMacHelper.Default() macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "ActiveProbing", ns.core.BooleanValue(False)) # setup stas staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) # setup ap. macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "BeaconGeneration", ns.core.BooleanValue(True), "BeaconInterval", ns.core.TimeValue(ns.core.Seconds(2.5))) apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i)) # Collect all of these new devices infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices) # Add the IPv4 protocol stack to the nodes in our container # internet.Install(stas) # # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. # ipAddrs.Assign(infraDevices) # # Assign a new network prefix for each mobile network, according to # the network mask initialized above # ipAddrs.NewNetwork() # # The new wireless nodes need a mobility model so we aggregate one # to each of the nodes we just finished building. # subnetAlloc = ns.mobility.ListPositionAllocator() for j in range(infra.GetN()): subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0)) mobility.PushReferenceMobilityModel(backbone.Get(i)) mobility.SetPositionAllocator(subnetAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-25, 25, -25, 25)), "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(30)), "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.4))) mobility.Install(infra) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Application configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Create the OnOff application to send UDP datagrams of size # 210 bytes at a rate of 448 Kb/s, between two nodes print "Create Applications." port = 9 # Discard port(RFC 863) # Let's make sure that the user does not define too few LAN nodes # to make this example work. We need lanNodes >= 5 assert (lanNodes >= 5) appSource = ns.network.NodeList.GetNode(11) appSink = ns.network.NodeList.GetNode(13) remoteAddr = ns.network.Ipv4Address("172.16.0.5") onoff = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port))) onoff.SetAttribute( "OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1))) onoff.SetAttribute( "OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0))) apps = onoff.Install(ns.network.NodeContainer(appSource)) apps.Start(ns.core.Seconds(3.0)) apps.Stop(ns.core.Seconds(20.0)) # Create a packet sink to receive these packets sink = ns.applications.PacketSinkHelper( "ns3::UdpSocketFactory", ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port)) apps = sink.Install(ns.network.NodeContainer(appSink)) apps.Start(ns.core.Seconds(3.0)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Tracing configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / print "Configure Tracing." # # Let's set up some ns-2-like ascii traces, using another helper class # #std.ofstream ascii #ascii = ns.core.AsciiTraceHelper(); #stream = ascii.CreateFileStream("mixed-wireless.tr"); #wifiPhy.EnableAsciiAll(stream); #csma.EnableAsciiAll(stream); print "(tracing not done for Python)" # Look at nodes 11, 13 only # WifiHelper.EnableAscii(ascii, 11, 0); # WifiHelper.EnableAscii(ascii, 13, 0); # Let's do a pcap trace on the backbone devices wifiPhy.EnablePcap("mixed-wireless", backboneDevices) # Let's additionally trace the application Sink, ifIndex 0 csma = ns.csma.CsmaHelper() csma.EnablePcapAll("mixed-wireless", False) # #ifdef ENABLE_FOR_TRACING_EXAMPLE # Config.Connect("/NodeList/*/$MobilityModel/CourseChange", # MakeCallback(&CourseChangeCallback)) # #endif # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Run simulation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # print "Run Simulation." ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy()
def Run(self, *positional_parameters, **keyword_parameters): ns.network.Packet.EnablePrinting() if "SINKS" in os.environ: self.m_nSinks = int(os.environ["SINKS"]) if "TXP" in os.environ: self.m_txp = float(os.environ["TXP"]) if "TOTAL_TIME" in os.environ: self.m_total_time = int(os.environ["TOTAL_TIME"]) if "NODES" in os.environ: self.m_nodes = int(os.environ["NODES"]) if "PROTOCOL" in os.environ: self.m_protocol = int(os.environ["PROTOCOL"]) if "NODE_SPEED" in os.environ: self.m_node_speed = int(os.environ["NODE_SPEED"]) if "NODE_PAUSE" in os.environ: self.m_node_pause = int(os.environ["NODE_PAUSE"]) if "FILE_NAME" in os.environ: self.m_CSVfileName = os.environ["FILE_NAME"] if 'nSinks' in keyword_parameters: self.m_nSinks = keyword_parameters['nSinks'] if 'txp' in keyword_parameters: self.m_txp = keyword_parameters['txp'] if 'TotalTime' in keyword_parameters: self.m_total_time = keyword_parameters['TotalTime'] if 'Nodes' in keyword_parameters: self.m_nodes = keyword_parameters['Nodes'] if 'Protocol' in keyword_parameters: self.m_protocol = keyword_parameters['Protocol'] if 'NodeSpeed' in keyword_parameters: self.m_node_speed = keyword_parameters['NodeSpeed'] if 'NodePause' in keyword_parameters: self.m_node_pause = keyword_parameters['NodePause'] if 'CSVfileName' in keyword_parameters: self.m_CSVfileName = keyword_parameters['CSVfileName'] self.m_CSVfileName += "." + str(time.time()) rate = "2048bps" phyMode = "DsssRate11Mbps" tr_name = self.m_CSVfileName + "-compare" self.m_protocolName = "protocol" ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("64")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue(rate)) ns.core.Config.SetDefault( "ns3::WifiRemoteStationManager::NonUnicastMode", ns.core.StringValue(phyMode)) adhocNodes = ns.network.NodeContainer() adhocNodes.Create(self.m_nodes) wifi = ns.wifi.WifiHelper() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211b) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper() wifiChannel.SetPropagationDelay( "ns3::ConstantSpeedPropagationDelayModel") wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel") wifiPhy.SetChannel(wifiChannel.Create()) wifiMac = ns.wifi.WifiMacHelper() wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue(phyMode), "ControlMode", ns.core.StringValue(phyMode)) wifiPhy.Set("TxPowerStart", ns.core.DoubleValue(self.m_txp)) wifiPhy.Set("TxPowerEnd", ns.core.DoubleValue(self.m_txp)) wifiMac.SetType("ns3::AdhocWifiMac") adhocDevices = wifi.Install(wifiPhy, wifiMac, adhocNodes) # type: NetDeviceContainer mobilityAdhoc = ns.mobility.MobilityHelper() streamIndex = 0 # used to get consistent mobility across scenarios pos = ns.core.ObjectFactory() pos.SetTypeId("ns3::RandomRectanglePositionAllocator") pos.Set( "X", ns.core.StringValue( "ns3::UniformRandomVariable[Min=0.0|Max=300.0]")) pos.Set( "Y", ns.core.StringValue( "ns3::UniformRandomVariable[Min=0.0|Max=1500.0]")) # Same as: Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> (); taPositionAlloc = pos.Create().GetObject( ns.mobility.PositionAllocator.GetTypeId( )) # type: Ptr<PositionAllocator> streamIndex += taPositionAlloc.AssignStreams(streamIndex) ssSpeed = "ns3::UniformRandomVariable[Min=0.0|Max=%s]" % self.m_node_speed ssPause = "ns3::ConstantRandomVariable[Constant=%s]" % self.m_node_pause mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel", "Speed", ns.core.StringValue(ssSpeed), "Pause", ns.core.StringValue(ssPause), "PositionAllocator", ns.core.PointerValue(taPositionAlloc)) mobilityAdhoc.SetPositionAllocator(taPositionAlloc) mobilityAdhoc.Install(adhocNodes) streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex) # NS_UNUSED(streamIndex) # From this point, streamIndex is unused aodv = ns.aodv.AodvHelper() olsr = ns.olsr.OlsrHelper() dsdv = ns.dsdv.DsdvHelper() dsr = ns.dsr.DsrHelper() dsrMain = ns.dsr.DsrMainHelper() list = ns.internet.Ipv4ListRoutingHelper() internet = ns.internet.InternetStackHelper() if self.m_protocol == 1: list.Add(olsr, 100) self.m_protocolName = "OLSR" elif self.m_protocol == 2: list.Add(aodv, 100) self.m_protocolName = "AODV" elif self.m_protocol == 3: list.Add(dsdv, 100) self.m_protocolName = "DSDV" elif self.m_protocol == 4: self.m_protocolName = "DSR" else: print("No such protocol:%s" % str(self.m_protocol) ) # NS_FATAL_ERROR ("No such protocol:" << m_protocol); if self.m_protocol < 4: internet.SetRoutingHelper(list) internet.Install(adhocNodes) elif self.m_protocol == 4: internet.Install(adhocNodes) dsrMain.Install(dsr, adhocNodes) print("assigning ip address") addressAdhoc = ns.internet.Ipv4AddressHelper() addressAdhoc.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0")) adhocInterfaces = addressAdhoc.Assign(adhocDevices) onoff1 = ns.applications.OnOffHelper("ns3::UdpSocketFactory", ns.network.Address()) onoff1.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]")) onoff1.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.0]")) for i in range(0, self.m_nSinks): # Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i)); sink = self.SetupPacketReceive(adhocInterfaces.GetAddress(i), adhocNodes.Get(i)) remoteAddress = ns.network.AddressValue( ns.network.InetSocketAddress(adhocInterfaces.GetAddress(i), self.port)) onoff1.SetAttribute("Remote", remoteAddress) # Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> (); posURV = ns.core.ObjectFactory() posURV.SetTypeId("ns3::UniformRandomVariable") var = posURV.Create().GetObject( ns.core.UniformRandomVariable.GetTypeId()) temp = onoff1.Install( adhocNodes.Get(i + self.m_nSinks)) # type: ApplicationContainer temp.Start(ns.core.Seconds(var.GetValue(100.0, 101.0))) temp.Stop(ns.core.Seconds(self.m_total_time)) ss = self.m_nSinks nodes = str(ss) ss2 = self.m_node_speed sNodeSpeed = str(ss2) ss3 = self.m_node_pause sNodePause = str(ss3) ss4 = rate sRate = str(ss4) tr_name = tr_name + "_" + \ self.m_protocolName + "_" + \ nodes + "sinks_" + \ sNodeSpeed + "speed_" + \ sNodePause + "pause_" + \ sRate + "rate" self.m_CSVfileName = tr_name ascii = ns.network.AsciiTraceHelper() ns.mobility.MobilityHelper.EnableAsciiAll( ascii.CreateFileStream( os.path.join(__workdir__, "%s.mob" % tr_name))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) print("Run Simulation.") self.WriteHeaderCsv() self.CheckThroughput() ns.core.Simulator.Stop(ns.core.Seconds(self.m_total_time)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() if self.m_debugger: for flow_id, flow_stats in monitor.GetFlowStats(): with open( os.path.join(__workdir__, (self.m_CSVfileName + ".txt")), 'a') as file: t = classifier.FindFlow(flow_id) proto = {6: 'TCP', 17: 'UDP'}[t.protocol] file.write("FlowID: %i (%s %s/%s --> %s/%i)\n" % \ (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort)) self.print_stats(file, flow_stats) file.close() monitor.SerializeToXmlFile( os.path.join(__workdir__, "%s.flowmon" % tr_name), True, True) delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue if flow_stats.rxPackets == 0: delays.append(0) else: delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) plt.hist(delays, 20) plt.xlabel("Delay (s)") plt.ylabel("Number of Flows") plt.savefig(os.path.join(__workdir__, '%s.png' % tr_name), dpi=75) plt.show() ns.core.Simulator.Destroy()
def main(): framework.start() # First, we initialize a few local variables that control some # simulation parameters. cmd = ns.core.CommandLine() cmd.backboneNodes = {{backbone_nodes}} cmd.infraNodes = {{infra_nodes}} cmd.lanNodes = {{lan_nodes}} cmd.stopTime = {{exec_time}} # Simulation defaults are typically set next, before command line # arguments are parsed. ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("1472")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("100kb/s")) backboneNodes = int(cmd.backboneNodes) infraNodes = int(cmd.infraNodes) lanNodes = int(cmd.lanNodes) stopTime = int(cmd.stopTime) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the backbone # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Create a container to manage the nodes of the adhoc(backbone) network. # Later we'll create the rest of the nodes we'll need. backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) # Create the backbone wifi net devices and install them into the nodes in # our container wifi = ns.wifi.WifiHelper() mac = ns.wifi.WifiMacHelper() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager( "ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate{}Mbps".format({{ofdm_rate}}))) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) backboneDevices = wifi.Install(wifiPhy, mac, backbone) # Add the IPv4 protocol stack to the nodes in our container print("Enabling OLSR routing on all backbone nodes") internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr) # has effect on the next Install () internet.Install(backbone) # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) # The ad-hoc network nodes need a mobility model so we aggregate one to # each of the nodes we just finished building. mobility = ns.mobility.MobilityHelper() mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(20.0), "MinY", ns.core.DoubleValue(20.0), "DeltaX", ns.core.DoubleValue(20.0), "DeltaY", ns.core.DoubleValue(20.0), "GridWidth", ns.core.UintegerValue(5), "LayoutType", ns.core.StringValue("RowFirst")) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500, 500)), "Speed", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"), "Pause", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]")) mobility.Install(backbone) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the LANs # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the CSMA networks will be in # the "172.16 address space ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes newLanNodes = ns.network.NodeContainer() newLanNodes.Create(lanNodes - 1) lan = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), newLanNodes) # Create the CSMA net devices and install them into the nodes in our # collection. csma = ns.csma.CsmaHelper() csma.SetChannelAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate({{datarate}}))) csma.SetChannelAttribute( "Delay", ns.core.TimeValue(ns.core.MilliSeconds({{delay}}))) lanDevices = csma.Install(lan) # Add the IPv4 protocol stack to the new LAN nodes internet.Install(newLanNodes) # Assign IPv4 addresses to the device drivers(actually to the # associated IPv4 interfaces) we just created. ipAddrs.Assign(lanDevices) # Assign a new network prefix for the next LAN, according to the # network mask initialized above ipAddrs.NewNetwork() # The new LAN nodes need a mobility model so we aggregate one # to each of the nodes we just finished building. mobilityLan = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() for j in range(newLanNodes.GetN()): positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0)) mobilityLan.SetPositionAllocator(positionAlloc) mobilityLan.PushReferenceMobilityModel(backbone.Get(i)) mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobilityLan.Install(newLanNodes) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Construct the mobile networks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Reset the address base-- all of the 802.11 networks will be in # the "10.0" address space ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): # Create a container to manage the nodes of the LAN. We need # two containers here; one with all of the new nodes, and one # with all of the nodes including new and existing nodes stas = ns.network.NodeContainer() stas.Create(infraNodes - 1) infra = ns.network.NodeContainer( ns.network.NodeContainer(backbone.Get(i)), stas) # Create another ad hoc network and devices ssid = ns.wifi.Ssid('wifi-infra' + str(i)) wifiInfra = ns.wifi.WifiHelper() wifiPhy.SetChannel(wifiChannel.Create()) wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager') macInfra = ns.wifi.WifiMacHelper() macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) # setup stas staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) # setup ap. macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "BeaconInterval", ns.core.TimeValue(ns.core.Seconds(2.5))) apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i)) # Collect all of these new devices infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices) # Add the IPv4 protocol stack to the nodes in our container internet.Install(stas) # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created. ipAddrs.Assign(infraDevices) # Assign a new network prefix for each mobile network, according to # the network mask initialized above ipAddrs.NewNetwork() # The new wireless nodes need a mobility model so we aggregate one # to each of the nodes we just finished building. subnetAlloc = ns.mobility.ListPositionAllocator() for j in range(infra.GetN()): subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0)) mobility.PushReferenceMobilityModel(backbone.Get(i)) mobility.SetPositionAllocator(subnetAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10, 10)), "Speed", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"), "Pause", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]")) mobility.Install(stas) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Application configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # Create the OnOff application to send UDP datagrams of size # 210 bytes at a rate of 448 Kb/s, between two nodes port = 9 # Discard port(RFC 863) appSource = ns.network.NodeList.GetNode(backboneNodes) lastNodeIndex = backboneNodes + backboneNodes * ( lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1 appSink = ns.network.NodeList.GetNode(lastNodeIndex) # Let's fetch the IP address of the last node, which is on Ipv4Interface 1 remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress( 1, 0).GetLocal() onoff = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port))) apps = onoff.Install(ns.network.NodeContainer(appSource)) apps.Start(ns.core.Seconds(3)) apps.Stop(ns.core.Seconds(stopTime - 1)) # Create a packet sink to receive these packets sink = ns.applications.PacketSinkHelper( "ns3::UdpSocketFactory", ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port)) apps = sink.Install(ns.network.NodeContainer(appSink)) apps.Start(ns.core.Seconds(3)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # Tracing configuration # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / csma = ns.csma.CsmaHelper() # Let's set up some ns-2-like ascii traces, using another helper class # ascii = ns.network.AsciiTraceHelper() stream = ascii.CreateFileStream("mixed-wireless.tr") wifiPhy.EnableAsciiAll(stream) csma.EnableAsciiAll(stream) internet.EnableAsciiIpv4All(stream) mob = ascii.CreateFileStream("mixed-wireless.mob") mobility.EnableAsciiAll(mob) # Csma captures in non-promiscuous mode csma.EnablePcapAll("mixed-wireless", False) # Let's do a pcap trace on the backbone devices wifiPhy.EnablePcap("mixed-wireless", backboneDevices) wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Run simulation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy() framework.addBinaryFile("mixed-wireless.tr") framework.addBinaryFile("mixed-wireless.mob") path = "*.pcap" for filename in glob.glob(path): framework.addBinaryFile(filename) framework.stop()
def main(argv): backboneNodes = 10 infraNodes = 5 lanNodes = 5 stopTime = 10 ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("210")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("448kb/s")) cmd = ns.core.CommandLine() cmd.Parse(argv) backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) wifi = ns.wifi.WifiHelper() mac = ns.wifi.NqosWifiMacHelper.Default() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) backboneDevices = wifi.Install(wifiPhy, mac, backbone) print "Enabling OLSR routing on all backbone nodes" internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr); internet.Install(backbone); internet.Reset() ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() x = 0.0 for i in range(backboneNodes): positionAlloc.Add(ns.core.Vector(x, 0.0, 0.0)) x += 5.0 mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(0, 1000, 0, 1000)), "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(2000)), "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.2))) mobility.Install(backbone) ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print "Configuring local area network for backbone node ", i newLanNodes = ns.network.NodeContainer() newLanNodes.Create(lanNodes - 1) lan = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), newLanNodes) csma = ns.csma.CsmaHelper() csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2))) lanDevices = csma.Install(lan) internet.Install(newLanNodes) ipAddrs.Assign(lanDevices) ipAddrs.NewNetwork() ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) for i in range(backboneNodes): print "Configuring wireless network for backbone node ", i stas = ns.network.NodeContainer() stas.Create(infraNodes - 1) infra = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), stas) ssid = ns.wifi.Ssid('wifi-infra' + str(i)) wifiInfra = ns.wifi.WifiHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager') macInfra = ns.wifi.NqosWifiMacHelper.Default(); macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "ActiveProbing", ns.core.BooleanValue(False)) staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "BeaconGeneration", ns.core.BooleanValue(True), "BeaconInterval", ns.core.TimeValue(ns.core.Seconds(2.5))) apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i)) infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices) internet.Install(stas) ipAddrs.Assign(infraDevices) ipAddrs.NewNetwork() subnetAlloc = ns.mobility.ListPositionAllocator() for j in range(infra.GetN()): subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0)) mobility.PushReferenceMobilityModel(backbone.Get(i)) mobility.SetPositionAllocator(subnetAlloc) mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-25, 25, -25, 25)), "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(30)), "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.4))) mobility.Install(infra) print "Create Applications." port = 9 assert(lanNodes >= 5) appSource = ns.network.NodeList.GetNode(11) appSink = ns.network.NodeList.GetNode(13) remoteAddr = ns.network.Ipv4Address("172.16.0.5") onoff = ns.applications.OnOffHelper("ns3::UdpSocketFactory", ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port))) onoff.SetAttribute("OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1))) onoff.SetAttribute("OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0))) apps = onoff.Install(ns.network.NodeContainer(appSource)) apps.Start(ns.core.Seconds(3.0)) apps.Stop(ns.core.Seconds(20.0)) sink = ns.applications.PacketSinkHelper("ns3::UdpSocketFactory", ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port)) apps = sink.Install(ns.network.NodeContainer(appSink)) apps.Start(ns.core.Seconds(3.0)) print "Configure Tracing." print "(tracing not done for Python)" wifiPhy.EnablePcap("mixed-wireless", backboneDevices) csma = ns.csma.CsmaHelper() csma.EnablePcapAll("mixed-wireless", False) print "Run Simulation." ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy()
ripRouting.ExcludeInterface(a, 1) ripRouting.ExcludeInterface(d, 3) ripRouting.SetInterfaceMetric(c, 3, 10) ripRouting.SetInterfaceMetric(d, 1, 10) listRH = ns.internet.Ipv4ListRoutingHelper() listRH.Add(ripRouting, 0) ''' // Ipv4StaticRoutingHelper staticRh; // listRH.Add (staticRh, 5); ''' internet = ns.internet.InternetStackHelper() internet.SetIpv6StackInstall(False) internet.SetRoutingHelper(listRH) internet.Install(routers) internetNodes = ns.internet.InternetStackHelper() internetNodes.SetIpv6StackInstall(False) internetNodes.Install(nodes) #Assign addresses. #The source and destination networks have global addresses #The "core" network just needs link-local addresses for routing. #We assign global addresses to the routers as well to receive #ICMPv6 errors. print "Assign IPv4 Addresses." ipv4 = ns.internet.Ipv4AddressHelper()
def main(argv): # # Primero, inicializamos algunas variables locales que controlan algunos # parametros de la simulacion. # cmd = ns.core.CommandLine() cmd.backboneNodes = 25 cmd.stopTime = 20 ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("1472")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("100kb/s")) cmd.AddValue("backboneNodes", "number of backbone nodes") cmd.AddValue("stopTime", "simulation stop time(seconds)") cmd.Parse(argv) backboneNodes = int(cmd.backboneNodes) stopTime = int(cmd.stopTime) if (stopTime < 10): print("Use a simulation stop time >= 10 seconds") exit(1) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # # EL backbone # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # / # # Creamos un contenedor para administrar los nodos de la red adhoc (backbone). # backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) # # Creamos los dispositivos de red wifi y los instalamos # en nuestro contenedor # wifi = ns.wifi.WifiHelper() mac = ns.wifi.WifiMacHelper() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) backboneDevices = wifi.Install(wifiPhy, mac, backbone) # # Agregamos la pila de protocolos IPv4 a los nodos en nuestro contenedor # internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr) internet.Install(backbone) # internet.Reset() # # Asignamos direcciones IPv4 a los controladores de dispositivo (en realidad a las interfaces # IPv4 asociadas) que acabamos de crear. # ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) # # Los nodos de red ad-hoc necesitan un modelo de movilidad, por lo que agregamos uno para # cada uno de los nodos que acabamos de terminar de construir. # mobility = ns.mobility.MobilityHelper() mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(20.0), "MinY", ns.core.DoubleValue(20.0), "DeltaX", ns.core.DoubleValue(20.0), "DeltaY", ns.core.DoubleValue(20.0), "GridWidth", ns.core.UintegerValue(5), "LayoutType", ns.core.StringValue("RowFirst")) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500, 500)), "Speed", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"), "Pause", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]")) mobility.Install(backbone) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Corremos la simulacion # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # print("Corremos la simulacion.") ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy()