From 8b8e2d9ec0162345a1de588c44e878504cc9b0f6 Mon Sep 17 00:00:00 2001 From: Tom Henderson Date: Tue, 30 Dec 2008 12:14:54 -0800 Subject: [PATCH 01/29] mixed-wireless was not instantiating a stationManager in helper --- examples/mixed-wireless.cc | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/mixed-wireless.cc b/examples/mixed-wireless.cc index 944dd63c5..0f9bdf953 100644 --- a/examples/mixed-wireless.cc +++ b/examples/mixed-wireless.cc @@ -132,11 +132,13 @@ main (int argc, char *argv[]) // Create the backbone wifi net devices and install them into the nodes in // our container // + WifiHelper wifi; + wifi.SetMac ("ns3::AdhocWifiMac"); + wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", + "DataMode", StringValue ("wifia-54mbs")); YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default (); YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default (); wifiPhy.SetChannel (wifiChannel.Create ()); - WifiHelper wifi; - wifi.SetMac ("ns3::AdhocWifiMac"); NetDeviceContainer backboneDevices = wifi.Install (wifiPhy, backbone); // // Add the IPv4 protocol stack to the nodes in our container @@ -244,8 +246,7 @@ main (int argc, char *argv[]) // // Create another ad hoc network and devices // - WifiHelper wifiInfra; - wifiInfra.SetMac ("ns3::AdhocWifiMac"); + WifiHelper wifiInfra = WifiHelper::Default (); wifiPhy.SetChannel (wifiChannel.Create ()); NetDeviceContainer infraDevices = wifiInfra.Install (wifiPhy, infra); From 5b1f7da9ebb4158c0e34be4aaba362a3109fa54d Mon Sep 17 00:00:00 2001 From: Tom Henderson Date: Tue, 30 Dec 2008 13:18:56 -0800 Subject: [PATCH 02/29] fix course change notification portion of the script --- examples/mixed-wireless.cc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/mixed-wireless.cc b/examples/mixed-wireless.cc index 0f9bdf953..fdd373b59 100644 --- a/examples/mixed-wireless.cc +++ b/examples/mixed-wireless.cc @@ -69,16 +69,15 @@ using namespace ns3; NS_LOG_COMPONENT_DEFINE ("MixedWireless"); // -// This function will be used below as a trace sink +// This function will be used below as a trace sink, if the command-line +// argument or default value "useCourseChangeCallback" is set to true // -#ifdef ENABLE_FOR_TRACING_EXAMPLE static void CourseChangeCallback (std::string path, Ptr model) { Vector position = model->GetPosition (); std::cout << "CourseChange " << path << " x=" << position.x << ", y=" << position.y << ", z=" << position.z << std::endl; } -#endif int main (int argc, char *argv[]) @@ -91,6 +90,7 @@ main (int argc, char *argv[]) uint32_t infraNodes = 5; uint32_t lanNodes = 5; uint32_t stopTime = 10; + bool useCourseChangeCallback = false; // // Simulation defaults are typically set next, before command line @@ -109,6 +109,7 @@ main (int argc, char *argv[]) cmd.AddValue ("infraNodes", "number of leaf nodes", infraNodes); cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes); cmd.AddValue("stopTime", "simulation stop time (seconds)", stopTime); + cmd.AddValue("useCourseChangeCallback", "whether to enable course change tracing", useCourseChangeCallback); // // The system global variables and the local values added to the argument @@ -346,11 +347,10 @@ main (int argc, char *argv[]) // Let's additionally trace the application Sink, ifIndex 0 CsmaHelper::EnablePcap ("mixed-wireless", appSink->GetId (), 0); -#ifdef ENABLE_FOR_TRACING_EXAMPLE - Config::Connect ("/NodeList/*/$MobilityModel/CourseChange", - MakeCallback (&CourseChangeCallback)); -#endif - + if (useCourseChangeCallback == true) + { + Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange", MakeCallback (&CourseChangeCallback)); + } /////////////////////////////////////////////////////////////////////////// // // From 9f05afa09dc721b5348539d91ff4eaecbbf02577 Mon Sep 17 00:00:00 2001 From: Tom Henderson Date: Tue, 30 Dec 2008 21:51:36 -0800 Subject: [PATCH 03/29] Additional cleanup of mixed-wireless; get packets to flow across different device technologies --- examples/mixed-wireless.cc | 111 ++++++++++++++++++++++++++----------- 1 file changed, 79 insertions(+), 32 deletions(-) diff --git a/examples/mixed-wireless.cc b/examples/mixed-wireless.cc index fdd373b59..dd80f9021 100644 --- a/examples/mixed-wireless.cc +++ b/examples/mixed-wireless.cc @@ -47,12 +47,19 @@ // | | // +----------------+ +----------------+ // | 802.11 | | 802.11 | -// | net | | net | +// | infra net | | infra net | // | K-1 hosts | | K-1 hosts | // +----------------+ +----------------+ // +// We'll send data from the first wired LAN node on the first wired LAN +// to the last wireless STA on the last infrastructure net, thereby +// causing packets to traverse CSMA to adhoc to infrastructure links +// +// Note that certain mobility patterns may cause packet forwarding +// to fail (if nodes become disconnected) #include +#include #include "ns3/core-module.h" #include "ns3/common-module.h" #include "ns3/node-module.h" @@ -60,6 +67,7 @@ #include "ns3/mobility-module.h" #include "ns3/contrib-module.h" #include "ns3/wifi-module.h" +#include "ns3/global-route-manager.h" using namespace ns3; @@ -91,13 +99,14 @@ main (int argc, char *argv[]) uint32_t lanNodes = 5; uint32_t stopTime = 10; bool useCourseChangeCallback = false; + bool enableTracing = false; // // Simulation defaults are typically set next, before command line // arguments are parsed. // Config::SetDefault ("ns3::OnOffApplication::PacketSize", StringValue ("210")); - Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("448kb/s")); + Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("10kb/s")); // // For convenience, we add the local variables to the command line argument @@ -110,6 +119,7 @@ main (int argc, char *argv[]) cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes); cmd.AddValue("stopTime", "simulation stop time (seconds)", stopTime); cmd.AddValue("useCourseChangeCallback", "whether to enable course change tracing", useCourseChangeCallback); + cmd.AddValue("enableTracing", "enable tracing", enableTracing); // // The system global variables and the local values added to the argument @@ -169,8 +179,8 @@ main (int argc, char *argv[]) } mobility.SetPositionAllocator (positionAlloc); mobility.SetMobilityModel ("ns3::RandomDirection2dMobilityModel", - "Bounds", RectangleValue (Rectangle (0, 1000, 0, 1000)), - "Speed", RandomVariableValue (ConstantVariable (2000)), + "Bounds", RectangleValue (Rectangle (0, 20, 0, 20)), + "Speed", RandomVariableValue (ConstantVariable (2)), "Pause", RandomVariableValue (ConstantVariable (0.2))); mobility.Install (backbone); @@ -240,20 +250,38 @@ main (int argc, char *argv[]) // two containers here; one with all of the new nodes, and one // with all of the nodes including new and existing nodes // - NodeContainer newInfraNodes; - newInfraNodes.Create (infraNodes - 1); + NodeContainer stas; + stas.Create (infraNodes - 1); // Now, create the container with all nodes on this link - NodeContainer infra (backbone.Get (i), newInfraNodes); + NodeContainer infra (backbone.Get (i), stas); // - // Create another ad hoc network and devices + // Create an infrastructure network // WifiHelper wifiInfra = WifiHelper::Default (); wifiPhy.SetChannel (wifiChannel.Create ()); - NetDeviceContainer infraDevices = wifiInfra.Install (wifiPhy, infra); + // Create unique ssids for these networks + std::string ssidString("wifi-infra"); + std::stringstream ss; + ss << i; + ssidString += ss.str(); + Ssid ssid = Ssid (ssidString); + wifiInfra.SetRemoteStationManager ("ns3::ArfWifiManager"); + // setup stas + wifiInfra.SetMac ("ns3::NqstaWifiMac", + "Ssid", SsidValue (ssid), + "ActiveProbing", BooleanValue (false)); + NetDeviceContainer staDevices = wifiInfra.Install (wifiPhy, stas); + // setup ap. + wifiInfra.SetMac ("ns3::NqapWifiMac", "Ssid", SsidValue (ssid), + "BeaconGeneration", BooleanValue (true), + "BeaconInterval", TimeValue (Seconds (2.5))); + NetDeviceContainer apDevices = wifiInfra.Install (wifiPhy, backbone.Get (i)); + // Collect all of these new devices + NetDeviceContainer infraDevices (apDevices, staDevices); // Add the IPv4 protocol stack to the nodes in our container // - internet.Install (newInfraNodes); + internet.Install (stas); // // Assign IPv4 addresses to the device drivers (actually to the associated // IPv4 interfaces) we just created. @@ -277,8 +305,8 @@ main (int argc, char *argv[]) mobility.PushReferenceMobilityModel (backbone.Get (i)); mobility.SetPositionAllocator (subnetAlloc); mobility.SetMobilityModel ("ns3::RandomDirection2dMobilityModel", - "Bounds", RectangleValue (Rectangle (-25, 25, -25, 25)), - "Speed", RandomVariableValue (ConstantVariable (30)), + "Bounds", RectangleValue (Rectangle (-10, 10, -10, 10)), + "Speed", RandomVariableValue (ConstantVariable (3)), "Pause", RandomVariableValue (ConstantVariable (0.4))); mobility.Install (infra); } @@ -288,6 +316,14 @@ main (int argc, char *argv[]) // // /////////////////////////////////////////////////////////////////////////// + // The below global routing does not take into account wireless effects. + // However, it is useful for setting default routes for all of the nodes + // such as the LAN nodes. + NS_LOG_INFO ("Enabling global routing on all nodes"); + GlobalRouteManager::PopulateRoutingTables (); + + // We enable OLSR (which will be consulted at a higher priority than + // the global routing above) on the backbone ad hoc nodes NS_LOG_INFO ("Enabling OLSR routing on all backbone nodes"); OlsrHelper olsr; olsr.Install (backbone); @@ -299,16 +335,25 @@ main (int argc, char *argv[]) /////////////////////////////////////////////////////////////////////////// // Create the OnOff application to send UDP datagrams of size - // 210 bytes at a rate of 448 Kb/s, between two nodes + // 210 bytes at a rate of 10 Kb/s, between two nodes + // We'll send data from the first wired LAN node on the first wired LAN + // to the last wireless STA on the last infrastructure net, thereby + // causing packets to traverse CSMA to adhoc to infrastructure links + NS_LOG_INFO ("Create Applications."); uint16_t 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 - NS_ASSERT (lanNodes >= 5); - Ptr appSource = NodeList::GetNode (11); - Ptr appSink = NodeList::GetNode (13); - Ipv4Address remoteAddr = Ipv4Address ("172.16.0.5"); + // Let's make sure that the user does not define too few nodes + // to make this example work. We need lanNodes > 1 and infraNodes > 1 + NS_ASSERT (lanNodes > 1 && infraNodes > 1); + // We want the source to be the first node created outside of the backbone + // Conveniently, the variable "backboneNodes" holds this node index value + Ptr appSource = NodeList::GetNode (backboneNodes); + // We want the sink to be the last node created in the topology. + uint32_t lastNodeIndex = backboneNodes + backboneNodes*(lanNodes - 1) + backboneNodes*(infraNodes - 1) - 1; + Ptr appSink = NodeList::GetNode (lastNodeIndex); + // Let's fetch the IP address of the last node, which is on Ipv4Interface 1 + Ipv4Address remoteAddr = appSink->GetObject ()->GetAddress(1); OnOffHelper onoff ("ns3::UdpSocketFactory", Address (InetSocketAddress (remoteAddr, port))); @@ -331,21 +376,23 @@ main (int argc, char *argv[]) /////////////////////////////////////////////////////////////////////////// NS_LOG_INFO ("Configure Tracing."); - // - // Let's set up some ns-2-like ascii traces, using another helper class - // std::ofstream ascii; - ascii.open ("mixed-wireless.tr"); - YansWifiPhyHelper::EnableAsciiAll (ascii); - CsmaHelper::EnableAsciiAll (ascii); - // Look at nodes 11, 13 only - //WifiHelper::EnableAscii (ascii, 11, 0); - //WifiHelper::EnableAscii (ascii, 13, 0); + if (enableTracing == true) + { + // + // Let's set up some ns-2-like ascii traces, using another helper class + // + ascii.open ("mixed-wireless.tr"); + YansWifiPhyHelper::EnableAsciiAll (ascii); + CsmaHelper::EnableAsciiAll (ascii); + InternetStackHelper::EnableAsciiAll (ascii); - // Let's do a pcap trace on the backbone devices - YansWifiPhyHelper::EnablePcap ("mixed-wireless", backboneDevices); - // Let's additionally trace the application Sink, ifIndex 0 - CsmaHelper::EnablePcap ("mixed-wireless", appSink->GetId (), 0); + // Let's do a pcap trace on the application source and sink, ifIndex 0 + CsmaHelper::EnablePcap ("mixed-wireless", appSource->GetId (), 0); + YansWifiPhyHelper::EnablePcap ("mixed-wireless", appSink->GetId (), 0); + YansWifiPhyHelper::EnablePcap ("mixed-wireless", 9, 2); + YansWifiPhyHelper::EnablePcap ("mixed-wireless", 9, 0); + } if (useCourseChangeCallback == true) { From 1732ab51e241ba33474560fb712d4c9ae41a376f Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 13:12:28 +0100 Subject: [PATCH 04/29] virtualize ErrorRateModel --- bindings/python/ns3_module_core.py | 8 +- bindings/python/ns3_module_wifi.py | 26 ++- src/devices/wifi/error-rate-model.cc | 240 +------------------ src/devices/wifi/error-rate-model.h | 23 +- src/devices/wifi/wifi-phy-test.cc | 5 +- src/devices/wifi/wifi-test.cc | 3 +- src/devices/wifi/wscript | 2 + src/devices/wifi/yans-error-rate-model.cc | 269 ++++++++++++++++++++++ src/devices/wifi/yans-error-rate-model.h | 60 +++++ src/helper/yans-wifi-helper.cc | 2 +- 10 files changed, 366 insertions(+), 272 deletions(-) create mode 100644 src/devices/wifi/yans-error-rate-model.cc create mode 100644 src/devices/wifi/yans-error-rate-model.h diff --git a/bindings/python/ns3_module_core.py b/bindings/python/ns3_module_core.py index 86f397e24..1f8470d43 100644 --- a/bindings/python/ns3_module_core.py +++ b/bindings/python/ns3_module_core.py @@ -1906,7 +1906,7 @@ def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls): cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) - ## traced-value.h: void ns3::TracedValue::Connect(ns3::CallbackBase const & cb, std::basic_string,std::allocator > path) [member function] + ## traced-value.h: void ns3::TracedValue::Connect(ns3::CallbackBase const & cb, std::string path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) @@ -1914,7 +1914,7 @@ def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls): cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) - ## traced-value.h: void ns3::TracedValue::Disconnect(ns3::CallbackBase const & cb, std::basic_string,std::allocator > path) [member function] + ## traced-value.h: void ns3::TracedValue::Disconnect(ns3::CallbackBase const & cb, std::string path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) @@ -2062,7 +2062,7 @@ def register_functions(root_module): module.add_function('TypeNameGet', 'std::string', [], - template_parameters=['long']) + template_parameters=['long long']) ## type-name.h: extern std::string ns3::TypeNameGet() [free function] module.add_function('TypeNameGet', 'std::string', @@ -2082,7 +2082,7 @@ def register_functions(root_module): module.add_function('TypeNameGet', 'std::string', [], - template_parameters=['unsigned long']) + template_parameters=['unsigned long long']) ## type-name.h: extern std::string ns3::TypeNameGet() [free function] module.add_function('TypeNameGet', 'std::string', diff --git a/bindings/python/ns3_module_wifi.py b/bindings/python/ns3_module_wifi.py index 14dc92bfa..a7ab2649d 100644 --- a/bindings/python/ns3_module_wifi.py +++ b/bindings/python/ns3_module_wifi.py @@ -99,6 +99,8 @@ def register_types(module): module.add_class('WifiChannel', parent=root_module['ns3::Channel']) ## wifi-net-device.h: ns3::WifiNetDevice [class] module.add_class('WifiNetDevice', parent=root_module['ns3::NetDevice']) + ## yans-error-rate-model.h: ns3::YansErrorRateModel [class] + module.add_class('YansErrorRateModel', parent=root_module['ns3::ErrorRateModel']) ## yans-wifi-channel.h: ns3::YansWifiChannel [class] module.add_class('YansWifiChannel', parent=root_module['ns3::WifiChannel']) ## aarf-wifi-manager.h: ns3::AarfWifiManager [class] @@ -189,6 +191,7 @@ def register_methods(root_module): register_Ns3RraaWifiManager_methods(root_module, root_module['ns3::RraaWifiManager']) register_Ns3WifiChannel_methods(root_module, root_module['ns3::WifiChannel']) register_Ns3WifiNetDevice_methods(root_module, root_module['ns3::WifiNetDevice']) + register_Ns3YansErrorRateModel_methods(root_module, root_module['ns3::YansErrorRateModel']) register_Ns3YansWifiChannel_methods(root_module, root_module['ns3::YansWifiChannel']) register_Ns3AarfWifiManager_methods(root_module, root_module['ns3::AarfWifiManager']) return @@ -2051,13 +2054,13 @@ def register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, cls): def register_Ns3ErrorRateModel_methods(root_module, cls): ## error-rate-model.h: ns3::ErrorRateModel::ErrorRateModel(ns3::ErrorRateModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ErrorRateModel const &', 'arg0')]) + ## error-rate-model.h: ns3::ErrorRateModel::ErrorRateModel() [constructor] + cls.add_constructor([]) ## error-rate-model.h: static ns3::TypeId ns3::ErrorRateModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) - ## error-rate-model.h: ns3::ErrorRateModel::ErrorRateModel() [constructor] - cls.add_constructor([]) ## error-rate-model.h: double ns3::ErrorRateModel::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function] cls.add_method('CalculateSnr', 'double', @@ -2067,7 +2070,7 @@ def register_Ns3ErrorRateModel_methods(root_module, cls): cls.add_method('GetChunkSuccessRate', 'double', [param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')], - is_const=True) + is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3FriisPropagationLossModel_methods(root_module, cls): @@ -2736,6 +2739,23 @@ def register_Ns3WifiNetDevice_methods(root_module, cls): visibility='private', is_virtual=True) return +def register_Ns3YansErrorRateModel_methods(root_module, cls): + ## yans-error-rate-model.h: ns3::YansErrorRateModel::YansErrorRateModel(ns3::YansErrorRateModel const & arg0) [copy constructor] + cls.add_constructor([param('ns3::YansErrorRateModel const &', 'arg0')]) + ## yans-error-rate-model.h: static ns3::TypeId ns3::YansErrorRateModel::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## yans-error-rate-model.h: ns3::YansErrorRateModel::YansErrorRateModel() [constructor] + cls.add_constructor([]) + ## yans-error-rate-model.h: double ns3::YansErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function] + cls.add_method('GetChunkSuccessRate', + 'double', + [param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')], + is_const=True, is_virtual=True) + return + def register_Ns3YansWifiChannel_methods(root_module, cls): ## yans-wifi-channel.h: ns3::YansWifiChannel::YansWifiChannel(ns3::YansWifiChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::YansWifiChannel const &', 'arg0')]) diff --git a/src/devices/wifi/error-rate-model.cc b/src/devices/wifi/error-rate-model.cc index f3c950e86..fe2f9d6a0 100644 --- a/src/devices/wifi/error-rate-model.cc +++ b/src/devices/wifi/error-rate-model.cc @@ -18,28 +18,17 @@ * Author: Mathieu Lacage */ #include "error-rate-model.h" -#include "wifi-phy.h" -#include "ns3/log.h" - -NS_LOG_COMPONENT_DEFINE ("ErrorRateModel"); namespace ns3 { -NS_OBJECT_ENSURE_REGISTERED (ErrorRateModel); - -TypeId -ErrorRateModel::GetTypeId (void) +TypeId ErrorRateModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ErrorRateModel") .SetParent () - .AddConstructor () ; return tid; } -ErrorRateModel::ErrorRateModel () -{} - double ErrorRateModel::CalculateSnr (WifiMode txMode, double ber) const { @@ -64,231 +53,4 @@ ErrorRateModel::CalculateSnr (WifiMode txMode, double ber) const return low; } - -double -ErrorRateModel::Log2 (double val) const -{ - return log(val) / log(2.0); -} -double -ErrorRateModel::GetBpskBer (double snr, uint32_t signalSpread, uint32_t phyRate) const -{ - double EbNo = snr * signalSpread / phyRate; - double z = sqrt(EbNo); - double ber = 0.5 * erfc(z); - NS_LOG_INFO ("bpsk snr="< tx = CreateObject (); Ptr rx = CreateObject (); - Ptr error = CreateObject (); + Ptr error = CreateObject (); tx->SetErrorRateModel (error); rx->SetErrorRateModel (error); tx->SetChannel (channel); @@ -217,7 +218,7 @@ CollisionExperiment::Run (struct CollisionExperiment::Input input) Ptr txB = CreateObject (); Ptr rx = CreateObject (); - Ptr error = CreateObject (); + Ptr error = CreateObject (); txA->SetErrorRateModel (error); txB->SetErrorRateModel (error); rx->SetErrorRateModel (error); diff --git a/src/devices/wifi/wifi-test.cc b/src/devices/wifi/wifi-test.cc index f13b68a00..413141acd 100644 --- a/src/devices/wifi/wifi-test.cc +++ b/src/devices/wifi/wifi-test.cc @@ -8,6 +8,7 @@ #include "propagation-delay-model.h" #include "propagation-loss-model.h" #include "error-rate-model.h" +#include "yans-error-rate-model.h" #include "ns3/static-mobility-model.h" #include "ns3/node.h" #include "ns3/simulator.h" @@ -52,7 +53,7 @@ WifiTest::CreateOne (Vector pos, Ptr channel) Ptr mac = m_mac.Create (); Ptr mobility = CreateObject (); Ptr phy = CreateObject (); - Ptr error = CreateObject (); + Ptr error = CreateObject (); phy->SetErrorRateModel (error); phy->SetChannel (channel); phy->SetDevice (dev); diff --git a/src/devices/wifi/wscript b/src/devices/wifi/wscript index b01ac49e0..179fb35da 100644 --- a/src/devices/wifi/wscript +++ b/src/devices/wifi/wscript @@ -12,6 +12,7 @@ def build(bld): 'wifi-phy.cc', 'wifi-phy-state-helper.cc', 'error-rate-model.cc', + 'yans-error-rate-model.cc', 'interference-helper.cc', 'yans-wifi-phy.cc', 'yans-wifi-channel.cc', @@ -75,6 +76,7 @@ def build(bld): 'wifi-phy.h', 'supported-rates.h', 'error-rate-model.h', + 'yans-error-rate-model.h', ] obj = bld.create_ns3_program('wifi-phy-test', diff --git a/src/devices/wifi/yans-error-rate-model.cc b/src/devices/wifi/yans-error-rate-model.cc new file mode 100644 index 000000000..351fa3d48 --- /dev/null +++ b/src/devices/wifi/yans-error-rate-model.cc @@ -0,0 +1,269 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2005,2006 INRIA + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Mathieu Lacage + */ +#include "yans-error-rate-model.h" +#include "wifi-phy.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("YansErrorRateModel"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (YansErrorRateModel); + +TypeId +YansErrorRateModel::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::YansErrorRateModel") + .SetParent () + .AddConstructor () + ; + return tid; +} + +YansErrorRateModel::YansErrorRateModel () +{} + +double +YansErrorRateModel::Log2 (double val) const +{ + return log(val) / log(2.0); +} +double +YansErrorRateModel::GetBpskBer (double snr, uint32_t signalSpread, uint32_t phyRate) const +{ + double EbNo = snr * signalSpread / phyRate; + double z = sqrt(EbNo); + double ber = 0.5 * erfc(z); + NS_LOG_INFO ("bpsk snr="< + */ +#ifndef YANS_ERROR_RATE_MODEL_H +#define YANS_ERROR_RATE_MODEL_H + +#include +#include "wifi-mode.h" +#include "error-rate-model.h" + +namespace ns3 { + +class YansErrorRateModel : public ErrorRateModel +{ +public: + static TypeId GetTypeId (void); + + YansErrorRateModel (); + + virtual double GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbits) const; + +private: + double Log2 (double val) const; + double GetBpskBer (double snr, uint32_t signalSpread, uint32_t phyRate) const; + double GetQamBer (double snr, unsigned int m, uint32_t signalSpread, uint32_t phyRate) const; + uint32_t Factorial (uint32_t k) const; + double Binomial (uint32_t k, double p, uint32_t n) const; + double CalculatePdOdd (double ber, unsigned int d) const; + double CalculatePdEven (double ber, unsigned int d) const; + double CalculatePd (double ber, unsigned int d) const; + double GetFecBpskBer (double snr, double nbits, + uint32_t signalSpread, uint32_t phyRate, + uint32_t dFree, uint32_t adFree) const; + double GetFecQamBer (double snr, uint32_t nbits, + uint32_t signalSpread, + uint32_t phyRate, + uint32_t m, uint32_t dfree, + uint32_t adFree, uint32_t adFreePlusOne) const; +}; + + +} // namespace ns3 + +#endif /* YANS_ERROR_RATE_MODEL_H */ diff --git a/src/helper/yans-wifi-helper.cc b/src/helper/yans-wifi-helper.cc index f7c9a2c8d..264023b69 100644 --- a/src/helper/yans-wifi-helper.cc +++ b/src/helper/yans-wifi-helper.cc @@ -154,7 +154,7 @@ YansWifiPhyHelper YansWifiPhyHelper::Default (void) { YansWifiPhyHelper helper; - helper.SetErrorRateModel ("ns3::ErrorRateModel"); + helper.SetErrorRateModel ("ns3::YansErrorRateModel"); return helper; } From fc340529eea66752560644b6aab008d254bd0bc7 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 13:46:41 +0100 Subject: [PATCH 05/29] remove public static variables. Use public static methods --- src/devices/wifi/interference-helper.cc | 6 +- src/devices/wifi/wifi-phy.cc | 95 ++++++++++++++++------- src/devices/wifi/wifi-phy.h | 16 ++-- src/devices/wifi/yans-error-rate-model.cc | 16 ++-- src/devices/wifi/yans-wifi-phy.cc | 26 +++---- 5 files changed, 99 insertions(+), 60 deletions(-) diff --git a/src/devices/wifi/interference-helper.cc b/src/devices/wifi/interference-helper.cc index 2cb95fef2..fa50b5674 100644 --- a/src/devices/wifi/interference-helper.cc +++ b/src/devices/wifi/interference-helper.cc @@ -224,11 +224,11 @@ InterferenceHelper::Configure80211aParameters (void) m_80211a = true; m_plcpLongPreambleDelayUs = 16; m_plcpShortPreambleDelayUs = 16; - m_longPlcpHeaderMode = WifiPhy::g_6mba; - m_shortPlcpHeaderMode = WifiPhy::g_6mba; + m_longPlcpHeaderMode = WifiPhy::Get6mba (); + m_shortPlcpHeaderMode = WifiPhy::Get6mba (); m_plcpHeaderLength = 4 + 1 + 12 + 1 + 6; /* 4095 bytes at a 6Mb/s rate with a 1/2 coding rate. */ - m_maxPacketDuration = CalculateTxDuration (4095, WifiPhy::g_6mba, WIFI_PREAMBLE_LONG); + m_maxPacketDuration = CalculateTxDuration (4095, WifiPhy::Get6mba (), WIFI_PREAMBLE_LONG); } void diff --git a/src/devices/wifi/wifi-phy.cc b/src/devices/wifi/wifi-phy.cc index 7e145e83d..946fc12c6 100644 --- a/src/devices/wifi/wifi-phy.cc +++ b/src/devices/wifi/wifi-phy.cc @@ -37,34 +37,6 @@ NS_LOG_COMPONENT_DEFINE ("WifiPhy"); namespace ns3 { -// Define all the WifiMode needed for 802.11a -WifiMode WifiPhy::g_6mba = WifiModeFactory::CreateBpsk ("wifia-6mbs", - true, - 20000000, 6000000, 12000000); -WifiMode WifiPhy::g_9mba = WifiModeFactory::CreateBpsk ("wifia-9mbs", - false, - 20000000, 9000000, 12000000); -// XXX explain why Bpsk rather than Qpsk -WifiMode WifiPhy::g_12mba = WifiModeFactory::CreateBpsk ("wifia-12mbs", - true, - 20000000, 12000000, 24000000); -WifiMode WifiPhy::g_18mba = WifiModeFactory::CreateBpsk ("wifia-18mbs", - false, - 20000000, 18000000, 24000000); -WifiMode WifiPhy::g_24mba = WifiModeFactory::CreateBpsk ("wifia-24mbs", - true, - 20000000, 24000000, 48000000); -WifiMode WifiPhy::g_36mba = WifiModeFactory::CreateBpsk ("wifia-36mbs", - false, - 20000000, 36000000, 48000000); -WifiMode WifiPhy::g_48mba = WifiModeFactory::CreateBpsk ("wifia-48mbs", - false, - 20000000, 48000000, 72000000); -WifiMode WifiPhy::g_54mba = WifiModeFactory::CreateBpsk ("wifia-54mbs", - false, - 20000000, 54000000, 72000000); - - /**************************************************************** * This destructor is needed. ****************************************************************/ @@ -97,4 +69,71 @@ WifiPhy::~WifiPhy () NS_LOG_FUNCTION (this); } +WifiMode +WifiPhy::Get6mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-6mbs", + true, + 20000000, 6000000, 12000000); + return mode; +} +WifiMode +WifiPhy::Get9mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-9mbs", + false, + 20000000, 9000000, 12000000); + return mode; +} +WifiMode +WifiPhy::Get12mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-12mbs", + true, + 20000000, 12000000, 24000000); + return mode; +} +WifiMode +WifiPhy::Get18mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-18mbs", + false, + 20000000, 18000000, 24000000); + return mode; +} +WifiMode +WifiPhy::Get24mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-24mbs", + true, + 20000000, 24000000, 48000000); + return mode; +} +WifiMode +WifiPhy::Get36mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-36mbs", + false, + 20000000, 36000000, 48000000); + return mode; +} + +WifiMode +WifiPhy::Get48mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-48mbs", + false, + 20000000, 48000000, 72000000); + return mode; +} + +WifiMode +WifiPhy::Get54mba (void) +{ + static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-54mbs", + false, + 20000000, 54000000, 72000000); + return mode; +} + } // namespace ns3 diff --git a/src/devices/wifi/wifi-phy.h b/src/devices/wifi/wifi-phy.h index 58c2cdbc4..9501ecbfe 100644 --- a/src/devices/wifi/wifi-phy.h +++ b/src/devices/wifi/wifi-phy.h @@ -242,14 +242,14 @@ public: virtual Ptr GetChannel (void) const = 0; - static WifiMode g_6mba; - static WifiMode g_9mba; - static WifiMode g_12mba; - static WifiMode g_18mba; - static WifiMode g_24mba; - static WifiMode g_36mba; - static WifiMode g_48mba; - static WifiMode g_54mba; + static WifiMode Get6mba (void); + static WifiMode Get9mba (void); + static WifiMode Get12mba (void); + static WifiMode Get18mba (void); + static WifiMode Get24mba (void); + static WifiMode Get36mba (void); + static WifiMode Get48mba (void); + static WifiMode Get54mba (void); }; } // namespace ns3 diff --git a/src/devices/wifi/yans-error-rate-model.cc b/src/devices/wifi/yans-error-rate-model.cc index 351fa3d48..d2c810344 100644 --- a/src/devices/wifi/yans-error-rate-model.cc +++ b/src/devices/wifi/yans-error-rate-model.cc @@ -171,7 +171,7 @@ YansErrorRateModel::GetFecQamBer (double snr, uint32_t nbits, double YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbits) const { - if (mode == WifiPhy::g_6mba) + if (mode == WifiPhy::Get6mba ()) { return GetFecBpskBer (snr, nbits, @@ -181,7 +181,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 11 // adFree ); } - else if (mode == WifiPhy::g_9mba) + else if (mode == WifiPhy::Get9mba ()) { return GetFecBpskBer (snr, nbits, @@ -191,7 +191,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 8 // adFree ); } - else if (mode == WifiPhy::g_12mba) + else if (mode == WifiPhy::Get12mba ()) { return GetFecQamBer (snr, nbits, @@ -203,7 +203,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 0 // adFreePlusOne ); } - else if (mode == WifiPhy::g_18mba) + else if (mode == WifiPhy::Get18mba ()) { return GetFecQamBer (snr, nbits, @@ -215,7 +215,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 31 // adFreePlusOne ); } - else if (mode == WifiPhy::g_24mba) + else if (mode == WifiPhy::Get24mba ()) { return GetFecQamBer (snr, nbits, @@ -227,7 +227,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 0 // adFreePlusOne ); } - else if (mode == WifiPhy::g_36mba) + else if (mode == WifiPhy::Get36mba ()) { return GetFecQamBer (snr, nbits, @@ -239,7 +239,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 31 // adFreePlusOne ); } - else if (mode == WifiPhy::g_48mba) + else if (mode == WifiPhy::Get48mba ()) { return GetFecQamBer (snr, nbits, @@ -251,7 +251,7 @@ YansErrorRateModel::GetChunkSuccessRate (WifiMode mode, double snr, uint32_t nbi 16 // adFreePlusOne ); } - else if (mode == WifiPhy::g_54mba) + else if (mode == WifiPhy::Get54mba ()) { return GetFecQamBer (snr, nbits, diff --git a/src/devices/wifi/yans-wifi-phy.cc b/src/devices/wifi/yans-wifi-phy.cc index ee79c8d44..d662ce02a 100644 --- a/src/devices/wifi/yans-wifi-phy.cc +++ b/src/devices/wifi/yans-wifi-phy.cc @@ -416,14 +416,14 @@ YansWifiPhy::Configure80211a (void) { NS_LOG_FUNCTION (this); m_interference.Configure80211aParameters (); - m_modes.push_back (g_6mba); - m_modes.push_back (g_9mba); - m_modes.push_back (g_12mba); - m_modes.push_back (g_18mba); - m_modes.push_back (g_24mba); - m_modes.push_back (g_36mba); - m_modes.push_back (g_48mba); - m_modes.push_back (g_54mba); + m_modes.push_back (WifiPhy::Get6mba ()); + m_modes.push_back (WifiPhy::Get9mba ()); + m_modes.push_back (WifiPhy::Get12mba ()); + m_modes.push_back (WifiPhy::Get18mba ()); + m_modes.push_back (WifiPhy::Get24mba ()); + m_modes.push_back (WifiPhy::Get36mba ()); + m_modes.push_back (WifiPhy::Get48mba ()); + m_modes.push_back (WifiPhy::Get54mba ()); } void @@ -431,11 +431,11 @@ YansWifiPhy::ConfigureHolland (void) { NS_LOG_FUNCTION (this); m_interference.Configure80211aParameters (); - m_modes.push_back (g_6mba); - m_modes.push_back (g_12mba); - m_modes.push_back (g_18mba); - m_modes.push_back (g_36mba); - m_modes.push_back (g_54mba); + m_modes.push_back (WifiPhy::Get6mba ()); + m_modes.push_back (WifiPhy::Get12mba ()); + m_modes.push_back (WifiPhy::Get18mba ()); + m_modes.push_back (WifiPhy::Get36mba ()); + m_modes.push_back (WifiPhy::Get54mba ()); } void From 8eec10538a05e79bdae2d5d4032b24b8bedf0721 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 14:25:55 +0100 Subject: [PATCH 06/29] ensure that all wifi modes are registered --- src/devices/wifi/wifi-phy.cc | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/devices/wifi/wifi-phy.cc b/src/devices/wifi/wifi-phy.cc index 946fc12c6..c6a353fde 100644 --- a/src/devices/wifi/wifi-phy.cc +++ b/src/devices/wifi/wifi-phy.cc @@ -81,8 +81,8 @@ WifiMode WifiPhy::Get9mba (void) { static WifiMode mode = WifiModeFactory::CreateBpsk ("wifia-9mbs", - false, - 20000000, 9000000, 12000000); + false, + 20000000, 9000000, 12000000); return mode; } WifiMode @@ -137,3 +137,21 @@ WifiPhy::Get54mba (void) } } // namespace ns3 + +namespace { + +static class Constructor +{ +public: + Constructor () { + ns3::WifiPhy::Get6mba (); + ns3::WifiPhy::Get9mba (); + ns3::WifiPhy::Get12mba (); + ns3::WifiPhy::Get18mba (); + ns3::WifiPhy::Get24mba (); + ns3::WifiPhy::Get36mba (); + ns3::WifiPhy::Get48mba (); + ns3::WifiPhy::Get54mba (); + } +} g_constructor; +} From 6966dcc4a396ae35207fc5a36913ebaad93645d1 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 15:23:49 +0100 Subject: [PATCH 07/29] fix typo --- src/devices/wifi/jakes-propagation-loss-model.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/devices/wifi/jakes-propagation-loss-model.cc b/src/devices/wifi/jakes-propagation-loss-model.cc index 78c84deb2..baecb6120 100644 --- a/src/devices/wifi/jakes-propagation-loss-model.cc +++ b/src/devices/wifi/jakes-propagation-loss-model.cc @@ -141,7 +141,7 @@ JakesPropagationLossModel::GetTypeId (void) MakeUintegerAccessor (&JakesPropagationLossModel::m_nOscillators), MakeUintegerChecker ()) .AddAttribute ("DopplerFreq", - "The doppler frequency in Hz (f_d = v / lambda = v * f / c, the defualt is 0)", + "The doppler frequency in Hz (f_d = v / lambda = v * f / c), the default is 0)", DoubleValue (0.0), MakeDoubleAccessor (&JakesPropagationLossModel::m_fd), MakeDoubleChecker ()) From 2bcbf6bbaddb25739e5e243a34448580eb884166 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 15:25:31 +0100 Subject: [PATCH 08/29] fix coding style --- .../wifi/jakes-propagation-loss-model.cc | 118 ++++++++++-------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/src/devices/wifi/jakes-propagation-loss-model.cc b/src/devices/wifi/jakes-propagation-loss-model.cc index baecb6120..403dba503 100644 --- a/src/devices/wifi/jakes-propagation-loss-model.cc +++ b/src/devices/wifi/jakes-propagation-loss-model.cc @@ -31,8 +31,6 @@ NS_LOG_COMPONENT_DEFINE ("Jakes"); namespace ns3 { - - class JakesPropagationLossModel::PathCoefficients { public: @@ -68,9 +66,10 @@ JakesPropagationLossModel::PathCoefficients::PathCoefficients (Ptrm_variable.GetValue (); + for (uint8_t i = 0; i < m_nRays; i++) + { + m_phases[i] = new double[m_nOscillators + 1]; + for (uint8_t j = 0; j <= m_nOscillators; j++) + { + m_phases[i][j] = 2.0 * JakesPropagationLossModel::PI * m_jakes->m_variable.GetValue (); + } } - } m_lastUpdate = Simulator::Now (); } @@ -101,19 +102,23 @@ JakesPropagationLossModel::PathCoefficients::GetLoss (void) ComplexNumber coef= {0.0, 0.0}; ComplexNumber fading; double norm = 0.0; - for (uint8_t i = 0; i < m_nRays; i++) { - fading.real = 0.0; - fading.imag = 0.0; - for (uint8_t j = 0; j <= m_nOscillators; j++) { - m_phases[i][j] += 2.0 * JakesPropagationLossModel::PI * cos (2.0 * JakesPropagationLossModel::PI * j / N) * m_jakes->m_fd * interval.GetSeconds (); - m_phases[i][j] -= 2.0 * JakesPropagationLossModel::PI * floor (m_phases[i][j] / 2.0 / JakesPropagationLossModel::PI); - fading.real += m_jakes->m_amp[j].real * cos (m_phases[i][j]); - fading.imag += m_jakes->m_amp[j].imag * cos (m_phases[i][j]); - norm += sqrt(pow (m_jakes->m_amp[j].real, 2) + pow(m_jakes->m_amp[j].imag, 2)); - } + for (uint8_t i = 0; i < m_nRays; i++) + { + fading.real = 0.0; + fading.imag = 0.0; + for (uint8_t j = 0; j <= m_nOscillators; j++) + { + m_phases[i][j] += 2.0 * JakesPropagationLossModel::PI * + cos (2.0 * JakesPropagationLossModel::PI * j / N) * m_jakes->m_fd * interval.GetSeconds (); + m_phases[i][j] -= 2.0 * JakesPropagationLossModel::PI * + floor (m_phases[i][j] / 2.0 / JakesPropagationLossModel::PI); + fading.real += m_jakes->m_amp[j].real * cos (m_phases[i][j]); + fading.imag += m_jakes->m_amp[j].imag * cos (m_phases[i][j]); + norm += sqrt(pow (m_jakes->m_amp[j].real, 2) + pow(m_jakes->m_amp[j].imag, 2)); + } coef.real += fading.real; coef.imag += fading.imag; - } + } m_lastUpdate = Simulator::Now (); double k = sqrt (pow (coef.real, 2) + pow (coef.imag, 2)) / norm; NS_LOG_DEBUG ("Jakes coef "<< k << " (" << 10 * log10 (k) << "dB)"); @@ -136,7 +141,8 @@ JakesPropagationLossModel::GetTypeId (void) MakeUintegerAccessor (&JakesPropagationLossModel::m_nRays), MakeUintegerChecker ()) .AddAttribute ("NumberOfOscillatorsPerRay", - "The number of oscillators to use by default for compute the coeficent for a given ray of a given path (default is 4)", + "The number of oscillators to use by default for compute the coeficent for a given ray of a given " + "path (default is 4)", UintegerValue (4), MakeUintegerAccessor (&JakesPropagationLossModel::m_nOscillators), MakeUintegerChecker ()) @@ -162,14 +168,16 @@ JakesPropagationLossModel::JakesPropagationLossModel () JakesPropagationLossModel::~JakesPropagationLossModel () { delete [] m_amp; - for (PathsList::iterator i = m_paths.end (); i != m_paths.begin (); i--) { - PathsSet *ps = *i; - for (DestinationList::iterator r = ps->receivers.begin (); r != ps->receivers.end (); r++) { - PathCoefficients *pc = *r; - delete pc; + for (PathsList::iterator i = m_paths.end (); i != m_paths.begin (); i--) + { + PathsSet *ps = *i; + for (DestinationList::iterator r = ps->receivers.begin (); r != ps->receivers.end (); r++) + { + PathCoefficients *pc = *r; + delete pc; + } + delete ps; } - delete ps; - } } void @@ -179,11 +187,12 @@ JakesPropagationLossModel::DoConstruct () m_amp = new ComplexNumber[m_nOscillators + 1]; m_amp[0].real = 2.0 * sqrt(2.0 / N) * cos (PI / 4.0); m_amp[0].imag = 2.0 * sqrt(2.0 / N) * sin (PI / 4.0); - for (uint8_t i = 1; i <= m_nOscillators; i++) { - double beta = PI * (double)i / m_nOscillators; - m_amp[i].real = 4.0 * cos (beta) / sqrt(N); - m_amp[i].imag = 4.0 * sin (beta) / sqrt(N); - } + for (uint8_t i = 1; i <= m_nOscillators; i++) + { + double beta = PI * (double)i / m_nOscillators; + m_amp[i].real = 4.0 * cos (beta) / sqrt(N); + m_amp[i].imag = 4.0 * sin (beta) / sqrt(N); + } } void @@ -203,25 +212,29 @@ JakesPropagationLossModel::DoGetLoss (Ptr a, Ptr b) const { PathsList::iterator i = m_paths.end (); - while (i != m_paths.begin ()) { - i--; - PathsSet *ps = *i; - if (PeekPointer (ps->sender) == PeekPointer(a)) { - m_paths.erase (i); - m_paths.push_back (ps); - for (DestinationList::iterator r = ps->receivers.begin (); r != ps->receivers.end (); r++) { - PathCoefficients *pc = *r; - if (PeekPointer (pc->GetReceiver ()) == PeekPointer (b)) { - ps->receivers.erase (r); - ps->receivers.push_back (pc); - return pc->GetLoss (); - } - } - PathCoefficients *pc = new PathCoefficients (this, b, m_nRays, m_nOscillators); - ps->receivers.push_back (pc); - return pc->GetLoss (); + while (i != m_paths.begin ()) + { + i--; + PathsSet *ps = *i; + if (PeekPointer (ps->sender) == PeekPointer(a)) + { + m_paths.erase (i); + m_paths.push_back (ps); + for (DestinationList::iterator r = ps->receivers.begin (); r != ps->receivers.end (); r++) + { + PathCoefficients *pc = *r; + if (PeekPointer (pc->GetReceiver ()) == PeekPointer (b)) + { + ps->receivers.erase (r); + ps->receivers.push_back (pc); + return pc->GetLoss (); + } + } + PathCoefficients *pc = new PathCoefficients (this, b, m_nRays, m_nOscillators); + ps->receivers.push_back (pc); + return pc->GetLoss (); + } } - } PathsSet *ps = new PathsSet; ps->sender = a; PathCoefficients *pc = new PathCoefficients (this, b, m_nRays, m_nOscillators); @@ -230,6 +243,5 @@ JakesPropagationLossModel::DoGetLoss (Ptr a, return pc->GetLoss (); } - } // namespace ns3 From 8e2a69255644c3290c44d227a85cca0c4740eb21 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Tue, 6 Jan 2009 15:28:03 +0100 Subject: [PATCH 09/29] remove uneeded PeekPointer calls --- src/devices/wifi/jakes-propagation-loss-model.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/devices/wifi/jakes-propagation-loss-model.cc b/src/devices/wifi/jakes-propagation-loss-model.cc index 403dba503..50f4d2ade 100644 --- a/src/devices/wifi/jakes-propagation-loss-model.cc +++ b/src/devices/wifi/jakes-propagation-loss-model.cc @@ -216,14 +216,14 @@ JakesPropagationLossModel::DoGetLoss (Ptr a, { i--; PathsSet *ps = *i; - if (PeekPointer (ps->sender) == PeekPointer(a)) + if (ps->sender == a) { m_paths.erase (i); m_paths.push_back (ps); for (DestinationList::iterator r = ps->receivers.begin (); r != ps->receivers.end (); r++) { PathCoefficients *pc = *r; - if (PeekPointer (pc->GetReceiver ()) == PeekPointer (b)) + if (pc->GetReceiver () == b) { ps->receivers.erase (r); ps->receivers.push_back (pc); From 180f0d7f46c60e23a08450c1179f3913d3b6bbe3 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Wed, 7 Jan 2009 13:27:03 +0100 Subject: [PATCH 10/29] rescan python --- bindings/python/ns3_module_wifi.py | 56 +++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/bindings/python/ns3_module_wifi.py b/bindings/python/ns3_module_wifi.py index a7ab2649d..719b90026 100644 --- a/bindings/python/ns3_module_wifi.py +++ b/bindings/python/ns3_module_wifi.py @@ -1361,22 +1361,6 @@ def register_Ns3WifiModeValue_methods(root_module, cls): return def register_Ns3WifiPhy_methods(root_module, cls): - ## wifi-phy.h: ns3::WifiPhy::g_6mba [variable] - cls.add_static_attribute('g_6mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_9mba [variable] - cls.add_static_attribute('g_9mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_12mba [variable] - cls.add_static_attribute('g_12mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_18mba [variable] - cls.add_static_attribute('g_18mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_24mba [variable] - cls.add_static_attribute('g_24mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_36mba [variable] - cls.add_static_attribute('g_36mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_48mba [variable] - cls.add_static_attribute('g_48mba', 'ns3::WifiMode', is_const=False) - ## wifi-phy.h: ns3::WifiPhy::g_54mba [variable] - cls.add_static_attribute('g_54mba', 'ns3::WifiMode', is_const=False) ## wifi-phy.h: ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')]) ## wifi-phy.h: static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function] @@ -1486,6 +1470,46 @@ def register_Ns3WifiPhy_methods(root_module, cls): 'ns3::Ptr< ns3::WifiChannel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get6mba() [member function] + cls.add_method('Get6mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get9mba() [member function] + cls.add_method('Get9mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get12mba() [member function] + cls.add_method('Get12mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get18mba() [member function] + cls.add_method('Get18mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get24mba() [member function] + cls.add_method('Get24mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get36mba() [member function] + cls.add_method('Get36mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get48mba() [member function] + cls.add_method('Get48mba', + 'ns3::WifiMode', + [], + is_static=True) + ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::Get54mba() [member function] + cls.add_method('Get54mba', + 'ns3::WifiMode', + [], + is_static=True) return def register_Ns3WifiRemoteStationManager_methods(root_module, cls): From 04d95b5962f7fd64e37192d1f43e0164d3190a2e Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Wed, 7 Jan 2009 13:33:59 +0100 Subject: [PATCH 11/29] fix coding style --- src/simulator/time.cc | 76 +++++++++++++++++++++++++------------------ 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/src/simulator/time.cc b/src/simulator/time.cc index ba36543e6..10e9a067f 100644 --- a/src/simulator/time.cc +++ b/src/simulator/time.cc @@ -698,11 +698,14 @@ void TimeTests::CheckOperations(Time t0, Time t1, bool *ok, bool verbose) itu3 = tu3.GetHighPrecision().GetInteger()/(1e27); } -void TimeTests::CheckConversions(uint64_t tval, bool *ok, bool verbose) { +void TimeTests::CheckConversions(uint64_t tval, bool *ok, bool verbose) +{ Time t_sec, t_ms, t_us, t_ns, t_ps, t_fs; if (verbose) - std::cout << std::endl << "Check conversions: " << tval << std::endl; + { + std::cout << std::endl << "Check conversions: " << tval << std::endl; + } // First check the seconds t_sec = Seconds((double)tval); @@ -764,15 +767,18 @@ void TimeTests::CheckConversions(uint64_t tval, bool *ok, bool verbose) { } void TimeTests::CheckPrecision(TimeStepPrecision::precision_t prec, uint64_t val, bool *ok, - bool verbose) { - if (verbose) { - std::cout << "check precision 10^-" << prec << std::endl; - } + bool verbose) +{ + if (verbose) + { + std::cout << "check precision 10^-" << prec << std::endl; + } TimeStepPrecision::Set (prec); - if (TimeStepPrecision::Get () != prec) { - ok = false; - } + if (TimeStepPrecision::Get () != prec) + { + ok = false; + } /* These still need to be fixed. // The smallest value that can be stored is 1x10^(-prec) @@ -802,20 +808,24 @@ void TimeTests::CheckTimeSec (std::string test_id, double actual, bool verbose) { double prec = pow(10,-((double)(ns3::TimeStepPrecision::Get ()))) * precMultFactor; - if ((actual < (expected-prec)) || (actual > (expected+prec))) { - std::cout << "FAIL " << test_id - << " Expected:" << expected - << " Actual: " << actual - << " Precision: " << prec << std::endl; - *flag = false; - } else { - if (verbose) { - std::cout << "PASS " << test_id + if ((actual < (expected-prec)) || (actual > (expected+prec))) + { + std::cout << "FAIL " << test_id << " Expected:" << expected << " Actual: " << actual << " Precision: " << prec << std::endl; + *flag = false; + } + else + { + if (verbose) + { + std::cout << "PASS " << test_id + << " Expected:" << expected + << " Actual: " << actual + << " Precision: " << prec << std::endl; + } } - } } void TimeTests::CheckTime (std::string test_id, int64_t actual, @@ -823,25 +833,29 @@ void TimeTests::CheckTime (std::string test_id, int64_t actual, bool verbose) { double prec = pow(10,-((double)(ns3::TimeStepPrecision::Get ()))) * precMultFactor; - if ((actual < (expected-prec)) || (actual > (expected+prec))) { - std::cout << "FAIL " << test_id - << " Expected:" << expected - << " Actual: " << actual - << " Precision: " << prec << std::endl; - *flag = false; - } else { - if (verbose) { - std::cout << "PASS " << test_id + if ((actual < (expected-prec)) || (actual > (expected+prec))) + { + std::cout << "FAIL " << test_id << " Expected:" << expected - << " Actual: " << actual + << " Actual: " << actual << " Precision: " << prec << std::endl; + *flag = false; + } + else + { + if (verbose) + { + std::cout << "PASS " << test_id + << " Expected:" << expected + << " Actual: " << actual + << " Precision: " << prec << std::endl; + } } - } } static TimeTests g_time_tests; -}; +} #endif /* RUN_SELF_TESTS */ From a3ebce551f04ab960b0f236b2965353da0de4322 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Wed, 7 Jan 2009 14:49:30 +0100 Subject: [PATCH 12/29] bug 455: Scalar(0.1) / Scalar(1.25) has no effect --- src/simulator/high-precision-128.cc | 50 ++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/src/simulator/high-precision-128.cc b/src/simulator/high-precision-128.cc index 8c1bfecfb..eb6cc965b 100644 --- a/src/simulator/high-precision-128.cc +++ b/src/simulator/high-precision-128.cc @@ -18,6 +18,7 @@ * Author: Mathieu Lacage */ #include "high-precision-128.h" +#include "ns3/test.h" #include #include @@ -160,10 +161,24 @@ HighPrecision::Div (HighPrecision const &o) HP128INC (m_ndivs++); EnsureSlow (); const_cast (o).EnsureSlow (); - cairo_int128_t div = _cairo_int128_rsa (o.m_slowValue, 64); cairo_quorem128_t qr; - qr = _cairo_int128_divrem (m_slowValue, div); - m_slowValue = qr.quo; + qr = _cairo_int128_divrem (m_slowValue, o.m_slowValue); + m_slowValue = _cairo_int128_lsl (qr.quo, 64); + // Now, manage the remainder + cairo_int128_t div = o.m_slowValue; + cairo_int128_t tmp; + tmp = _cairo_int128_rsa (qr.rem, 64); + cairo_int128_t zero = _cairo_int64_to_int128 (0); + if (_cairo_int128_eq (tmp, zero)) + { + qr.rem = _cairo_int128_lsl (qr.rem, 64); + } + else + { + div = _cairo_int128_rsa (div, 64); + } + qr = _cairo_int128_divrem (qr.rem, div); + m_slowValue = _cairo_int128_add (m_slowValue, qr.quo); return false; } int @@ -207,14 +222,15 @@ HighPrecision128Tests::HighPrecision128Tests () HighPrecision128Tests::~HighPrecision128Tests () {} -#define CHECK_EXPECTED(v,expected) \ -{ \ - if (v.GetInteger () != expected) \ - { \ - Failure () << "file="<<__FILE__<<", line="<<__LINE__<<", expected: "< Date: Thu, 8 Jan 2009 09:31:38 +0100 Subject: [PATCH 13/29] a Calendar queue without resizing. --- src/simulator/calendar-scheduler.cc | 327 ++++++++++++++++++++++++++++ src/simulator/calendar-scheduler.h | 58 +++++ src/simulator/wscript | 2 + 3 files changed, 387 insertions(+) create mode 100644 src/simulator/calendar-scheduler.cc create mode 100644 src/simulator/calendar-scheduler.h diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc new file mode 100644 index 000000000..0aae470a4 --- /dev/null +++ b/src/simulator/calendar-scheduler.cc @@ -0,0 +1,327 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2005 INRIA + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Mathieu Lacage + */ + +#include "calendar-scheduler.h" +#include "event-impl.h" +#include +#include +#include +#include "ns3/assert.h" +#include "ns3/log.h" + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("CalendarScheduler"); + +class Calendar +{ +public: + Calendar (uint32_t nBuckets, + uint64_t newWidth, uint64_t startPrio); + ~Calendar (); + + void Insert (const Scheduler::Event &ev); + Scheduler::Event PeekNext (void) const; + Scheduler::Event RemoveNext (void); + void Remove (const Scheduler::Event &ev); + uint32_t GetNBuckets (void) const; + +private: + Calendar &operator = (const Calendar &o); + Calendar (const Calendar &o); + void UpdateSearch (uint32_t bucket, uint64_t ts) const; + + typedef std::list Bucket; + Bucket *m_buckets; + uint32_t m_nBuckets; + // duration of a year + uint64_t m_width; + // bucket index from which the last event was dequeued + uint32_t m_lastBucket; + // priority at the top of the bucket from which last event was dequeued + uint64_t m_bucketTop; + // priority of last event dequeued + uint64_t m_lastPrio; +}; + + +Calendar::Calendar (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio) +{ + m_buckets = new Bucket [nBuckets]; + m_nBuckets = nBuckets; + m_width = width; + m_lastPrio = startPrio; + uint32_t n = startPrio / width; + m_lastBucket = n % nBuckets; + m_bucketTop = (n + 1) * width; +} +Calendar::~Calendar () +{ + delete [] m_buckets; + m_buckets = 0; +} +uint32_t +Calendar::GetNBuckets (void) const +{ + return m_nBuckets; +} +void +Calendar::Insert (const Scheduler::Event &ev) +{ + // calculate bucket index. + uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; + + // insert in bucket list. + Bucket::iterator end = m_buckets[bucket].end (); + for (Bucket::iterator i = m_buckets[bucket].begin (); i != end; ++i) + { + if (ev.key < i->key) + { + m_buckets[bucket].insert (i, ev); + return; + } + } + m_buckets[bucket].push_back (ev); +} +void +Calendar::UpdateSearch (uint32_t bucket, uint64_t ts) const +{ + // we update these variables to be able to find the + // 'next' event faster next time. + Calendar *self = const_cast (this); + self->m_lastBucket = bucket; + self->m_bucketTop = ts; +} +Scheduler::Event +Calendar::PeekNext (void) const +{ + uint32_t i = m_lastBucket; + uint64_t bucketTop = m_bucketTop; + do { + if (!m_buckets[i].empty ()) + { + Scheduler::Event next = m_buckets[i].front (); + if (next.key.m_ts < bucketTop) + { + UpdateSearch (i, bucketTop); + return next; + } + } + i++; + i %= m_nBuckets; + bucketTop += m_width; + } while (i != m_lastBucket); + + // We did not find a low-priority event within next year. + // So, iterate again to search the absolute minimum priority event. + i = m_lastBucket; + bucketTop = m_bucketTop; + Scheduler::Event minEvent = {0, {~0, ~0}}; + uint32_t minBucket; + uint64_t minBucketTop; + do { + if (!m_buckets[i].empty ()) + { + Scheduler::Event event = m_buckets[i].front (); + if (event.key < minEvent.key) + { + minEvent = event; + minBucket = i; + minBucketTop = bucketTop; + } + } + i++; + i %= m_nBuckets; + bucketTop += m_width; + } while (i != m_lastBucket); + + UpdateSearch (minBucket, minBucketTop); + + return minEvent; +} + +Scheduler::Event +Calendar::RemoveNext (void) +{ + uint32_t i = m_lastBucket; + uint64_t bucketTop = m_bucketTop; + do { + if (!m_buckets[i].empty ()) + { + Scheduler::Event next = m_buckets[i].front (); + if (next.key.m_ts < bucketTop) + { + m_lastBucket = i; + m_bucketTop = bucketTop; + m_lastPrio = next.key.m_ts; + m_buckets[i].pop_front (); + return next; + } + } + i++; + i %= m_nBuckets; + bucketTop += m_width; + } while (i != m_lastBucket); + + // We did not find a low-priority event within next year. + // So, iterate again to search the absolute minimum priority event. + i = m_lastBucket; + bucketTop = m_bucketTop; + Scheduler::Event minEvent = {0, {~0, ~0}}; + uint32_t minBucket; + uint64_t minBucketTop; + do { + if (!m_buckets[i].empty ()) + { + Scheduler::Event event = m_buckets[i].front (); + if (event.key < minEvent.key) + { + minEvent = event; + minBucket = i; + minBucketTop = bucketTop; + } + } + i++; + i %= m_nBuckets; + bucketTop += m_width; + } while (i != m_lastBucket); + + m_lastBucket = minBucket; + m_bucketTop = minBucketTop; + m_lastPrio = minEvent.key.m_ts; + m_buckets[minBucket].pop_front (); + + return minEvent; +} + +void +Calendar::Remove (const Scheduler::Event &ev) +{ + // bucket index of event + uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; + + Bucket::iterator end = m_buckets[bucket].end (); + for (Bucket::iterator i = m_buckets[bucket].begin (); i != end; ++i) + { + if (i->key.m_uid == ev.key.m_uid) + { + NS_ASSERT (ev.impl == i->impl); + m_buckets[bucket].erase (i); + return; + } + } + NS_ASSERT (false); +} + + + + + +CalendarScheduler::CalendarScheduler () +{ + NS_LOG_FUNCTION (this); + m_calendar = new Calendar (2, 1, 0); + m_qSize = 0; +} +CalendarScheduler::~CalendarScheduler () +{ + NS_LOG_FUNCTION (this); + delete m_calendar; + m_calendar = 0; +} + +void +CalendarScheduler::Insert (const Event &ev) +{ + NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid); + m_calendar->Insert (ev); + m_qSize++; + ResizeUp (); +} +bool +CalendarScheduler::IsEmpty (void) const +{ + return m_qSize == 0; +} +Scheduler::Event +CalendarScheduler::PeekNext (void) const +{ + NS_LOG_FUNCTION (this); + return m_calendar->PeekNext (); +} + +Scheduler::Event +CalendarScheduler::RemoveNext (void) +{ + NS_LOG_FUNCTION (this); + + Scheduler::Event ev = m_calendar->RemoveNext (); + m_qSize--; + ResizeDown (); + + return ev; +} + +void +CalendarScheduler::Remove (const Event &ev) +{ + NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid); + + m_calendar->Remove (ev); + m_qSize--; + ResizeDown (); +} + +void +CalendarScheduler::ResizeUp (void) +{ + if (m_qSize > m_calendar->GetNBuckets () * 2) + { + Resize (m_calendar->GetNBuckets () * 2); + } +} +void +CalendarScheduler::ResizeDown (void) +{ + if (m_qSize < ((m_calendar->GetNBuckets () / 2) - 2)) + { + Resize (m_calendar->GetNBuckets () / 2); + } +} +#if 0 +uint32_t +CalendarScheduler::CalculateNewWidth (void) const +{ + // We don't implement the heuristic from the calendar queue paper. Instead, + // we implement the same heuristic found in the ns-2 calendar scheduler. + +} +#endif +void +CalendarScheduler::Resize (uint32_t newSize) +{ + NS_LOG_FUNCTION (this << newSize); + + +} + +} // namespace ns3 diff --git a/src/simulator/calendar-scheduler.h b/src/simulator/calendar-scheduler.h new file mode 100644 index 000000000..dd6faab66 --- /dev/null +++ b/src/simulator/calendar-scheduler.h @@ -0,0 +1,58 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2005 INRIA + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Mathieu Lacage + */ + +#ifndef CALENDAR_SCHEDULER_H +#define CALENDAR_SCHEDULER_H + +#include "scheduler.h" +#include + +namespace ns3 { + +class EventImpl; +class Calendar; + +/** + * \ingroup scheduler + */ +class CalendarScheduler : public Scheduler +{ +public: + CalendarScheduler (); + virtual ~CalendarScheduler (); + + virtual void Insert (const Event &ev); + virtual bool IsEmpty (void) const; + virtual Event PeekNext (void) const; + virtual Event RemoveNext (void); + virtual void Remove (const Event &ev); + +private: + void ResizeUp (void); + void ResizeDown (void); + void Resize (uint32_t newSize); + + Calendar *m_calendar; + uint32_t m_qSize; +}; + +} // namespace ns3 + +#endif /* CALENDAR_SCHEDULER_H */ diff --git a/src/simulator/wscript b/src/simulator/wscript index 506119579..adf1c09ef 100644 --- a/src/simulator/wscript +++ b/src/simulator/wscript @@ -59,6 +59,7 @@ def build(bld): 'list-scheduler.cc', 'map-scheduler.cc', 'heap-scheduler.cc', + 'calendar-scheduler.cc', 'event-impl.cc', 'simulator.cc', 'default-simulator-impl.cc', @@ -82,6 +83,7 @@ def build(bld): 'list-scheduler.h', 'map-scheduler.h', 'heap-scheduler.h', + 'calendar-scheduler.h', 'simulation-singleton.h', 'timer.h', 'timer-impl.h', From 03f68f9350362709e7a82c13275e5e701e229181 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Thu, 8 Jan 2009 11:15:27 +0100 Subject: [PATCH 14/29] resize calendar queue. Slow :/ --- src/simulator/calendar-scheduler.cc | 153 +++++++++++++++++----------- src/simulator/calendar-scheduler.h | 2 + 2 files changed, 95 insertions(+), 60 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 0aae470a4..076a2f5f5 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -34,7 +34,7 @@ class Calendar { public: Calendar (uint32_t nBuckets, - uint64_t newWidth, uint64_t startPrio); + uint64_t newWidth); ~Calendar (); void Insert (const Scheduler::Event &ev); @@ -51,28 +51,24 @@ private: typedef std::list Bucket; Bucket *m_buckets; uint32_t m_nBuckets; - // duration of a year + // duration of a bucket uint64_t m_width; // bucket index from which the last event was dequeued uint32_t m_lastBucket; // priority at the top of the bucket from which last event was dequeued uint64_t m_bucketTop; - // priority of last event dequeued - uint64_t m_lastPrio; }; Calendar::Calendar (uint32_t nBuckets, - uint64_t width, - uint64_t startPrio) + uint64_t width) { + NS_ASSERT (width > 0); m_buckets = new Bucket [nBuckets]; m_nBuckets = nBuckets; m_width = width; - m_lastPrio = startPrio; - uint32_t n = startPrio / width; - m_lastBucket = n % nBuckets; - m_bucketTop = (n + 1) * width; + m_lastBucket = 0; + m_bucketTop = m_width; } Calendar::~Calendar () { @@ -116,6 +112,9 @@ Calendar::PeekNext (void) const { uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; + Scheduler::Event minEvent = {0, {~0, ~0}}; + uint32_t minBucket = 0; // quiet compiler + uint64_t minBucketTop = 0; // quiet compiler do { if (!m_buckets[i].empty ()) { @@ -125,26 +124,9 @@ Calendar::PeekNext (void) const UpdateSearch (i, bucketTop); return next; } - } - i++; - i %= m_nBuckets; - bucketTop += m_width; - } while (i != m_lastBucket); - - // We did not find a low-priority event within next year. - // So, iterate again to search the absolute minimum priority event. - i = m_lastBucket; - bucketTop = m_bucketTop; - Scheduler::Event minEvent = {0, {~0, ~0}}; - uint32_t minBucket; - uint64_t minBucketTop; - do { - if (!m_buckets[i].empty ()) - { - Scheduler::Event event = m_buckets[i].front (); - if (event.key < minEvent.key) + if (next.key < minEvent.key) { - minEvent = event; + minEvent = next; minBucket = i; minBucketTop = bucketTop; } @@ -164,6 +146,9 @@ Calendar::RemoveNext (void) { uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; + Scheduler::Event minEvent = {0, {~0, ~0}}; + uint32_t minBucket = 0; // quiet compiler + uint64_t minBucketTop = 0; // quiet compiler do { if (!m_buckets[i].empty ()) { @@ -172,30 +157,12 @@ Calendar::RemoveNext (void) { m_lastBucket = i; m_bucketTop = bucketTop; - m_lastPrio = next.key.m_ts; m_buckets[i].pop_front (); return next; } - } - i++; - i %= m_nBuckets; - bucketTop += m_width; - } while (i != m_lastBucket); - - // We did not find a low-priority event within next year. - // So, iterate again to search the absolute minimum priority event. - i = m_lastBucket; - bucketTop = m_bucketTop; - Scheduler::Event minEvent = {0, {~0, ~0}}; - uint32_t minBucket; - uint64_t minBucketTop; - do { - if (!m_buckets[i].empty ()) - { - Scheduler::Event event = m_buckets[i].front (); - if (event.key < minEvent.key) + if (next.key < minEvent.key) { - minEvent = event; + minEvent = next; minBucket = i; minBucketTop = bucketTop; } @@ -207,7 +174,6 @@ Calendar::RemoveNext (void) m_lastBucket = minBucket; m_bucketTop = minBucketTop; - m_lastPrio = minEvent.key.m_ts; m_buckets[minBucket].pop_front (); return minEvent; @@ -233,13 +199,10 @@ Calendar::Remove (const Scheduler::Event &ev) } - - - CalendarScheduler::CalendarScheduler () { NS_LOG_FUNCTION (this); - m_calendar = new Calendar (2, 1, 0); + m_calendar = new Calendar (2, 1); m_qSize = 0; } CalendarScheduler::~CalendarScheduler () @@ -302,26 +265,96 @@ CalendarScheduler::ResizeUp (void) void CalendarScheduler::ResizeDown (void) { - if (m_qSize < ((m_calendar->GetNBuckets () / 2) - 2)) + if (m_qSize < m_calendar->GetNBuckets () / 2) { Resize (m_calendar->GetNBuckets () / 2); } } -#if 0 + uint32_t -CalendarScheduler::CalculateNewWidth (void) const +CalendarScheduler::CalculateNewWidth (std::list *dequeued) { - // We don't implement the heuristic from the calendar queue paper. Instead, - // we implement the same heuristic found in the ns-2 calendar scheduler. + if (m_qSize < 2) + { + return 1; + } + uint32_t nSamples; + if (m_qSize <= 5) + { + nSamples = m_qSize; + } + else + { + nSamples = 5 + m_qSize / 10; + } + if (nSamples > 25) + { + nSamples = 25; + } + + for (uint32_t i = 0; i < nSamples; i++) + { + dequeued->push_back (m_calendar->RemoveNext ()); + } + m_qSize -= nSamples; + uint64_t totalSeparation = 0; + std::list::const_iterator end = dequeued->end (); + std::list::const_iterator cur = dequeued->begin (); + std::list::const_iterator next = cur; + next++; + while (next != end) + { + totalSeparation += next->key.m_ts - cur->key.m_ts; + cur++; + next++; + } + uint64_t twiceAvg = totalSeparation / (nSamples - 1) * 2; + totalSeparation = 0; + cur = dequeued->begin (); + next = cur; + next++; + while (next != end) + { + uint64_t diff = next->key.m_ts - cur->key.m_ts; + if (diff <= twiceAvg) + { + totalSeparation += diff; + } + cur++; + next++; + } + + totalSeparation *= 3; + totalSeparation = std::max (totalSeparation, (uint64_t)1); + return totalSeparation; } -#endif + void CalendarScheduler::Resize (uint32_t newSize) { NS_LOG_FUNCTION (this << newSize); + std::list dequeued; + uint32_t newWidth = CalculateNewWidth (&dequeued); + Calendar *calendar = new Calendar (newSize, newWidth); + + for (uint32_t i = 0; i < m_qSize; i++) + { + Scheduler::Event ev = m_calendar->RemoveNext (); + calendar->Insert (ev); + } + std::list::const_iterator end = dequeued.end (); + for (std::list::const_iterator i = dequeued.begin (); + i != end; ++i) + { + calendar->Insert (*i); + } + m_qSize += dequeued.size (); + + delete m_calendar; + m_calendar = calendar; } } // namespace ns3 diff --git a/src/simulator/calendar-scheduler.h b/src/simulator/calendar-scheduler.h index dd6faab66..9b32c20da 100644 --- a/src/simulator/calendar-scheduler.h +++ b/src/simulator/calendar-scheduler.h @@ -23,6 +23,7 @@ #include "scheduler.h" #include +#include namespace ns3 { @@ -48,6 +49,7 @@ private: void ResizeUp (void); void ResizeDown (void); void Resize (uint32_t newSize); + uint32_t CalculateNewWidth (std::list *dequeued); Calendar *m_calendar; uint32_t m_qSize; From a60dcb5fb480623aa4be6dfdd85e37069511c07c Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Thu, 8 Jan 2009 11:21:25 +0100 Subject: [PATCH 15/29] add back asserts --- src/simulator/calendar-scheduler.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 076a2f5f5..3bf012143 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -229,6 +229,7 @@ Scheduler::Event CalendarScheduler::PeekNext (void) const { NS_LOG_FUNCTION (this); + NS_ASSERT (!IsEmpty ()); return m_calendar->PeekNext (); } @@ -236,7 +237,7 @@ Scheduler::Event CalendarScheduler::RemoveNext (void) { NS_LOG_FUNCTION (this); - + NS_ASSERT (!IsEmpty ()); Scheduler::Event ev = m_calendar->RemoveNext (); m_qSize--; ResizeDown (); @@ -248,7 +249,7 @@ void CalendarScheduler::Remove (const Event &ev) { NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid); - + NS_ASSERT (!IsEmpty ()); m_calendar->Remove (ev); m_qSize--; ResizeDown (); From e5bb6e6b60c980d4db17bccbea29eec28311ec68 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Thu, 8 Jan 2009 11:43:15 +0100 Subject: [PATCH 16/29] optimize resizing --- src/simulator/calendar-scheduler.cc | 39 +++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 3bf012143..0cbe633cb 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -37,7 +37,9 @@ public: uint64_t newWidth); ~Calendar (); + void InsertAll (const Calendar *calendar); void Insert (const Scheduler::Event &ev); + void InsertMin (const Scheduler::Event &ev); Scheduler::Event PeekNext (void) const; Scheduler::Event RemoveNext (void); void Remove (const Scheduler::Event &ev); @@ -80,6 +82,26 @@ Calendar::GetNBuckets (void) const { return m_nBuckets; } +void +Calendar::InsertAll (const Calendar *calendar) +{ + for (uint32_t i = 0; i < calendar->m_nBuckets; i++) + { + Bucket::iterator end = calendar->m_buckets[i].end (); + for (Bucket::iterator j = calendar->m_buckets[i].begin (); j != end; ++j) + { + Insert (*j); + } + } +} +void +Calendar::InsertMin (const Scheduler::Event &ev) +{ + uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; + m_lastBucket = bucket; + m_bucketTop = (m_lastBucket + 1) * m_width; + Insert (ev); +} void Calendar::Insert (const Scheduler::Event &ev) { @@ -297,7 +319,6 @@ CalendarScheduler::CalculateNewWidth (std::list *dequeued) { dequeued->push_back (m_calendar->RemoveNext ()); } - m_qSize -= nSamples; uint64_t totalSeparation = 0; std::list::const_iterator end = dequeued->end (); @@ -341,18 +362,20 @@ CalendarScheduler::Resize (uint32_t newSize) Calendar *calendar = new Calendar (newSize, newWidth); - for (uint32_t i = 0; i < m_qSize; i++) - { - Scheduler::Event ev = m_calendar->RemoveNext (); - calendar->Insert (ev); - } + calendar->InsertAll (m_calendar); std::list::const_iterator end = dequeued.end (); for (std::list::const_iterator i = dequeued.begin (); i != end; ++i) { - calendar->Insert (*i); + if (i == dequeued.begin ()) + { + calendar->InsertMin (*i); + } + else + { + calendar->Insert (*i); + } } - m_qSize += dequeued.size (); delete m_calendar; m_calendar = calendar; From 28a2ce0c66f9fdb0bfa449e51195678e0663e47f Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Thu, 8 Jan 2009 16:23:33 +0100 Subject: [PATCH 17/29] introduce lastPrio to handle resizing correctly --- src/simulator/calendar-scheduler.cc | 192 ++++++++++++++++------------ src/simulator/calendar-scheduler.h | 3 +- 2 files changed, 113 insertions(+), 82 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 0cbe633cb..329528150 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -33,22 +33,32 @@ NS_LOG_COMPONENT_DEFINE ("CalendarScheduler"); class Calendar { public: - Calendar (uint32_t nBuckets, - uint64_t newWidth); + Calendar (); ~Calendar (); + Calendar *CreateResized (uint32_t nBuckets, + uint64_t newWidth) const; + void InsertAll (const Calendar *calendar); void Insert (const Scheduler::Event &ev); - void InsertMin (const Scheduler::Event &ev); Scheduler::Event PeekNext (void) const; Scheduler::Event RemoveNext (void); void Remove (const Scheduler::Event &ev); uint32_t GetNBuckets (void) const; + std::list PeekNext (uint32_t n) const; + + void PrintBucketDistribution (void); private: Calendar &operator = (const Calendar &o); Calendar (const Calendar &o); - void UpdateSearch (uint32_t bucket, uint64_t ts) const; + Calendar (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio); + void Init (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio); + inline uint32_t Hash (uint64_t key) const; typedef std::list Bucket; Bucket *m_buckets; @@ -59,54 +69,80 @@ private: uint32_t m_lastBucket; // priority at the top of the bucket from which last event was dequeued uint64_t m_bucketTop; + // the priority of the last event removed. + uint64_t m_lastPrio; }; - +Calendar::Calendar () +{ + Init (2, 1, 0); +} Calendar::Calendar (uint32_t nBuckets, - uint64_t width) + uint64_t width, + uint64_t startPrio) { NS_ASSERT (width > 0); + Init (nBuckets, width, startPrio); +} +void +Calendar::Init (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio) +{ m_buckets = new Bucket [nBuckets]; m_nBuckets = nBuckets; m_width = width; - m_lastBucket = 0; - m_bucketTop = m_width; + m_lastPrio = startPrio; + m_lastBucket = Hash (startPrio); + m_bucketTop = (startPrio / width + 1) * width; } Calendar::~Calendar () { delete [] m_buckets; m_buckets = 0; } +Calendar * +Calendar::CreateResized (uint32_t nBuckets, + uint64_t newWidth) const +{ + Calendar *calendar = new Calendar (nBuckets, newWidth, m_lastPrio); + for (uint32_t i = 0; i < m_nBuckets; i++) + { + Bucket::iterator end = m_buckets[i].end (); + for (Bucket::iterator j = m_buckets[i].begin (); j != end; ++j) + { + calendar->Insert (*j); + } + } + return calendar; +} + +void +Calendar::PrintBucketDistribution (void) +{ + for (uint32_t i = 0; i < m_nBuckets; i++) + { + std::cout << m_buckets[i].size () << " "; + } + std::cout << std::endl; +} uint32_t Calendar::GetNBuckets (void) const { return m_nBuckets; } -void -Calendar::InsertAll (const Calendar *calendar) +uint32_t +Calendar::Hash (uint64_t ts) const { - for (uint32_t i = 0; i < calendar->m_nBuckets; i++) - { - Bucket::iterator end = calendar->m_buckets[i].end (); - for (Bucket::iterator j = calendar->m_buckets[i].begin (); j != end; ++j) - { - Insert (*j); - } - } -} -void -Calendar::InsertMin (const Scheduler::Event &ev) -{ - uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; - m_lastBucket = bucket; - m_bucketTop = (m_lastBucket + 1) * m_width; - Insert (ev); + uint32_t bucket = (ts / m_width) % m_nBuckets; + return bucket; } void Calendar::Insert (const Scheduler::Event &ev) { + NS_LOG_FUNCTION (this << ev.key.m_ts << ev.key.m_uid); // calculate bucket index. - uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; + uint32_t bucket = Hash (ev.key.m_ts); // insert in bucket list. Bucket::iterator end = m_buckets[bucket].end (); @@ -119,38 +155,56 @@ Calendar::Insert (const Scheduler::Event &ev) } } m_buckets[bucket].push_back (ev); + NS_LOG_LOGIC ("insert in bucket=" << bucket); } -void -Calendar::UpdateSearch (uint32_t bucket, uint64_t ts) const +std::list +Calendar::PeekNext (uint32_t n) const { - // we update these variables to be able to find the - // 'next' event faster next time. - Calendar *self = const_cast (this); - self->m_lastBucket = bucket; - self->m_bucketTop = ts; + // save state + uint32_t lastBucket = m_lastBucket; + uint64_t bucketTop = m_bucketTop; + uint64_t lastPrio = m_lastPrio; + + Calendar *self = const_cast (this); + std::list events; + // gather requested events + for (uint32_t i = 0; i < n; i++) + { + events.push_back (self->RemoveNext ()); + } + // put them back + for (std::list::const_iterator i = events.begin (); i != events.end (); ++i) + { + self->Insert (*i); + } + + // restore state. + self->m_lastBucket = lastBucket; + self->m_bucketTop = bucketTop; + self->m_lastPrio = lastPrio; + + // return copy of requested events. + return events; } + Scheduler::Event Calendar::PeekNext (void) const { + NS_LOG_FUNCTION (this << m_lastBucket << m_bucketTop); uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; Scheduler::Event minEvent = {0, {~0, ~0}}; - uint32_t minBucket = 0; // quiet compiler - uint64_t minBucketTop = 0; // quiet compiler do { if (!m_buckets[i].empty ()) { Scheduler::Event next = m_buckets[i].front (); if (next.key.m_ts < bucketTop) { - UpdateSearch (i, bucketTop); return next; } if (next.key < minEvent.key) { minEvent = next; - minBucket = i; - minBucketTop = bucketTop; } } i++; @@ -158,19 +212,16 @@ Calendar::PeekNext (void) const bucketTop += m_width; } while (i != m_lastBucket); - UpdateSearch (minBucket, minBucketTop); - return minEvent; } Scheduler::Event Calendar::RemoveNext (void) { + NS_LOG_FUNCTION (this << m_lastBucket << m_bucketTop); uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; Scheduler::Event minEvent = {0, {~0, ~0}}; - uint32_t minBucket = 0; // quiet compiler - uint64_t minBucketTop = 0; // quiet compiler do { if (!m_buckets[i].empty ()) { @@ -178,15 +229,15 @@ Calendar::RemoveNext (void) if (next.key.m_ts < bucketTop) { m_lastBucket = i; + m_lastPrio = next.key.m_ts; m_bucketTop = bucketTop; m_buckets[i].pop_front (); + NS_LOG_LOGIC ("remove ts=" << next.key.m_ts << ", key=" << next.key.m_uid << ", from bucket=" << i); return next; } if (next.key < minEvent.key) { minEvent = next; - minBucket = i; - minBucketTop = bucketTop; } } i++; @@ -194,9 +245,12 @@ Calendar::RemoveNext (void) bucketTop += m_width; } while (i != m_lastBucket); - m_lastBucket = minBucket; - m_bucketTop = minBucketTop; - m_buckets[minBucket].pop_front (); + m_lastPrio = minEvent.key.m_ts; + m_lastBucket = Hash (minEvent.key.m_ts); + m_bucketTop = (minEvent.key.m_ts / m_width + 1) * m_width; + m_buckets[m_lastBucket].pop_front (); + + NS_LOG_LOGIC ("remove ts=" << minEvent.key.m_ts << ", key=" << minEvent.key.m_uid << ", from bucket=" << m_lastBucket); return minEvent; } @@ -205,7 +259,7 @@ void Calendar::Remove (const Scheduler::Event &ev) { // bucket index of event - uint32_t bucket = (ev.key.m_ts / m_width) % m_nBuckets; + uint32_t bucket = Hash (ev.key.m_ts); Bucket::iterator end = m_buckets[bucket].end (); for (Bucket::iterator i = m_buckets[bucket].begin (); i != end; ++i) @@ -224,7 +278,7 @@ Calendar::Remove (const Scheduler::Event &ev) CalendarScheduler::CalendarScheduler () { NS_LOG_FUNCTION (this); - m_calendar = new Calendar (2, 1); + m_calendar = new Calendar (); m_qSize = 0; } CalendarScheduler::~CalendarScheduler () @@ -237,7 +291,6 @@ CalendarScheduler::~CalendarScheduler () void CalendarScheduler::Insert (const Event &ev) { - NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid); m_calendar->Insert (ev); m_qSize++; ResizeUp (); @@ -250,7 +303,6 @@ CalendarScheduler::IsEmpty (void) const Scheduler::Event CalendarScheduler::PeekNext (void) const { - NS_LOG_FUNCTION (this); NS_ASSERT (!IsEmpty ()); return m_calendar->PeekNext (); } @@ -258,7 +310,6 @@ CalendarScheduler::PeekNext (void) const Scheduler::Event CalendarScheduler::RemoveNext (void) { - NS_LOG_FUNCTION (this); NS_ASSERT (!IsEmpty ()); Scheduler::Event ev = m_calendar->RemoveNext (); m_qSize--; @@ -270,7 +321,6 @@ CalendarScheduler::RemoveNext (void) void CalendarScheduler::Remove (const Event &ev) { - NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid); NS_ASSERT (!IsEmpty ()); m_calendar->Remove (ev); m_qSize--; @@ -295,7 +345,7 @@ CalendarScheduler::ResizeDown (void) } uint32_t -CalendarScheduler::CalculateNewWidth (std::list *dequeued) +CalendarScheduler::CalculateNewWidth (void) { if (m_qSize < 2) { @@ -315,14 +365,11 @@ CalendarScheduler::CalculateNewWidth (std::list *dequeued) nSamples = 25; } - for (uint32_t i = 0; i < nSamples; i++) - { - dequeued->push_back (m_calendar->RemoveNext ()); - } + std::list samples = m_calendar->PeekNext (nSamples); uint64_t totalSeparation = 0; - std::list::const_iterator end = dequeued->end (); - std::list::const_iterator cur = dequeued->begin (); + std::list::const_iterator end = samples.end (); + std::list::const_iterator cur = samples.begin (); std::list::const_iterator next = cur; next++; while (next != end) @@ -333,7 +380,7 @@ CalendarScheduler::CalculateNewWidth (std::list *dequeued) } uint64_t twiceAvg = totalSeparation / (nSamples - 1) * 2; totalSeparation = 0; - cur = dequeued->begin (); + cur = samples.begin (); next = cur; next++; while (next != end) @@ -357,25 +404,10 @@ CalendarScheduler::Resize (uint32_t newSize) { NS_LOG_FUNCTION (this << newSize); - std::list dequeued; - uint32_t newWidth = CalculateNewWidth (&dequeued); - - Calendar *calendar = new Calendar (newSize, newWidth); + m_calendar->PrintBucketDistribution (); - calendar->InsertAll (m_calendar); - std::list::const_iterator end = dequeued.end (); - for (std::list::const_iterator i = dequeued.begin (); - i != end; ++i) - { - if (i == dequeued.begin ()) - { - calendar->InsertMin (*i); - } - else - { - calendar->Insert (*i); - } - } + uint32_t newWidth = CalculateNewWidth (); + Calendar *calendar = m_calendar->CreateResized (newSize, newWidth); delete m_calendar; m_calendar = calendar; diff --git a/src/simulator/calendar-scheduler.h b/src/simulator/calendar-scheduler.h index 9b32c20da..fbcad2ee8 100644 --- a/src/simulator/calendar-scheduler.h +++ b/src/simulator/calendar-scheduler.h @@ -23,7 +23,6 @@ #include "scheduler.h" #include -#include namespace ns3 { @@ -49,7 +48,7 @@ private: void ResizeUp (void); void ResizeDown (void); void Resize (uint32_t newSize); - uint32_t CalculateNewWidth (std::list *dequeued); + uint32_t CalculateNewWidth (void); Calendar *m_calendar; uint32_t m_qSize; From 557a62b1a1087ef9c6809a69f835ebd716bc496e Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 07:51:17 +0100 Subject: [PATCH 18/29] simplify the implementation --- src/simulator/calendar-scheduler.cc | 283 ++++++++++------------------ src/simulator/calendar-scheduler.h | 24 ++- 2 files changed, 122 insertions(+), 185 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 329528150..9ec14b182 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -30,65 +30,24 @@ namespace ns3 { NS_LOG_COMPONENT_DEFINE ("CalendarScheduler"); -class Calendar -{ -public: - Calendar (); - ~Calendar (); - - Calendar *CreateResized (uint32_t nBuckets, - uint64_t newWidth) const; - - void InsertAll (const Calendar *calendar); - void Insert (const Scheduler::Event &ev); - Scheduler::Event PeekNext (void) const; - Scheduler::Event RemoveNext (void); - void Remove (const Scheduler::Event &ev); - uint32_t GetNBuckets (void) const; - std::list PeekNext (uint32_t n) const; - - void PrintBucketDistribution (void); - -private: - Calendar &operator = (const Calendar &o); - Calendar (const Calendar &o); - Calendar (uint32_t nBuckets, - uint64_t width, - uint64_t startPrio); - void Init (uint32_t nBuckets, - uint64_t width, - uint64_t startPrio); - inline uint32_t Hash (uint64_t key) const; - - typedef std::list Bucket; - Bucket *m_buckets; - uint32_t m_nBuckets; - // duration of a bucket - uint64_t m_width; - // bucket index from which the last event was dequeued - uint32_t m_lastBucket; - // priority at the top of the bucket from which last event was dequeued - uint64_t m_bucketTop; - // the priority of the last event removed. - uint64_t m_lastPrio; -}; - -Calendar::Calendar () +CalendarScheduler::CalendarScheduler () { + NS_LOG_FUNCTION (this); Init (2, 1, 0); + m_qSize = 0; } -Calendar::Calendar (uint32_t nBuckets, - uint64_t width, - uint64_t startPrio) +CalendarScheduler::~CalendarScheduler () { - NS_ASSERT (width > 0); - Init (nBuckets, width, startPrio); + NS_LOG_FUNCTION (this); + delete [] m_buckets; + m_buckets = 0; } void -Calendar::Init (uint32_t nBuckets, - uint64_t width, - uint64_t startPrio) +CalendarScheduler::Init (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio) { + NS_LOG_FUNCTION (this << nBuckets << width << startPrio); m_buckets = new Bucket [nBuckets]; m_nBuckets = nBuckets; m_width = width; @@ -96,53 +55,31 @@ Calendar::Init (uint32_t nBuckets, m_lastBucket = Hash (startPrio); m_bucketTop = (startPrio / width + 1) * width; } -Calendar::~Calendar () -{ - delete [] m_buckets; - m_buckets = 0; -} -Calendar * -Calendar::CreateResized (uint32_t nBuckets, - uint64_t newWidth) const -{ - Calendar *calendar = new Calendar (nBuckets, newWidth, m_lastPrio); - for (uint32_t i = 0; i < m_nBuckets; i++) - { - Bucket::iterator end = m_buckets[i].end (); - for (Bucket::iterator j = m_buckets[i].begin (); j != end; ++j) - { - calendar->Insert (*j); - } - } - return calendar; -} - void -Calendar::PrintBucketDistribution (void) +CalendarScheduler::PrintInfo (void) { + std::cout << "nBuckets=" << m_nBuckets << ", width=" << m_width<< std::endl; + std::cout << "Bucket Distribution "; for (uint32_t i = 0; i < m_nBuckets; i++) { std::cout << m_buckets[i].size () << " "; } std::cout << std::endl; } -uint32_t -Calendar::GetNBuckets (void) const -{ - return m_nBuckets; -} uint32_t -Calendar::Hash (uint64_t ts) const +CalendarScheduler::Hash (uint64_t ts) const { uint32_t bucket = (ts / m_width) % m_nBuckets; return bucket; } + void -Calendar::Insert (const Scheduler::Event &ev) +CalendarScheduler::DoInsert (const Event &ev) { NS_LOG_FUNCTION (this << ev.key.m_ts << ev.key.m_uid); // calculate bucket index. uint32_t bucket = Hash (ev.key.m_ts); + NS_LOG_LOGIC ("insert in bucket=" << bucket); // insert in bucket list. Bucket::iterator end = m_buckets[bucket].end (); @@ -155,42 +92,25 @@ Calendar::Insert (const Scheduler::Event &ev) } } m_buckets[bucket].push_back (ev); - NS_LOG_LOGIC ("insert in bucket=" << bucket); } -std::list -Calendar::PeekNext (uint32_t n) const + +void +CalendarScheduler::Insert (const Event &ev) { - // save state - uint32_t lastBucket = m_lastBucket; - uint64_t bucketTop = m_bucketTop; - uint64_t lastPrio = m_lastPrio; - - Calendar *self = const_cast (this); - std::list events; - // gather requested events - for (uint32_t i = 0; i < n; i++) - { - events.push_back (self->RemoveNext ()); - } - // put them back - for (std::list::const_iterator i = events.begin (); i != events.end (); ++i) - { - self->Insert (*i); - } - - // restore state. - self->m_lastBucket = lastBucket; - self->m_bucketTop = bucketTop; - self->m_lastPrio = lastPrio; - - // return copy of requested events. - return events; + DoInsert (ev); + m_qSize++; + ResizeUp (); +} +bool +CalendarScheduler::IsEmpty (void) const +{ + return m_qSize == 0; } - Scheduler::Event -Calendar::PeekNext (void) const +CalendarScheduler::PeekNext (void) const { NS_LOG_FUNCTION (this << m_lastBucket << m_bucketTop); + NS_ASSERT (!IsEmpty ()); uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; Scheduler::Event minEvent = {0, {~0, ~0}}; @@ -216,9 +136,8 @@ Calendar::PeekNext (void) const } Scheduler::Event -Calendar::RemoveNext (void) +CalendarScheduler::DoRemoveNext (void) { - NS_LOG_FUNCTION (this << m_lastBucket << m_bucketTop); uint32_t i = m_lastBucket; uint64_t bucketTop = m_bucketTop; Scheduler::Event minEvent = {0, {~0, ~0}}; @@ -232,7 +151,6 @@ Calendar::RemoveNext (void) m_lastPrio = next.key.m_ts; m_bucketTop = bucketTop; m_buckets[i].pop_front (); - NS_LOG_LOGIC ("remove ts=" << next.key.m_ts << ", key=" << next.key.m_uid << ", from bucket=" << i); return next; } if (next.key < minEvent.key) @@ -250,14 +168,28 @@ Calendar::RemoveNext (void) m_bucketTop = (minEvent.key.m_ts / m_width + 1) * m_width; m_buckets[m_lastBucket].pop_front (); - NS_LOG_LOGIC ("remove ts=" << minEvent.key.m_ts << ", key=" << minEvent.key.m_uid << ", from bucket=" << m_lastBucket); - return minEvent; } -void -Calendar::Remove (const Scheduler::Event &ev) +Scheduler::Event +CalendarScheduler::RemoveNext (void) { + NS_LOG_FUNCTION (this << m_lastBucket << m_bucketTop); + NS_ASSERT (!IsEmpty ()); + + Scheduler::Event ev = DoRemoveNext (); + NS_LOG_LOGIC ("remove ts=" << ev.key.m_ts << + ", key=" << ev.key.m_uid << + ", from bucket=" << m_lastBucket); + m_qSize--; + ResizeDown (); + return ev; +} + +void +CalendarScheduler::Remove (const Event &ev) +{ + NS_ASSERT (!IsEmpty ()); // bucket index of event uint32_t bucket = Hash (ev.key.m_ts); @@ -268,79 +200,30 @@ Calendar::Remove (const Scheduler::Event &ev) { NS_ASSERT (ev.impl == i->impl); m_buckets[bucket].erase (i); + + m_qSize--; + ResizeDown (); return; } } NS_ASSERT (false); } - -CalendarScheduler::CalendarScheduler () -{ - NS_LOG_FUNCTION (this); - m_calendar = new Calendar (); - m_qSize = 0; -} -CalendarScheduler::~CalendarScheduler () -{ - NS_LOG_FUNCTION (this); - delete m_calendar; - m_calendar = 0; -} - -void -CalendarScheduler::Insert (const Event &ev) -{ - m_calendar->Insert (ev); - m_qSize++; - ResizeUp (); -} -bool -CalendarScheduler::IsEmpty (void) const -{ - return m_qSize == 0; -} -Scheduler::Event -CalendarScheduler::PeekNext (void) const -{ - NS_ASSERT (!IsEmpty ()); - return m_calendar->PeekNext (); -} - -Scheduler::Event -CalendarScheduler::RemoveNext (void) -{ - NS_ASSERT (!IsEmpty ()); - Scheduler::Event ev = m_calendar->RemoveNext (); - m_qSize--; - ResizeDown (); - - return ev; -} - -void -CalendarScheduler::Remove (const Event &ev) -{ - NS_ASSERT (!IsEmpty ()); - m_calendar->Remove (ev); - m_qSize--; - ResizeDown (); -} - void CalendarScheduler::ResizeUp (void) { - if (m_qSize > m_calendar->GetNBuckets () * 2) + if (m_qSize > m_nBuckets * 2 && + m_nBuckets < 32768) { - Resize (m_calendar->GetNBuckets () * 2); + Resize (m_nBuckets * 2); } } void CalendarScheduler::ResizeDown (void) { - if (m_qSize < m_calendar->GetNBuckets () / 2) + if (m_qSize < m_nBuckets / 2) { - Resize (m_calendar->GetNBuckets () / 2); + Resize (m_nBuckets / 2); } } @@ -365,8 +248,31 @@ CalendarScheduler::CalculateNewWidth (void) nSamples = 25; } - std::list samples = m_calendar->PeekNext (nSamples); - + // we gather the first nSamples from the queue + std::list samples; + // save state + uint32_t lastBucket = m_lastBucket; + uint64_t bucketTop = m_bucketTop; + uint64_t lastPrio = m_lastPrio; + + // gather requested events + for (uint32_t i = 0; i < nSamples; i++) + { + samples.push_back (DoRemoveNext ()); + } + // put them back + for (std::list::const_iterator i = samples.begin (); + i != samples.end (); ++i) + { + DoInsert (*i); + } + + // restore state. + m_lastBucket = lastBucket; + m_bucketTop = bucketTop; + m_lastPrio = lastPrio; + + // finally calculate inter-time average over samples. uint64_t totalSeparation = 0; std::list::const_iterator end = samples.end (); std::list::const_iterator cur = samples.begin (); @@ -398,19 +304,30 @@ CalendarScheduler::CalculateNewWidth (void) totalSeparation = std::max (totalSeparation, (uint64_t)1); return totalSeparation; } +void +CalendarScheduler::DoResize (uint32_t newSize, uint32_t newWidth) +{ + Bucket *oldBuckets = m_buckets; + uint32_t oldNBuckets = m_nBuckets; + Init (newSize, newWidth, m_lastPrio); + for (uint32_t i = 0; i < oldNBuckets; i++) + { + Bucket::iterator end = oldBuckets[i].end (); + for (Bucket::iterator j = oldBuckets[i].begin (); j != end; ++j) + { + DoInsert (*j); + } + } +} void CalendarScheduler::Resize (uint32_t newSize) { NS_LOG_FUNCTION (this << newSize); - m_calendar->PrintBucketDistribution (); - + //PrintInfo (); uint32_t newWidth = CalculateNewWidth (); - Calendar *calendar = m_calendar->CreateResized (newSize, newWidth); - - delete m_calendar; - m_calendar = calendar; + DoResize (newSize, newWidth); } } // namespace ns3 diff --git a/src/simulator/calendar-scheduler.h b/src/simulator/calendar-scheduler.h index fbcad2ee8..a034c685a 100644 --- a/src/simulator/calendar-scheduler.h +++ b/src/simulator/calendar-scheduler.h @@ -23,11 +23,11 @@ #include "scheduler.h" #include +#include namespace ns3 { class EventImpl; -class Calendar; /** * \ingroup scheduler @@ -49,8 +49,28 @@ private: void ResizeDown (void); void Resize (uint32_t newSize); uint32_t CalculateNewWidth (void); + void Init (uint32_t nBuckets, + uint64_t width, + uint64_t startPrio); + inline uint32_t Hash (uint64_t key) const; + void PrintInfo (void); + void DoResize (uint32_t newSize, uint32_t newWidth); + Scheduler::Event DoRemoveNext (void); + void DoInsert (const Event &ev); - Calendar *m_calendar; + typedef std::list Bucket; + Bucket *m_buckets; + // number of buckets in array + uint32_t m_nBuckets; + // duration of a bucket + uint64_t m_width; + // bucket index from which the last event was dequeued + uint32_t m_lastBucket; + // priority at the top of the bucket from which last event was dequeued + uint64_t m_bucketTop; + // the priority of the last event removed + uint64_t m_lastPrio; + // number of events in queue uint32_t m_qSize; }; From b2624f8ae9cd470d17a8e7d09a6d373dcc280587 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 07:51:42 +0100 Subject: [PATCH 19/29] handle calendar scheduler in bench --- utils/bench-simulator.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/utils/bench-simulator.cc b/utils/bench-simulator.cc index 1c096b113..75eeda668 100644 --- a/utils/bench-simulator.cc +++ b/utils/bench-simulator.cc @@ -168,6 +168,10 @@ int main (int argc, char *argv[]) { Simulator::SetScheduler (CreateObject ()); } + else if (strcmp ("--calendar", argv[0]) == 0) + { + Simulator::SetScheduler (CreateObject ()); + } else if (strcmp ("--debug", argv[0]) == 0) { g_debug = true; From 85af7552ddbbbc1df76bf2412ffbfb1e039d6c2c Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 08:17:46 +0100 Subject: [PATCH 20/29] add SchedulerType global variable --- src/simulator/calendar-scheduler.cc | 14 ++++++++++++- src/simulator/calendar-scheduler.h | 16 ++++++++++++++- src/simulator/heap-scheduler.cc | 11 ++++++++++ src/simulator/heap-scheduler.h | 2 ++ src/simulator/list-scheduler.cc | 12 +++++++++++ src/simulator/list-scheduler.h | 2 ++ src/simulator/map-scheduler.cc | 12 +++++++++++ src/simulator/map-scheduler.h | 2 ++ src/simulator/simulator.cc | 32 ++++++++++++++++++++--------- 9 files changed, 91 insertions(+), 12 deletions(-) diff --git a/src/simulator/calendar-scheduler.cc b/src/simulator/calendar-scheduler.cc index 9ec14b182..904ecfcf2 100644 --- a/src/simulator/calendar-scheduler.cc +++ b/src/simulator/calendar-scheduler.cc @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2005 INRIA + * Copyright (c) 2009 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as @@ -30,6 +30,18 @@ namespace ns3 { NS_LOG_COMPONENT_DEFINE ("CalendarScheduler"); +NS_OBJECT_ENSURE_REGISTERED (CalendarScheduler); + +TypeId +CalendarScheduler::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::CalendarScheduler") + .SetParent () + .AddConstructor () + ; + return tid; +} + CalendarScheduler::CalendarScheduler () { NS_LOG_FUNCTION (this); diff --git a/src/simulator/calendar-scheduler.h b/src/simulator/calendar-scheduler.h index a034c685a..79f420fe6 100644 --- a/src/simulator/calendar-scheduler.h +++ b/src/simulator/calendar-scheduler.h @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2005 INRIA + * Copyright (c) 2009 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as @@ -31,10 +31,24 @@ class EventImpl; /** * \ingroup scheduler + * \brief a calendar queue event scheduler + * + * This event scheduler is a direct implementation of the algorithm known as a calendar queue. + * first published in 1988 in "Calendar Queues: A Fast O(1) Priority Queue Implementation for + * the Simulation Event Set Problem" by Randy Brown. There are many refinements published + * later but this class implements the original algorithm (to the best of my knowledge). + * + * Note: This queue is much slower than I expected (much slower than the std::map queue) + * and this seems to be because the original resizing policy is horribly bad. This is + * most likely the reason why there have been so many variations published which all + * slightly tweak the resizing heuristics to obtain a better distribution of events + * across buckets. */ class CalendarScheduler : public Scheduler { public: + static TypeId GetTypeId (void); + CalendarScheduler (); virtual ~CalendarScheduler (); diff --git a/src/simulator/heap-scheduler.cc b/src/simulator/heap-scheduler.cc index 6795f64fd..fa39011b9 100644 --- a/src/simulator/heap-scheduler.cc +++ b/src/simulator/heap-scheduler.cc @@ -29,6 +29,17 @@ NS_LOG_COMPONENT_DEFINE ("HeapScheduler"); namespace ns3 { +NS_OBJECT_ENSURE_REGISTERED (HeapScheduler); + +TypeId +HeapScheduler::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::HeapScheduler") + .SetParent () + .AddConstructor () + ; + return tid; +} HeapScheduler::HeapScheduler () { diff --git a/src/simulator/heap-scheduler.h b/src/simulator/heap-scheduler.h index ca4a38be5..600f26dc9 100644 --- a/src/simulator/heap-scheduler.h +++ b/src/simulator/heap-scheduler.h @@ -47,6 +47,8 @@ namespace ns3 { class HeapScheduler : public Scheduler { public: + static TypeId GetTypeId (void); + HeapScheduler (); virtual ~HeapScheduler (); diff --git a/src/simulator/list-scheduler.cc b/src/simulator/list-scheduler.cc index 822cfe4a8..9c4bc3b40 100644 --- a/src/simulator/list-scheduler.cc +++ b/src/simulator/list-scheduler.cc @@ -27,6 +27,18 @@ namespace ns3 { +NS_OBJECT_ENSURE_REGISTERED (ListScheduler); + +TypeId +ListScheduler::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::ListScheduler") + .SetParent () + .AddConstructor () + ; + return tid; +} + ListScheduler::ListScheduler () {} ListScheduler::~ListScheduler () diff --git a/src/simulator/list-scheduler.h b/src/simulator/list-scheduler.h index 064ae1d17..55317c02a 100644 --- a/src/simulator/list-scheduler.h +++ b/src/simulator/list-scheduler.h @@ -40,6 +40,8 @@ class EventImpl; class ListScheduler : public Scheduler { public: + static TypeId GetTypeId (void); + ListScheduler (); virtual ~ListScheduler (); diff --git a/src/simulator/map-scheduler.cc b/src/simulator/map-scheduler.cc index ce861b8d0..cb1d6573b 100644 --- a/src/simulator/map-scheduler.cc +++ b/src/simulator/map-scheduler.cc @@ -29,6 +29,18 @@ NS_LOG_COMPONENT_DEFINE ("MapScheduler"); namespace ns3 { +NS_OBJECT_ENSURE_REGISTERED (MapScheduler); + +TypeId +MapScheduler::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::MapScheduler") + .SetParent () + .AddConstructor () + ; + return tid; +} + MapScheduler::MapScheduler () {} MapScheduler::~MapScheduler () diff --git a/src/simulator/map-scheduler.h b/src/simulator/map-scheduler.h index d82eb7fec..c07102a03 100644 --- a/src/simulator/map-scheduler.h +++ b/src/simulator/map-scheduler.h @@ -38,6 +38,8 @@ namespace ns3 { class MapScheduler : public Scheduler { public: + static TypeId GetTypeId (void); + MapScheduler (); virtual ~MapScheduler (); diff --git a/src/simulator/simulator.cc b/src/simulator/simulator.cc index b399d806f..efd1c80bc 100644 --- a/src/simulator/simulator.cc +++ b/src/simulator/simulator.cc @@ -23,7 +23,6 @@ #include "default-simulator-impl.h" #include "realtime-simulator-impl.h" #include "scheduler.h" -#include "map-scheduler.h" #include "event-impl.h" #include "ns3/ptr.h" @@ -48,6 +47,12 @@ GlobalValue g_simTypeImpl = GlobalValue ("SimulatorImplementationType", StringValue ("ns3::DefaultSimulatorImpl"), MakeStringChecker ()); +GlobalValue g_schedTypeImpl = GlobalValue ("SchedulerType", + "The object class to use as the scheduler implementation", + StringValue ("ns3::MapScheduler"), + MakeStringChecker ()); + + #ifdef NS3_LOG_ENABLE // @@ -77,15 +82,21 @@ static SimulatorImpl * GetImpl (void) */ if (impl == 0) { - ObjectFactory factory; - StringValue s; - - g_simTypeImpl.GetValue (s); - factory.SetTypeId (s.Get ()); - impl = factory.Create (); - - Ptr scheduler = CreateObject (); - impl->SetScheduler (scheduler); + { + ObjectFactory factory; + StringValue s; + + g_simTypeImpl.GetValue (s); + factory.SetTypeId (s.Get ()); + impl = factory.Create (); + } + { + ObjectFactory factory; + StringValue s; + g_schedTypeImpl.GetValue (s); + factory.SetTypeId (s.Get ()); + impl->SetScheduler (factory.Create ()); + } // // Note: we call LogSetTimePrinter _after_ creating the implementation @@ -302,6 +313,7 @@ Simulator::GetImplementation (void) #include "ns3/ptr.h" #include "list-scheduler.h" #include "heap-scheduler.h" +#include "map-scheduler.h" namespace ns3 { From c41be20e405a39f2b157be0eb1cbfe2a3e0ff170 Mon Sep 17 00:00:00 2001 From: Mauro Tortonesi Date: Fri, 9 Jan 2009 08:31:17 +0100 Subject: [PATCH 21/29] bug 460: ListPositionAllocator bug --- src/mobility/position-allocator.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/mobility/position-allocator.cc b/src/mobility/position-allocator.cc index 0bf06f863..31427117b 100644 --- a/src/mobility/position-allocator.cc +++ b/src/mobility/position-allocator.cc @@ -70,6 +70,10 @@ ListPositionAllocator::GetNext (void) const { Vector v = *m_current; m_current++; + if (m_current == m_positions.end()) + { + m_current = m_positions.begin (); + } return v; } From 4bdb706cf05b6461c2d45d911d3e2d458c891b55 Mon Sep 17 00:00:00 2001 From: Mauro Tortonesi Date: Fri, 9 Jan 2009 08:34:08 +0100 Subject: [PATCH 22/29] bug 461: RandomWaypointMobilityModel broken --- src/mobility/random-waypoint-mobility-model.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mobility/random-waypoint-mobility-model.cc b/src/mobility/random-waypoint-mobility-model.cc index a7c6e1537..5188fff82 100644 --- a/src/mobility/random-waypoint-mobility-model.cc +++ b/src/mobility/random-waypoint-mobility-model.cc @@ -56,7 +56,7 @@ RandomWaypointMobilityModel::GetTypeId (void) RandomWaypointMobilityModel::RandomWaypointMobilityModel () { - Simulator::ScheduleNow (&RandomWaypointMobilityModel::Start, this); + m_event = Simulator::ScheduleNow (&RandomWaypointMobilityModel::Start, this); } void @@ -72,6 +72,7 @@ RandomWaypointMobilityModel::BeginWalk (void) double k = speed / std::sqrt (dx*dx + dy*dy + dz*dz); m_helper.SetVelocity (Vector (k*dx, k*dy, k*dz)); + m_helper.Unpause (); Time travelDelay = Seconds (CalculateDistance (destination, m_current) / speed); m_event = Simulator::Schedule (travelDelay, &RandomWaypointMobilityModel::Start, this); @@ -99,7 +100,7 @@ RandomWaypointMobilityModel::DoSetPosition (const Vector &position) { m_helper.SetPosition (position); Simulator::Remove (m_event); - Simulator::ScheduleNow (&RandomWaypointMobilityModel::Start, this); + m_event = Simulator::ScheduleNow (&RandomWaypointMobilityModel::Start, this); } Vector RandomWaypointMobilityModel::DoGetVelocity (void) const From 74f2de296cf19f15fd740dd2235d1c4b56fee406 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 08:54:32 +0100 Subject: [PATCH 23/29] bug 459: Simulator::Run does nothing after Simulator::Stop is called --- src/simulator/default-simulator-impl.cc | 2 +- src/simulator/realtime-simulator-impl.cc | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/simulator/default-simulator-impl.cc b/src/simulator/default-simulator-impl.cc index 670413c71..ec3db6aac 100644 --- a/src/simulator/default-simulator-impl.cc +++ b/src/simulator/default-simulator-impl.cc @@ -144,7 +144,7 @@ DefaultSimulatorImpl::Next (void) const void DefaultSimulatorImpl::Run (void) { - + m_stop = false; while (!m_events->IsEmpty () && !m_stop) { ProcessOneEvent (); diff --git a/src/simulator/realtime-simulator-impl.cc b/src/simulator/realtime-simulator-impl.cc index bd49d028d..5cc3c10b1 100644 --- a/src/simulator/realtime-simulator-impl.cc +++ b/src/simulator/realtime-simulator-impl.cc @@ -421,6 +421,7 @@ RealtimeSimulatorImpl::Run (void) NS_ASSERT_MSG (m_running == false, "RealtimeSimulatorImpl::Run(): Simulator already running"); + m_stop = false; m_running = true; m_synchronizer->SetOrigin (m_currentTs); From c33a52854141bfc279c91de4f80e7678462eb4fb Mon Sep 17 00:00:00 2001 From: Timo Bingmann Date: Fri, 9 Jan 2009 09:13:02 +0100 Subject: [PATCH 24/29] update prev even if it is null --- src/helper/yans-wifi-helper.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helper/yans-wifi-helper.cc b/src/helper/yans-wifi-helper.cc index 264023b69..d0c701491 100644 --- a/src/helper/yans-wifi-helper.cc +++ b/src/helper/yans-wifi-helper.cc @@ -131,12 +131,12 @@ YansWifiChannelHelper::Create (void) const if (prev != 0) { prev->SetNext (cur); - prev = cur; } if (m_propagationLoss.begin () == i) { channel->SetPropagationLossModel (cur); } + prev = cur; } Ptr delay = m_propagationDelay.Create (); channel->SetPropagationDelayModel (delay); From 011ece16dfa015febac37b6fe1f965d4af386b36 Mon Sep 17 00:00:00 2001 From: Timo Bingmann Date: Fri, 9 Jan 2009 09:39:42 +0100 Subject: [PATCH 25/29] PropagationLossModel::GetLoss -> CalcRxPower. Add ThreeLogDistancePropagationLossModel. --- samples/main-propagation-loss.cc | 2 +- .../wifi/jakes-propagation-loss-model.cc | 13 +- .../wifi/jakes-propagation-loss-model.h | 6 +- src/devices/wifi/propagation-loss-model.cc | 163 +++++++++++++++--- src/devices/wifi/propagation-loss-model.h | 102 +++++++++-- src/devices/wifi/yans-wifi-channel.cc | 2 +- 6 files changed, 235 insertions(+), 53 deletions(-) diff --git a/samples/main-propagation-loss.cc b/samples/main-propagation-loss.cc index bee2b4d71..d0af2d71e 100644 --- a/samples/main-propagation-loss.cc +++ b/samples/main-propagation-loss.cc @@ -40,7 +40,7 @@ PrintOne (double minTxpower, double maxTxpower, double stepTxpower, double min, std::cout << x << " "; for (double txpower = minTxpower; txpower < maxTxpower; txpower += stepTxpower) { - double rxPowerDbm = txpower + model->GetLoss (a, b); + double rxPowerDbm = model->CalcRxPower (txpower, a, b); std::cout << rxPowerDbm << " "; } std::cout << std::endl; diff --git a/src/devices/wifi/jakes-propagation-loss-model.cc b/src/devices/wifi/jakes-propagation-loss-model.cc index 50f4d2ade..aaf030d10 100644 --- a/src/devices/wifi/jakes-propagation-loss-model.cc +++ b/src/devices/wifi/jakes-propagation-loss-model.cc @@ -207,9 +207,10 @@ JakesPropagationLossModel::SetNOscillators (uint8_t nOscillators) m_nOscillators = nOscillators; } -double -JakesPropagationLossModel::DoGetLoss (Ptr a, - Ptr b) const +double +JakesPropagationLossModel::DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const { PathsList::iterator i = m_paths.end (); while (i != m_paths.begin ()) @@ -227,12 +228,12 @@ JakesPropagationLossModel::DoGetLoss (Ptr a, { ps->receivers.erase (r); ps->receivers.push_back (pc); - return pc->GetLoss (); + return txPowerDbm + pc->GetLoss (); } } PathCoefficients *pc = new PathCoefficients (this, b, m_nRays, m_nOscillators); ps->receivers.push_back (pc); - return pc->GetLoss (); + return txPowerDbm + pc->GetLoss (); } } PathsSet *ps = new PathsSet; @@ -240,7 +241,7 @@ JakesPropagationLossModel::DoGetLoss (Ptr a, PathCoefficients *pc = new PathCoefficients (this, b, m_nRays, m_nOscillators); ps->receivers.push_back (pc); m_paths.push_back (ps); - return pc->GetLoss (); + return txPowerDbm + pc->GetLoss (); } } // namespace ns3 diff --git a/src/devices/wifi/jakes-propagation-loss-model.h b/src/devices/wifi/jakes-propagation-loss-model.h index 7b1c37830..1833953db 100644 --- a/src/devices/wifi/jakes-propagation-loss-model.h +++ b/src/devices/wifi/jakes-propagation-loss-model.h @@ -100,9 +100,9 @@ private: JakesPropagationLossModel (const JakesPropagationLossModel &o); JakesPropagationLossModel & operator = (const JakesPropagationLossModel &o); void DoConstruct (void); - virtual double DoGetLoss (Ptr a, - Ptr b) const; - + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; class PathCoefficients; struct ComplexNumber { diff --git a/src/devices/wifi/propagation-loss-model.cc b/src/devices/wifi/propagation-loss-model.cc index c486e2319..9205305d2 100644 --- a/src/devices/wifi/propagation-loss-model.cc +++ b/src/devices/wifi/propagation-loss-model.cc @@ -16,21 +16,22 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage + * Contributions: Timo Bingmann */ + #include "propagation-loss-model.h" #include "ns3/log.h" #include "ns3/mobility-model.h" #include "ns3/static-mobility-model.h" +#include "ns3/boolean.h" #include "ns3/double.h" -#include "ns3/pointer.h" #include NS_LOG_COMPONENT_DEFINE ("PropagationLossModel"); namespace ns3 { - -const double FriisPropagationLossModel::PI = 3.1415; +// ------------------------------------------------------------------------- // NS_OBJECT_ENSURE_REGISTERED (PropagationLossModel); @@ -57,17 +58,19 @@ PropagationLossModel::SetNext (Ptr next) } double -PropagationLossModel::GetLoss (Ptr a, - Ptr b) const +PropagationLossModel::CalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const { - double self = DoGetLoss (a, b); + double self = DoCalcRxPower (txPowerDbm, a, b); if (m_next != 0) { - self += m_next->GetLoss (a, b); + self = m_next->CalcRxPower (self, a, b); } return self; } +// ------------------------------------------------------------------------- // NS_OBJECT_ENSURE_REGISTERED (RandomPropagationLossModel); @@ -77,7 +80,7 @@ RandomPropagationLossModel::GetTypeId (void) static TypeId tid = TypeId ("ns3::RandomPropagationLossModel") .SetParent () .AddConstructor () - .AddAttribute ("Variable", "The random variable used to pick a loss everytime GetLoss is invoked.", + .AddAttribute ("Variable", "The random variable used to pick a loss everytime CalcRxPower is invoked.", RandomVariableValue (ConstantVariable (1.0)), MakeRandomVariableAccessor (&RandomPropagationLossModel::m_variable), MakeRandomVariableChecker ()) @@ -92,16 +95,21 @@ RandomPropagationLossModel::~RandomPropagationLossModel () {} double -RandomPropagationLossModel::DoGetLoss (Ptr a, - Ptr b) const +RandomPropagationLossModel::DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const { double rxc = -m_variable.GetValue (); NS_LOG_DEBUG ("attenuation coefficent="< a, - Ptr b) const +FriisPropagationLossModel::DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const { /* * Friis free space equation: @@ -201,30 +209,32 @@ FriisPropagationLossModel::DoGetLoss (Ptr a, * lambda: wavelength (m) * * Here, we ignore tx and rx gain and the input and output values - * are in dbm: + * are in dB or dBm: * * lambda^2 * rx = tx + 10 log10 (-------------------) * (4 * pi * d)^2 * L * - * rx: rx power (dbm) - * tx: tx power (dbm) + * rx: rx power (dB) + * tx: tx power (dB) * d: distance (m) - * L: system loss + * L: system loss (unit-less) * lambda: wavelength (m) */ double distance = a->GetDistanceFrom (b); if (distance <= m_minDistance) { - return 0.0; + return txPowerDbm; } double numerator = m_lambda * m_lambda; double denominator = 16 * PI * PI * distance * distance * m_systemLoss; double pr = 10 * log10 (numerator / denominator); NS_LOG_DEBUG ("distance="< ()) .AddAttribute ("ReferenceLoss", - "The reference loss at reference distance", + "The reference loss at reference distance (dB). (Default is Friis at 1m with 5.15 GHz)", DoubleValue (46.6777), MakeDoubleAccessor (&LogDistancePropagationLossModel::m_referenceLoss), MakeDoubleChecker ()) @@ -274,13 +284,14 @@ LogDistancePropagationLossModel::GetPathLossExponent (void) const } double -LogDistancePropagationLossModel::DoGetLoss (Ptr a, - Ptr b) const +LogDistancePropagationLossModel::DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const { double distance = a->GetDistanceFrom (b); if (distance <= m_referenceDistance) { - return 0.0; + return txPowerDbm; } /** * The formula is: @@ -289,18 +300,114 @@ LogDistancePropagationLossModel::DoGetLoss (Ptr a, * Pr0: rx power at reference distance d0 (W) * d0: reference distance: 1.0 (m) * d: distance (m) - * tx: tx power (db) - * rx: db + * tx: tx power (dB) + * rx: dB * * Which, in our case is: - * + * * rx = rx0(tx) - 10 * n * log (d/d0) */ double pathLossDb = 10 * m_exponent * log10 (distance / m_referenceDistance); double rxc = -m_referenceLoss - pathLossDb; NS_LOG_DEBUG ("distance="< () + .AddConstructor () + .AddAttribute ("Distance0", + "Beginning of the first (near) distance field", + DoubleValue (1.0), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_distance0), + MakeDoubleChecker ()) + .AddAttribute ("Distance1", + "Beginning of the second (middle) distance field.", + DoubleValue (200.0), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_distance1), + MakeDoubleChecker ()) + .AddAttribute ("Distance2", + "Beginning of the third (far) distance field.", + DoubleValue (500.0), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_distance2), + MakeDoubleChecker ()) + .AddAttribute ("Exponent0", + "The exponent for the first field.", + DoubleValue (1.9), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_exponent0), + MakeDoubleChecker ()) + .AddAttribute ("Exponent1", + "The exponent for the second field.", + DoubleValue (3.8), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_exponent1), + MakeDoubleChecker ()) + .AddAttribute ("Exponent2", + "The exponent for the third field.", + DoubleValue (3.8), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_exponent2), + MakeDoubleChecker ()) + .AddAttribute ("ReferenceLoss", + "The reference loss at distance d0 (dB). (Default is Friis at 1m with 5.15 GHz)", + DoubleValue (46.6777), + MakeDoubleAccessor (&ThreeLogDistancePropagationLossModel::m_referenceLoss), + MakeDoubleChecker ()) + ; + return tid; + +} + +ThreeLogDistancePropagationLossModel::ThreeLogDistancePropagationLossModel () +{ +} + +double +ThreeLogDistancePropagationLossModel::DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const +{ + double distance = a->GetDistanceFrom (b); + NS_ASSERT(distance >= 0); + + // See doxygen comments for the formula and explanation + + double pathLossDb; + + if (distance < m_distance0) + { + pathLossDb = 0; + } + else if (distance < m_distance1) + { + pathLossDb = m_referenceLoss + + 10 * m_exponent0 * log10(distance / m_distance0); + } + else if (distance < m_distance2) + { + pathLossDb = m_referenceLoss + + 10 * m_exponent0 * log10(m_distance1 / m_distance0) + + 10 * m_exponent1 * log10(distance / m_distance1); + } + else + { + pathLossDb = m_referenceLoss + + 10 * m_exponent0 * log10(m_distance1 / m_distance0) + + 10 * m_exponent1 * log10(m_distance2 / m_distance1) + + 10 * m_exponent2 * log10(distance / m_distance2); + } + + NS_LOG_DEBUG ("ThreeLogDistance distance=" << distance << "m, " << + "attenuation=" << pathLossDb << "dB"); + + return txPowerDbm - pathLossDb; +} + + } // namespace ns3 diff --git a/src/devices/wifi/propagation-loss-model.h b/src/devices/wifi/propagation-loss-model.h index 8bc5c74f3..3feb1ba18 100644 --- a/src/devices/wifi/propagation-loss-model.h +++ b/src/devices/wifi/propagation-loss-model.h @@ -16,7 +16,9 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage + * Contributions: Timo Bingmann */ + #ifndef PROPAGATION_LOSS_MODEL_H #define PROPAGATION_LOSS_MODEL_H @@ -30,8 +32,8 @@ class MobilityModel; /** * \brief Modelize the propagation loss through a transmission medium * - * Calculate the receive power (dbm) from a transmit power (dbm), - * and, a mobility model for the source and destination positions. + * Calculate the receive power (dbm) from a transmit power (dbm) + * and a mobility model for the source and destination positions. */ class PropagationLossModel : public Object { @@ -44,23 +46,26 @@ public: void SetNext (Ptr next); /** + * \param txPowerDbm current transmission power (in dBm) * \param a the mobility model of the source * \param b the mobility model of the destination - * \returns the attenuation coefficient (dB) + * \returns the reception power after adding/multiplying propagation loss (in dBm) */ - double GetLoss (Ptr a, - Ptr b) const; + double CalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; private: PropagationLossModel (const PropagationLossModel &o); PropagationLossModel &operator = (const PropagationLossModel &o); - virtual double DoGetLoss (Ptr a, - Ptr b) const = 0; + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const = 0; Ptr m_next; }; /** - * \brief The propagation loss is random + * \brief The propagation loss follows a random distribution. */ class RandomPropagationLossModel : public PropagationLossModel { @@ -73,8 +78,9 @@ public: private: RandomPropagationLossModel (const RandomPropagationLossModel &o); RandomPropagationLossModel & operator = (const RandomPropagationLossModel &o); - virtual double DoGetLoss (Ptr a, - Ptr b) const; + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; RandomVariable m_variable; }; @@ -163,8 +169,9 @@ public: private: FriisPropagationLossModel (const FriisPropagationLossModel &o); FriisPropagationLossModel & operator = (const FriisPropagationLossModel &o); - virtual double DoGetLoss (Ptr a, - Ptr b) const; + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; double DbmToW (double dbm) const; double DbmFromW (double w) const; @@ -213,8 +220,9 @@ public: private: LogDistancePropagationLossModel (const LogDistancePropagationLossModel &o); LogDistancePropagationLossModel & operator = (const LogDistancePropagationLossModel &o); - virtual double DoGetLoss (Ptr a, - Ptr b) const; + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; static Ptr CreateDefaultReference (void); double m_exponent; @@ -222,6 +230,72 @@ private: double m_referenceLoss; }; +/** + * \brief A log distance path loss propagation model with three distance + * fields. This model is the same as ns3::LogDistancePropagationLossModel + * except that it has three distance fields: near, middle and far with + * different exponents. + * + * Within each field the reception power is calculated using the log-distance + * propagation equation: + * \f[ L = L_0 + 10 \cdot n_0 log_{10}(\frac{d}{d_0})\f] + * Each field begins where the previous ends and all together form a continuous function. + * + * There are three valid distance fields: near, middle, far. Actually four: the + * first from 0 to the reference distance is invalid and returns txPowerDbm. + * + * \f[ \underbrace{0 \cdots\cdots}_{=0} \underbrace{d_0 \cdots\cdots}_{n_0} \underbrace{d_1 \cdots\cdots}_{n_1} \underbrace{d_2 \cdots\cdots}_{n_2} \infty \f] + * + * Complete formula for the path loss in dB: + * + * \f[\displaystyle L = +\begin{cases} +0 & d < d_0 \\ +L_0 + 10 \cdot n_0 \log_{10}(\frac{d}{d_0}) & d_0 \leq d < d_1 \\ +L_0 + 10 \cdot n_0 \log_{10}(\frac{d_1}{d_0}) + 10 \cdot n_1 \log_{10}(\frac{d}{d_1}) & d_1 \leq d < d_2 \\ +L_0 + 10 \cdot n_0 \log_{10}(\frac{d_1}{d_0}) + 10 \cdot n_1 \log_{10}(\frac{d_2}{d_1}) + 10 \cdot n_2 \log_{10}(\frac{d}{d_2})& d_2 \leq d +\end{cases}\f] + * + * where: + * - \f$ L \f$ : resulting path loss (dB) + * - \f$ d \f$ : distance (m) + * - \f$ d_0, d_1, d_2 \f$ : three distance fields (m) + * - \f$ n_0, n_1, n_2 \f$ : path loss distance exponent for each field (unitless) + * - \f$ L_0 \f$ : path loss at reference distance (dB) + * + * When the path loss is requested at a distance smaller than the reference + * distance \f$ d_0 \f$, the tx power (with no path loss) is returned. The + * reference distance defaults to 1m and reference loss defaults to + * ns3::FriisPropagationLossModel with 5.15 GHz and is thus \f$ L_0 \f$ = 46.67 dB. + */ + +class ThreeLogDistancePropagationLossModel : public PropagationLossModel +{ +public: + static TypeId GetTypeId (void); + ThreeLogDistancePropagationLossModel (); + + // Parameters are all accessible via attributes. + +private: + ThreeLogDistancePropagationLossModel (const ThreeLogDistancePropagationLossModel& o); + ThreeLogDistancePropagationLossModel& operator= (const ThreeLogDistancePropagationLossModel& o); + + virtual double DoCalcRxPower (double txPowerDbm, + Ptr a, + Ptr b) const; + + double m_distance0; + double m_distance1; + double m_distance2; + + double m_exponent0; + double m_exponent1; + double m_exponent2; + + double m_referenceLoss; +}; + } // namespace ns3 #endif /* PROPAGATION_LOSS_MODEL_H */ diff --git a/src/devices/wifi/yans-wifi-channel.cc b/src/devices/wifi/yans-wifi-channel.cc index 1c7022752..2bbc4559b 100644 --- a/src/devices/wifi/yans-wifi-channel.cc +++ b/src/devices/wifi/yans-wifi-channel.cc @@ -83,7 +83,7 @@ YansWifiChannel::Send (Ptr sender, Ptr packet, double { Ptr receiverMobility = (*i)->GetMobility ()->GetObject (); Time delay = m_delay->GetDelay (senderMobility, receiverMobility); - double rxPowerDbm = txPowerDbm + m_loss->GetLoss (senderMobility, receiverMobility); + double rxPowerDbm = m_loss->CalcRxPower (txPowerDbm, senderMobility, receiverMobility); NS_LOG_DEBUG ("propagation: txPower="< + * Original Author: Mathieu Lacage + * Enhancements: Timo Bingmann */ #include "gnuplot.h" #include "ns3/assert.h" #include +#include namespace ns3 { -GnuplotDataset::GnuplotDataset () - : m_title ("untitled"), - m_style (LINES), - m_errorBars (NONE) -{} +// --- GnuplotDataset::Data ------------------------------------------------ // -GnuplotDataset::GnuplotDataset (std::string title) - : m_title (title), - m_style (LINES), - m_errorBars (NONE) -{} -void -GnuplotDataset::SetStyle (enum Style style) +struct GnuplotDataset::Data +{ + // *** Data Variables *** + + unsigned int m_references; + + std::string m_title; + std::string m_extra; + + /** + * Initializes the reference counter to 1 and sets m_title and m_extra. + */ + Data(const std::string& title); + + /// Required. + virtual ~Data(); + + /** + * Returns "plot" or "splot". + */ + virtual std::string GetCommand() const = 0; + + /** + * Prints the plot description used as argument to (s)plot. Either the + * function expression or a datafile description. Should include m_title and + * m_extra in the output. + */ + virtual void PrintExpression(std::ostream &os) const = 0; + + /** + * Print the inline data file contents trailing the plot command. Empty for + * functions. + */ + virtual void PrintDatafile(std::ostream &os) const = 0; +}; + +GnuplotDataset::Data::Data(const std::string& title) + : m_references(1), + m_title(title), + m_extra(m_defaultExtra) { - m_style = style; } -void -GnuplotDataset::SetErrorBars (enum ErrorBars errorBars) + +GnuplotDataset::Data::~Data() { - m_errorBars = errorBars; } -void -GnuplotDataset::Add (double x, double y) + +// --- GnuplotDataset ------------------------------------------------------ // + +std::string GnuplotDataset::m_defaultExtra = ""; + +GnuplotDataset::GnuplotDataset (struct Data* data) + : m_data(data) { - NS_ASSERT (m_errorBars == NONE); - struct Data data; +} + +GnuplotDataset::GnuplotDataset (const GnuplotDataset& original) + : m_data(original.m_data) +{ + ++m_data->m_references; +} + +GnuplotDataset::~GnuplotDataset() +{ + if (--m_data->m_references == 0) + delete m_data; +} + +GnuplotDataset& GnuplotDataset::operator= (const GnuplotDataset& original) +{ + if (this != &original) + { + if (--m_data->m_references == 0) + delete m_data; + + m_data = original.m_data; + ++m_data->m_references; + } + return *this; +} + +void +GnuplotDataset::SetTitle (const std::string& title) +{ + m_data->m_title = title; +} + +void +GnuplotDataset::SetDefaultExtra (const std::string& extra) +{ + m_defaultExtra = extra; +} +void +GnuplotDataset::SetExtra (const std::string& extra) +{ + m_data->m_extra = extra; +} + +// --- Gnuplot2dDataset::Data2d -------------------------------------------- // + +struct Gnuplot2dDataset::Data2d : public GnuplotDataset::Data +{ + // *** Data Variables *** + + enum Style m_style; + enum ErrorBars m_errorBars; + + PointSet m_pointset; + + /** + * Initializes with the values from m_defaultStyle and m_defaultErrorBars. + */ + Data2d(const std::string& title); + + virtual std::string GetCommand() const; + virtual void PrintExpression(std::ostream &os) const; + virtual void PrintDatafile(std::ostream &os) const; +}; + +Gnuplot2dDataset::Data2d::Data2d(const std::string& title) + : Data(title), + m_style(m_defaultStyle), + m_errorBars(m_defaultErrorBars) +{ +} + +std::string +Gnuplot2dDataset::Data2d::GetCommand() const +{ + return "plot"; +} + +void +Gnuplot2dDataset::Data2d::PrintExpression(std::ostream &os) const +{ + os << "'-' "; + + if (m_title.size()) + os << " title '" << m_title << "'"; + + switch (m_style) { + case LINES: + os << " with lines"; + break; + case POINTS: + switch (m_errorBars) + { + case NONE: + os << " with points"; + break; + case X: + os << " with xerrorbars"; + break; + case Y: + os << " with yerrorbars"; + break; + case XY: + os << " with xyerrorbars"; + break; + } + break; + case LINES_POINTS: + switch (m_errorBars) + { + case NONE: + os << " with linespoints"; + break; + case X: + os << " with errorlines"; + break; + case Y: + os << " with yerrorlines"; + break; + case XY: + os << " with xyerrorlines"; + break; + } + break; + case DOTS: + os << " with dots"; + break; + case IMPULSES: + os << " with impulses"; + break; + case STEPS: + os << " with steps"; + break; + case FSTEPS: + os << " with fsteps"; + break; + case HISTEPS: + os << " with histeps"; + break; + } + + if (m_extra.size()) + os << " " << m_extra; +} + +void +Gnuplot2dDataset::Data2d::PrintDatafile(std::ostream &os) const +{ + for (PointSet::const_iterator i = m_pointset.begin (); + i != m_pointset.end (); ++i) + { + if (i->empty) { + os << std::endl; + continue; + } + + switch (m_errorBars) { + case NONE: + os << i->x << " " << i->y << std::endl; + break; + case X: + os << i->x << " " << i->y << " " << i->dx << std::endl; + break; + case Y: + os << i->x << " " << i->y << " " << i->dy << std::endl; + break; + case XY: + os << i->x << " " << i->y << " " << i->dx << " " << i->dy << std::endl; + break; + } + } + os << "e" << std::endl; +} + +// --- Gnuplot2dDataset ---------------------------------------------------- // + +enum Gnuplot2dDataset::Style Gnuplot2dDataset::m_defaultStyle = LINES; +enum Gnuplot2dDataset::ErrorBars Gnuplot2dDataset::m_defaultErrorBars = NONE; + +Gnuplot2dDataset::Gnuplot2dDataset (const std::string& title) + : GnuplotDataset( new Data2d(title) ) +{ +} + +void +Gnuplot2dDataset::SetDefaultStyle (enum Style style) +{ + m_defaultStyle = style; +} +void +Gnuplot2dDataset::SetStyle (enum Style style) +{ + reinterpret_cast(m_data)->m_style = style; +} + +void +Gnuplot2dDataset::SetDefaultErrorBars (enum ErrorBars errorBars) +{ + m_defaultErrorBars = errorBars; +} +void +Gnuplot2dDataset::SetErrorBars (enum ErrorBars errorBars) +{ + reinterpret_cast(m_data)->m_errorBars = errorBars; +} + +void +Gnuplot2dDataset::Add (double x, double y) +{ + NS_ASSERT (reinterpret_cast(m_data)->m_errorBars == NONE); + + struct Point data; + data.empty = false; data.x = x; data.y = y; data.dx = 0.0; data.dy = 0.0; - m_dataset.push_back (data); + reinterpret_cast(m_data)->m_pointset.push_back (data); } + void -GnuplotDataset::Add (double x, double y, double errorDelta) +Gnuplot2dDataset::Add (double x, double y, double errorDelta) { - NS_ASSERT (m_errorBars == X || m_errorBars == Y); - struct Data data; + NS_ASSERT ( reinterpret_cast(m_data)->m_errorBars == X || + reinterpret_cast(m_data)->m_errorBars == Y ); + + struct Point data; + data.empty = false; data.x = x; data.y = y; data.dx = errorDelta; data.dy = errorDelta; - m_dataset.push_back (data); -} - -Gnuplot::Gnuplot (std::string pngFilename) - : m_pngFilename (pngFilename) -{} - -Gnuplot::~Gnuplot () -{ - for (Datasets::const_iterator i = m_datasets.begin (); i != m_datasets.end (); i++) - { - delete *i; - } - m_datasets.clear (); + reinterpret_cast(m_data)->m_pointset.push_back (data); } void -Gnuplot::SetLegend (std::string xLegend, std::string yLegend) +Gnuplot2dDataset::Add (double x, double y, double minY, double maxY) +{ + NS_ASSERT ( reinterpret_cast(m_data)->m_errorBars == X || + reinterpret_cast(m_data)->m_errorBars == Y ); + + struct Point data; + data.empty = false; + data.x = x; + data.y = y; + data.dx = minY; + data.dy = maxY; + reinterpret_cast(m_data)->m_pointset.push_back (data); +} + +void +Gnuplot2dDataset::AddEmptyLine() +{ + struct Point data; + data.empty = true; + reinterpret_cast(m_data)->m_pointset.push_back (data); +} + +// --- Gnuplot2dFunction::Function2d --------------------------------------- // + +struct Gnuplot2dFunction::Function2d : public GnuplotDataset::Data +{ + // *** Data Variables *** + + std::string m_function; + + /** + * Initializes with the function and title. + */ + Function2d(const std::string& title, const std::string& function); + + virtual std::string GetCommand() const; + virtual void PrintExpression(std::ostream &os) const; + virtual void PrintDatafile(std::ostream &os) const; +}; + +Gnuplot2dFunction::Function2d::Function2d(const std::string& title, const std::string& function) + : Data(title), + m_function(function) +{ +} + +std::string +Gnuplot2dFunction::Function2d::GetCommand() const +{ + return "plot"; +} + +void +Gnuplot2dFunction::Function2d::PrintExpression(std::ostream &os) const +{ + os << m_function; + + if (m_title.size()) + os << " title '" << m_title << "'"; + + if (m_extra.size()) + os << " " << m_extra; +} + +void +Gnuplot2dFunction::Function2d::PrintDatafile(std::ostream &os) const +{ +} + +// --- Gnuplot2dFunction --------------------------------------------------- // + +Gnuplot2dFunction::Gnuplot2dFunction (const std::string& title, const std::string& function) + : GnuplotDataset( new Function2d(title, function) ) +{ +} + +void +Gnuplot2dFunction::SetFunction (const std::string& function) +{ + reinterpret_cast(m_data)->m_function = function; +} + +// --- Gnuplot3dDataset::Data3d -------------------------------------------- // + +struct Gnuplot3dDataset::Data3d : public GnuplotDataset::Data +{ + // *** Data Variables *** + + std::string m_style; + + PointSet m_pointset; + + /** + * Initializes with value from m_defaultStyle. + */ + Data3d(const std::string& title); + + virtual std::string GetCommand() const; + virtual void PrintExpression(std::ostream &os) const; + virtual void PrintDatafile(std::ostream &os) const; +}; + +Gnuplot3dDataset::Data3d::Data3d(const std::string& title) + : Data(title), + m_style(m_defaultStyle) +{ +} + +std::string +Gnuplot3dDataset::Data3d::GetCommand() const +{ + return "splot"; +} + +void +Gnuplot3dDataset::Data3d::PrintExpression(std::ostream &os) const +{ + os << "'-' "; + + if (m_style.size()) + os << " " << m_style; + + if (m_title.size()) + os << " title '" << m_title << "'"; + + if (m_extra.size()) + os << " " << m_extra; +} + +void +Gnuplot3dDataset::Data3d::PrintDatafile(std::ostream &os) const +{ + for (PointSet::const_iterator i = m_pointset.begin (); + i != m_pointset.end (); ++i) + { + if (i->empty) { + os << std::endl; + continue; + } + + os << i->x << " " << i->y << " " << i->z << std::endl; + } + os << "e" << std::endl; +} + +// --- Gnuplot3dDataset ---------------------------------------------------- // + +std::string Gnuplot3dDataset::m_defaultStyle = ""; + +Gnuplot3dDataset::Gnuplot3dDataset (const std::string& title) + : GnuplotDataset( new Data3d(title) ) +{ +} + +void +Gnuplot3dDataset::SetDefaultStyle (const std::string& style) +{ + m_defaultStyle = style; +} +void +Gnuplot3dDataset::SetStyle (const std::string& style) +{ + reinterpret_cast(m_data)->m_style = style; +} + +void +Gnuplot3dDataset::Add (double x, double y, double z) +{ + struct Point data; + data.empty = false; + data.x = x; + data.y = y; + data.z = z; + reinterpret_cast(m_data)->m_pointset.push_back (data); +} + +void +Gnuplot3dDataset::AddEmptyLine() +{ + struct Point data; + data.empty = true; + reinterpret_cast(m_data)->m_pointset.push_back (data); +} + +// --- Gnuplot3dFunction::Function3d --------------------------------------- // + +struct Gnuplot3dFunction::Function3d : public GnuplotDataset::Data +{ + // *** Data Variables *** + + std::string m_function; + + /** + * Initializes with the function and title. + */ + Function3d(const std::string& title, const std::string& function); + + virtual std::string GetCommand() const; + virtual void PrintExpression(std::ostream &os) const; + virtual void PrintDatafile(std::ostream &os) const; +}; + +Gnuplot3dFunction::Function3d::Function3d(const std::string& title, const std::string& function) + : Data(title), + m_function(function) +{ +} + +std::string +Gnuplot3dFunction::Function3d::GetCommand() const +{ + return "splot"; +} + +void +Gnuplot3dFunction::Function3d::PrintExpression(std::ostream &os) const +{ + os << m_function; + + if (m_title.size()) + os << " title '" << m_title << "'"; + + if (m_extra.size()) + os << " " << m_extra; +} + +void +Gnuplot3dFunction::Function3d::PrintDatafile(std::ostream &os) const +{ +} + +// --- Gnuplot3dFunction --------------------------------------------------- // + +Gnuplot3dFunction::Gnuplot3dFunction (const std::string& title, const std::string& function) + : GnuplotDataset( new Function3d(title, function) ) +{ +} + +void +Gnuplot3dFunction::SetFunction (const std::string& function) +{ + reinterpret_cast(m_data)->m_function = function; +} + +// ------------------------------------------------------------------------- // + +Gnuplot::Gnuplot (const std::string& outputFilename, const std::string& title) + : m_outputFilename(outputFilename), + m_terminal( DetectTerminal(outputFilename) ), + m_title(title) +{ +} + +std::string Gnuplot::DetectTerminal (const std::string& filename) +{ + std::string::size_type dotpos = filename.rfind('.'); + if (dotpos == std::string::npos) return ""; + + if (filename.substr(dotpos) == ".png") { + return "png"; + } + else if (filename.substr(dotpos) == ".pdf") { + return "pdf"; + } + + return ""; +} + +void +Gnuplot::SetTerminal (const std::string& terminal) +{ + m_terminal = terminal; +} + +void +Gnuplot::SetTitle (const std::string& title) +{ + m_title = title; +} + +void +Gnuplot::SetLegend (const std::string& xLegend, const std::string& yLegend) { m_xLegend = xLegend; m_yLegend = yLegend; } -void -Gnuplot::AddDataset (const GnuplotDataset &dataset) +void +Gnuplot::SetExtra (const std::string& extra) { - m_datasets.push_back (new GnuplotDataset (dataset)); + m_extra = extra; +} + +void +Gnuplot::AppendExtra (const std::string& extra) +{ + m_extra += "\n"; + m_extra += extra; } void -Gnuplot::GenerateOutput (std::ostream &os) +Gnuplot::AddDataset (const GnuplotDataset& dataset) { - os << "set terminal png" << std::endl; - os << "set output '" << m_pngFilename << "'" << std::endl; - os << "set xlabel '" << m_xLegend << "'" << std::endl; - os << "set ylabel '" << m_yLegend << "'" << std::endl; - os << "plot "; + m_datasets.push_back (dataset); +} + +void +Gnuplot::GenerateOutput (std::ostream &os) const +{ + if (m_terminal.size()) + os << "set terminal " << m_terminal << std::endl; + + if (m_outputFilename.size()) + os << "set output '" << m_outputFilename << "'" << std::endl; + + if (m_title.size()) + os << "set title '" << m_title << "'" << std::endl; + + if (m_xLegend.size()) + os << "set xlabel '" << m_xLegend << "'" << std::endl; + + if (m_yLegend.size()) + os << "set ylabel '" << m_yLegend << "'" << std::endl; + + if (m_extra.size()) + os << m_extra << std::endl; + + if (m_datasets.empty()) + return; + + // Determine the GetCommand() values of all datasets included. Check that all + // are equal and print the command. + + std::string command = m_datasets.begin()->m_data->GetCommand(); + + for (Datasets::const_iterator i = m_datasets.begin () + 1; + i != m_datasets.end (); ++i) + { + NS_ASSERT_MSG(command == i->m_data->GetCommand(), + "Cannot mix 'plot' and 'splot' GnuplotDatasets."); + } + + os << command << " "; + + // Print all dataset expressions + for (Datasets::const_iterator i = m_datasets.begin (); i != m_datasets.end ();) { - os << "'-' title '" << (*i)->m_title << "'"; - switch ((*i)->m_style) { - case GnuplotDataset::LINES: - os << " with lines"; - break; - case GnuplotDataset::POINTS: - switch ((*i)->m_errorBars) - { - case GnuplotDataset::NONE: - os << " with points"; - break; - case GnuplotDataset::X: - os << " with xerrorbars"; - break; - case GnuplotDataset::Y: - os << " with yerrorbars"; - break; - case GnuplotDataset::XY: - os << " with xyerrorbars"; - break; - } - break; - case GnuplotDataset::LINES_POINTS: - switch ((*i)->m_errorBars) - { - case GnuplotDataset::NONE: - os << " with linespoints"; - break; - case GnuplotDataset::X: - os << " with xerrorlines"; - break; - case GnuplotDataset::Y: - os << " with yerrorlines"; - break; - case GnuplotDataset::XY: - os << " with xyerrorlines"; - break; - } - break; - case GnuplotDataset::DOTS: - os << " with dots"; - break; - case GnuplotDataset::IMPULSES: - os << " with impulses"; - break; - case GnuplotDataset::STEPS: - os << " with steps"; - break; - case GnuplotDataset::FSTEPS: - os << " with fsteps"; - break; - case GnuplotDataset::HISTEPS: - os << " with histeps"; - break; - } + i->m_data->PrintExpression(os); + i++; + if (i != m_datasets.end ()) { os << ", "; } } os << std::endl; + + // followed by the inline datafile. + for (Datasets::const_iterator i = m_datasets.begin (); i != m_datasets.end (); i++) { - for (GnuplotDataset::Dataset::const_iterator j = (*i)->m_dataset.begin (); - j != (*i)->m_dataset.end (); j++) - { - switch ((*i)->m_errorBars) { - case GnuplotDataset::NONE: - os << j->x << " " << j->y << std::endl; - break; - case GnuplotDataset::X: - os << j->x << " " << j->y << " " << j->dx << std::endl; - break; - case GnuplotDataset::Y: - os << j->x << " " << j->y << " " << j->dy << std::endl; - break; - case GnuplotDataset::XY: - os << j->x << " " << j->y << " " << j->dx << " " << j->dy << std::endl; - break; - } - } - os << "e" << std::endl; + i->m_data->PrintDatafile(os); } } +// ------------------------------------------------------------------------- // + +GnuplotCollection::GnuplotCollection (const std::string& outputFilename) + : m_outputFilename(outputFilename), + m_terminal( Gnuplot::DetectTerminal(outputFilename) ) +{ +} + +void +GnuplotCollection::SetTerminal (const std::string& terminal) +{ + m_terminal = terminal; +} + +void +GnuplotCollection::AddPlot (const Gnuplot& plot) +{ + m_plots.push_back (plot); +} + +Gnuplot& +GnuplotCollection::GetPlot(unsigned int id) +{ + if (id >= m_plots.size()) + throw(std::range_error("Gnuplot id is out of range")); + else + return m_plots[id]; +} + +void +GnuplotCollection::GenerateOutput (std::ostream &os) const +{ + if (m_terminal.size()) + os << "set terminal " << m_terminal << std::endl; + + if (m_outputFilename.size()) + os << "set output '" << m_outputFilename << "'" << std::endl; + + for (Plots::const_iterator i = m_plots.begin (); i != m_plots.end (); ++i) + { + i->GenerateOutput (os); + } +} + +// ------------------------------------------------------------------------- // + } // namespace ns3 diff --git a/src/contrib/gnuplot.h b/src/contrib/gnuplot.h index ff1b2b7fb..5e8329e8e 100644 --- a/src/contrib/gnuplot.h +++ b/src/contrib/gnuplot.h @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2007 INRIA + * Copyright (c) 2007 INRIA, 2008 Timo Bingmann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as @@ -15,7 +15,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Author: Mathieu Lacage + * Original Author: Mathieu Lacage + * Enhancements: Timo Bingmann */ #ifndef GNUPLOT_H #define GNUPLOT_H @@ -27,10 +28,82 @@ namespace ns3 { /** - * \brief store a dataset to be used by ns3::Gnuplot + * \brief Abstract class to store a plot line to be used by ns3::Gnuplot. + * + * This class contains a reference counted data object in m_data. The data + * object contains different structs derived from struct Data by subclasses. */ class GnuplotDataset { +public: + + /** + * Reference-counting copy constructor. + */ + GnuplotDataset (const GnuplotDataset& original); + + /** + * Reference-counting destructor. + */ + ~GnuplotDataset(); + + /** + * Reference-counting assignment operator. + */ + GnuplotDataset& operator= (const GnuplotDataset& original); + + /** + * \brief Change line title. + * \param title the new title string to use for this dataset. + */ + void SetTitle (const std::string& title); + + /** + * \brief Change extra formatting style parameters for newly created objects. + * \param extra extra formatting + */ + static void SetDefaultExtra (const std::string& extra); + + /** + * \brief Add extra formatting parameters to this dataset. + * \param extra extra formatting + */ + void SetExtra (const std::string& extra); + +protected: + + /// Friend because it accesses m_data and it's virtual functions directly in + /// GenerateOutput(). + friend class Gnuplot; + + /** + * \brief Extra gnuplot parameters set on every newly created dataset. + */ + static std::string m_defaultExtra; + + /** + * \brief Derived classes subclass this struct and add their own data fields. + */ + struct Data; + + /** + * Called by constructors of derived classes. + * \param data the reference counted data object representing this dataset. + */ + GnuplotDataset (struct Data* data); + + /** + * Reference counted data object. + */ + struct Data* m_data; +}; + +/** + * \brief Class to represent a 2D points plot. Set the line or points style + * using SetStyle() and set points using Add(). + */ +class Gnuplot2dDataset : public GnuplotDataset +{ public: /** * The plotting style to use for this dataset. @@ -45,6 +118,7 @@ public: FSTEPS, HISTEPS, }; + /** * Whether errorbars should be used for this dataset. */ @@ -55,21 +129,31 @@ public: XY }; - /** - * Create an empty dataset without any title. - */ - GnuplotDataset (); /** * \param title the title to be associated to this dataset. * * Create an empty dataset. Usually, the dataset's title is * displayed in the legend box. */ - GnuplotDataset (std::string title); + Gnuplot2dDataset (const std::string& title = "Untitled"); + + /** + * Change default style for all newly created objects. + * \param style the style of plotting to use for newly created datasets. + */ + static void SetDefaultStyle (enum Style style); + /** * \param style the style of plotting to use for this dataset. */ void SetStyle (enum Style style); + + /** + * Change default errorbars style for all newly created objects. + * \param errorBars the style of errorbars to use for newly created datasets. + */ + static void SetDefaultErrorBars (enum ErrorBars errorBars); + /** * \param errorBars the style of errorbars to display. * @@ -79,6 +163,7 @@ public: * method. */ void SetErrorBars (enum ErrorBars errorBars); + /** * \param x x coord to new data point * \param y y coord to new data point @@ -86,27 +171,164 @@ public: * Use this method with error bar style NONE. */ void Add (double x, double y); + /** * \param x x coord to new data point * \param y y coord to new data point - * \param errorDelta + * \param errorDelta data point error range. * * Use this method with error bar style X or Y. */ void Add (double x, double y, double errorDelta); + + /** + * \param x x coord to new data point + * \param y y coord to new data point + * \param minY minimum error data point + * \param maxY maximum error data point + * + * Use this method with error bar style X or Y. + */ + void Add (double x, double y, double minY, double maxY); + + /** + * Add an empty line in the data output sequence. Empty lines in the plot + * data break continuous lines and do other things in the output. + */ + void AddEmptyLine(); + private: - friend class Gnuplot; - struct Data { + + struct Point { + bool empty; double x; double y; double dx; double dy; }; - typedef std::vector Dataset; - Dataset m_dataset; - std::string m_title; - enum Style m_style; - enum ErrorBars m_errorBars; + + typedef std::vector PointSet; + + static enum Style m_defaultStyle; + static enum ErrorBars m_defaultErrorBars; + + /// Forward declaration of the internal data class. + struct Data2d; +}; + +/** + * \brief Class to represent a 2D function expression plot. + * + * Since the function expression is not escaped, styles and extras could just + * as well be included in the expression string. + */ +class Gnuplot2dFunction : public GnuplotDataset +{ +public: + /** + * \param title the title to be associated to this dataset. + * \param function function to plot + * + * Create an function dataset. Usually, the dataset's title is displayed in + * the legend box. + */ + Gnuplot2dFunction (const std::string& title = "Untitled", const std::string& function = ""); + + /** + * \param function new function string to set + */ + void SetFunction (const std::string& function); + +private: + + /// Forward declaration of the internal data class. + struct Function2d; +}; + +/** + * \brief Class to represent a 3D points plot. Set the line or points style + * using SetStyle() and set points using Add(). + */ +class Gnuplot3dDataset : public GnuplotDataset +{ +public: + /** + * \param title the title to be associated to this dataset. + * + * Create an empty dataset. Usually, the dataset's title is + * displayed in the legend box. + */ + Gnuplot3dDataset (const std::string& title = "Untitled"); + + /** + * Change default style for all newly created objects. + * \param style the style of plotting to use for newly created datasets. + */ + static void SetDefaultStyle (const std::string& style); + + /** + * \param style the style of plotting to use for this dataset. + */ + void SetStyle (const std::string& style); + + /** + * \param x x coord to new data point + * \param y y coord to new data point + * \param z z coord to new data point + * + * Use this method to add a new 3D point + */ + void Add (double x, double y, double z); + + /** + * Add an empty line in the data output sequence. Empty lines in the plot + * data break continuous lines and do other things in the output. + */ + void AddEmptyLine(); + +private: + + struct Point { + bool empty; + double x, y, z; + }; + + typedef std::vector PointSet; + + static std::string m_defaultStyle; + + /// Forward declaration of the internal data class. + struct Data3d; +}; + +/** + * \brief Class to represent a 3D function expression plot. + * + * Since the function expression is not escaped, styles and extras could just as + * well be included in the expression string. The only difference to + * Gnuplot2dFunction is the splot command string. + */ +class Gnuplot3dFunction : public GnuplotDataset +{ +public: + /** + * \param title the title to be associated to this dataset. + * \param function function to plot + * + * Create an function dataset. Usually, the dataset's title is displayed in + * the legend box. + */ + Gnuplot3dFunction (const std::string& title = "Untitled", const std::string& function = ""); + + /** + * \param function new function string to set + */ + void SetFunction (const std::string& function); + +private: + + /// Forward declaration of the internal data class. + struct Function3d; }; /** @@ -120,35 +342,117 @@ class Gnuplot { public: /** - * \param pngFilename the name of the file where the png rendering of the + * \param outputFilename the name of the file where the rendering of the * graph will be generated if you feed the command stream output by * Gnuplot::GenerateOutput to the gnuplot program. + * \param title title line of the plot page */ - Gnuplot (std::string pngFilename); - ~Gnuplot (); + Gnuplot (const std::string& outputFilename="", const std::string& title = ""); + + /** + * Crude attempt to auto-detect the correct terminal setting by inspecting + * the filename's extension. + * \param filename output file name + */ + static std::string DetectTerminal(const std::string& filename); + + /** + * \param terminal terminal setting string for output. The default terminal + * string is "png" + */ + void SetTerminal (const std::string& terminal); + + /** + * \param title set new plot title string to use for this plot. + */ + void SetTitle (const std::string& title); /** * \param xLegend the legend for the x horizontal axis * \param yLegend the legend for the y vertical axis */ - void SetLegend (std::string xLegend, std::string yLegend); + void SetLegend (const std::string& xLegend, const std::string& yLegend); + + /** + * \param extra set extra gnuplot directive for output. + */ + void SetExtra (const std::string& extra); + + /** + * \param extra append extra gnuplot directive for output. + */ + void AppendExtra (const std::string& extra); /** * \param dataset add a dataset to the graph to be plotted. */ - void AddDataset (const GnuplotDataset &dataset); + void AddDataset (const GnuplotDataset& dataset); /** - * \param os the output stream on which the relevant gnuplot - * commands should be generated. + * \param os the output stream on which the relevant gnuplot commands should + * be generated. Including output file and terminal headers. */ - void GenerateOutput (std::ostream &os); + void GenerateOutput (std::ostream &os) const; + private: - typedef std::vector Datasets; + typedef std::vector Datasets; + + std::string m_outputFilename; + std::string m_terminal; + Datasets m_datasets; + + std::string m_title; std::string m_xLegend; std::string m_yLegend; - std::string m_pngFilename; + std::string m_extra; +}; + +/** + * \brief a simple class to group together multiple gnuplots into one file, + * e.g. for PDF multi-page output terminals. + */ +class GnuplotCollection +{ +public: + /** + * \param outputFilename the name of the file where the rendering of the + * graph will be generated if you feed the command stream output by + * GnuplotCollection::GenerateOutput to the gnuplot program. + */ + GnuplotCollection (const std::string& outputFilename); + + /** + * \param terminal terminal setting string for output. The default terminal + * string is guessed from the output filename's extension. + */ + void SetTerminal (const std::string& terminal); + + /** + * \param plot add a plot to the collection to be plotted. + */ + void AddPlot (const Gnuplot& plot); + + /** + * Return a pointer to one of the added plots. + * \param id index of plot to return + * \return reference to plot, throws std::range_error if it does not exist. + */ + Gnuplot& GetPlot(unsigned int id); + + /** + * \param os the output stream on which the relevant gnuplot commands should + * be generated. + */ + void GenerateOutput (std::ostream &os) const; + +private: + typedef std::vector Plots; + + std::string m_outputFilename; + std::string m_terminal; + + Plots m_plots; }; } // namespace ns3 From f0c50a6466331ef010e83346f97aedc50ddc4aad Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 09:54:14 +0100 Subject: [PATCH 28/29] rescan python --- bindings/python/ns3_module_contrib.py | 202 ++++++++++++++++++++++---- 1 file changed, 173 insertions(+), 29 deletions(-) diff --git a/bindings/python/ns3_module_contrib.py b/bindings/python/ns3_module_contrib.py index 610813da8..e9bcfc194 100644 --- a/bindings/python/ns3_module_contrib.py +++ b/bindings/python/ns3_module_contrib.py @@ -9,18 +9,28 @@ def register_types(module): module.add_class('EventGarbageCollector') ## gnuplot.h: ns3::Gnuplot [class] module.add_class('Gnuplot') + ## gnuplot.h: ns3::GnuplotCollection [class] + module.add_class('GnuplotCollection') ## gnuplot.h: ns3::GnuplotDataset [class] module.add_class('GnuplotDataset') - ## gnuplot.h: ns3::GnuplotDataset::Style [enumeration] - module.add_enum('Style', ['LINES', 'POINTS', 'LINES_POINTS', 'DOTS', 'IMPULSES', 'STEPS', 'FSTEPS', 'HISTEPS'], outer_class=root_module['ns3::GnuplotDataset']) - ## gnuplot.h: ns3::GnuplotDataset::ErrorBars [enumeration] - module.add_enum('ErrorBars', ['NONE', 'X', 'Y', 'XY'], outer_class=root_module['ns3::GnuplotDataset']) ## gtk-config-store.h: ns3::GtkConfigStore [class] module.add_class('GtkConfigStore') ## config-store.h: ns3::ConfigStore [class] module.add_class('ConfigStore', parent=root_module['ns3::ObjectBase']) ## flow-id-tag.h: ns3::FlowIdTag [class] module.add_class('FlowIdTag', parent=root_module['ns3::Tag']) + ## gnuplot.h: ns3::Gnuplot2dDataset [class] + module.add_class('Gnuplot2dDataset', parent=root_module['ns3::GnuplotDataset']) + ## gnuplot.h: ns3::Gnuplot2dDataset::Style [enumeration] + module.add_enum('Style', ['LINES', 'POINTS', 'LINES_POINTS', 'DOTS', 'IMPULSES', 'STEPS', 'FSTEPS', 'HISTEPS'], outer_class=root_module['ns3::Gnuplot2dDataset']) + ## gnuplot.h: ns3::Gnuplot2dDataset::ErrorBars [enumeration] + module.add_enum('ErrorBars', ['NONE', 'X', 'Y', 'XY'], outer_class=root_module['ns3::Gnuplot2dDataset']) + ## gnuplot.h: ns3::Gnuplot2dFunction [class] + module.add_class('Gnuplot2dFunction', parent=root_module['ns3::GnuplotDataset']) + ## gnuplot.h: ns3::Gnuplot3dDataset [class] + module.add_class('Gnuplot3dDataset', parent=root_module['ns3::GnuplotDataset']) + ## gnuplot.h: ns3::Gnuplot3dFunction [class] + module.add_class('Gnuplot3dFunction', parent=root_module['ns3::GnuplotDataset']) ## Register a nested module for the namespace Config @@ -66,10 +76,15 @@ def register_methods(root_module): register_Ns3DelayJitterEstimation_methods(root_module, root_module['ns3::DelayJitterEstimation']) register_Ns3EventGarbageCollector_methods(root_module, root_module['ns3::EventGarbageCollector']) register_Ns3Gnuplot_methods(root_module, root_module['ns3::Gnuplot']) + register_Ns3GnuplotCollection_methods(root_module, root_module['ns3::GnuplotCollection']) register_Ns3GnuplotDataset_methods(root_module, root_module['ns3::GnuplotDataset']) register_Ns3GtkConfigStore_methods(root_module, root_module['ns3::GtkConfigStore']) register_Ns3ConfigStore_methods(root_module, root_module['ns3::ConfigStore']) register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag']) + register_Ns3Gnuplot2dDataset_methods(root_module, root_module['ns3::Gnuplot2dDataset']) + register_Ns3Gnuplot2dFunction_methods(root_module, root_module['ns3::Gnuplot2dFunction']) + register_Ns3Gnuplot3dDataset_methods(root_module, root_module['ns3::Gnuplot3dDataset']) + register_Ns3Gnuplot3dFunction_methods(root_module, root_module['ns3::Gnuplot3dFunction']) return def register_Ns3DelayJitterEstimation_methods(root_module, cls): @@ -112,45 +127,87 @@ def register_Ns3EventGarbageCollector_methods(root_module, cls): def register_Ns3Gnuplot_methods(root_module, cls): ## gnuplot.h: ns3::Gnuplot::Gnuplot(ns3::Gnuplot const & arg0) [copy constructor] cls.add_constructor([param('ns3::Gnuplot const &', 'arg0')]) - ## gnuplot.h: ns3::Gnuplot::Gnuplot(std::string pngFilename) [constructor] - cls.add_constructor([param('std::string', 'pngFilename')]) - ## gnuplot.h: void ns3::Gnuplot::SetLegend(std::string xLegend, std::string yLegend) [member function] + ## gnuplot.h: ns3::Gnuplot::Gnuplot(std::string const & outputFilename="", std::string const & title="") [constructor] + cls.add_constructor([param('std::string const &', 'outputFilename', default_value='""'), param('std::string const &', 'title', default_value='""')]) + ## gnuplot.h: static std::string ns3::Gnuplot::DetectTerminal(std::string const & filename) [member function] + cls.add_method('DetectTerminal', + 'std::string', + [param('std::string const &', 'filename')], + is_static=True) + ## gnuplot.h: void ns3::Gnuplot::SetTerminal(std::string const & terminal) [member function] + cls.add_method('SetTerminal', + 'void', + [param('std::string const &', 'terminal')]) + ## gnuplot.h: void ns3::Gnuplot::SetTitle(std::string const & title) [member function] + cls.add_method('SetTitle', + 'void', + [param('std::string const &', 'title')]) + ## gnuplot.h: void ns3::Gnuplot::SetLegend(std::string const & xLegend, std::string const & yLegend) [member function] cls.add_method('SetLegend', 'void', - [param('std::string', 'xLegend'), param('std::string', 'yLegend')]) + [param('std::string const &', 'xLegend'), param('std::string const &', 'yLegend')]) + ## gnuplot.h: void ns3::Gnuplot::SetExtra(std::string const & extra) [member function] + cls.add_method('SetExtra', + 'void', + [param('std::string const &', 'extra')]) + ## gnuplot.h: void ns3::Gnuplot::AppendExtra(std::string const & extra) [member function] + cls.add_method('AppendExtra', + 'void', + [param('std::string const &', 'extra')]) ## gnuplot.h: void ns3::Gnuplot::AddDataset(ns3::GnuplotDataset const & dataset) [member function] cls.add_method('AddDataset', 'void', [param('ns3::GnuplotDataset const &', 'dataset')]) - ## gnuplot.h: void ns3::Gnuplot::GenerateOutput(std::ostream & os) [member function] + ## gnuplot.h: void ns3::Gnuplot::GenerateOutput(std::ostream & os) const [member function] cls.add_method('GenerateOutput', 'void', - [param('std::ostream &', 'os')]) + [param('std::ostream &', 'os')], + is_const=True) + return + +def register_Ns3GnuplotCollection_methods(root_module, cls): + ## gnuplot.h: ns3::GnuplotCollection::GnuplotCollection(ns3::GnuplotCollection const & arg0) [copy constructor] + cls.add_constructor([param('ns3::GnuplotCollection const &', 'arg0')]) + ## gnuplot.h: ns3::GnuplotCollection::GnuplotCollection(std::string const & outputFilename) [constructor] + cls.add_constructor([param('std::string const &', 'outputFilename')]) + ## gnuplot.h: void ns3::GnuplotCollection::SetTerminal(std::string const & terminal) [member function] + cls.add_method('SetTerminal', + 'void', + [param('std::string const &', 'terminal')]) + ## gnuplot.h: void ns3::GnuplotCollection::AddPlot(ns3::Gnuplot const & plot) [member function] + cls.add_method('AddPlot', + 'void', + [param('ns3::Gnuplot const &', 'plot')]) + ## gnuplot.h: ns3::Gnuplot & ns3::GnuplotCollection::GetPlot(unsigned int id) [member function] + cls.add_method('GetPlot', + 'ns3::Gnuplot &', + [param('unsigned int', 'id')]) + ## gnuplot.h: void ns3::GnuplotCollection::GenerateOutput(std::ostream & os) const [member function] + cls.add_method('GenerateOutput', + 'void', + [param('std::ostream &', 'os')], + is_const=True) return def register_Ns3GnuplotDataset_methods(root_module, cls): - ## gnuplot.h: ns3::GnuplotDataset::GnuplotDataset(ns3::GnuplotDataset const & arg0) [copy constructor] - cls.add_constructor([param('ns3::GnuplotDataset const &', 'arg0')]) - ## gnuplot.h: ns3::GnuplotDataset::GnuplotDataset() [constructor] - cls.add_constructor([]) - ## gnuplot.h: ns3::GnuplotDataset::GnuplotDataset(std::string title) [constructor] - cls.add_constructor([param('std::string', 'title')]) - ## gnuplot.h: void ns3::GnuplotDataset::SetStyle(ns3::GnuplotDataset::Style style) [member function] - cls.add_method('SetStyle', + ## gnuplot.h: ns3::GnuplotDataset::GnuplotDataset(ns3::GnuplotDataset const & original) [copy constructor] + cls.add_constructor([param('ns3::GnuplotDataset const &', 'original')]) + ## gnuplot.h: void ns3::GnuplotDataset::SetTitle(std::string const & title) [member function] + cls.add_method('SetTitle', 'void', - [param('ns3::GnuplotDataset::Style', 'style')]) - ## gnuplot.h: void ns3::GnuplotDataset::SetErrorBars(ns3::GnuplotDataset::ErrorBars errorBars) [member function] - cls.add_method('SetErrorBars', + [param('std::string const &', 'title')]) + ## gnuplot.h: static void ns3::GnuplotDataset::SetDefaultExtra(std::string const & extra) [member function] + cls.add_method('SetDefaultExtra', 'void', - [param('ns3::GnuplotDataset::ErrorBars', 'errorBars')]) - ## gnuplot.h: void ns3::GnuplotDataset::Add(double x, double y) [member function] - cls.add_method('Add', + [param('std::string const &', 'extra')], + is_static=True) + ## gnuplot.h: void ns3::GnuplotDataset::SetExtra(std::string const & extra) [member function] + cls.add_method('SetExtra', 'void', - [param('double', 'x'), param('double', 'y')]) - ## gnuplot.h: void ns3::GnuplotDataset::Add(double x, double y, double errorDelta) [member function] - cls.add_method('Add', - 'void', - [param('double', 'x'), param('double', 'y'), param('double', 'errorDelta')]) + [param('std::string const &', 'extra')]) + ## gnuplot.h: ns3::GnuplotDataset::GnuplotDataset(ns3::GnuplotDataset::Data * data) [constructor] + cls.add_constructor([param('ns3::GnuplotDataset::Data *', 'data')], + visibility='protected') return def register_Ns3GtkConfigStore_methods(root_module, cls): @@ -238,6 +295,93 @@ def register_Ns3FlowIdTag_methods(root_module, cls): is_static=True) return +def register_Ns3Gnuplot2dDataset_methods(root_module, cls): + ## gnuplot.h: ns3::Gnuplot2dDataset::Gnuplot2dDataset(ns3::Gnuplot2dDataset const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Gnuplot2dDataset const &', 'arg0')]) + ## gnuplot.h: ns3::Gnuplot2dDataset::Gnuplot2dDataset(std::string const & title="Untitled") [constructor] + cls.add_constructor([param('std::string const &', 'title', default_value='"Untitled"')]) + ## gnuplot.h: static void ns3::Gnuplot2dDataset::SetDefaultStyle(ns3::Gnuplot2dDataset::Style style) [member function] + cls.add_method('SetDefaultStyle', + 'void', + [param('ns3::Gnuplot2dDataset::Style', 'style')], + is_static=True) + ## gnuplot.h: void ns3::Gnuplot2dDataset::SetStyle(ns3::Gnuplot2dDataset::Style style) [member function] + cls.add_method('SetStyle', + 'void', + [param('ns3::Gnuplot2dDataset::Style', 'style')]) + ## gnuplot.h: static void ns3::Gnuplot2dDataset::SetDefaultErrorBars(ns3::Gnuplot2dDataset::ErrorBars errorBars) [member function] + cls.add_method('SetDefaultErrorBars', + 'void', + [param('ns3::Gnuplot2dDataset::ErrorBars', 'errorBars')], + is_static=True) + ## gnuplot.h: void ns3::Gnuplot2dDataset::SetErrorBars(ns3::Gnuplot2dDataset::ErrorBars errorBars) [member function] + cls.add_method('SetErrorBars', + 'void', + [param('ns3::Gnuplot2dDataset::ErrorBars', 'errorBars')]) + ## gnuplot.h: void ns3::Gnuplot2dDataset::Add(double x, double y) [member function] + cls.add_method('Add', + 'void', + [param('double', 'x'), param('double', 'y')]) + ## gnuplot.h: void ns3::Gnuplot2dDataset::Add(double x, double y, double errorDelta) [member function] + cls.add_method('Add', + 'void', + [param('double', 'x'), param('double', 'y'), param('double', 'errorDelta')]) + ## gnuplot.h: void ns3::Gnuplot2dDataset::Add(double x, double y, double minY, double maxY) [member function] + cls.add_method('Add', + 'void', + [param('double', 'x'), param('double', 'y'), param('double', 'minY'), param('double', 'maxY')]) + ## gnuplot.h: void ns3::Gnuplot2dDataset::AddEmptyLine() [member function] + cls.add_method('AddEmptyLine', + 'void', + []) + return + +def register_Ns3Gnuplot2dFunction_methods(root_module, cls): + ## gnuplot.h: ns3::Gnuplot2dFunction::Gnuplot2dFunction(ns3::Gnuplot2dFunction const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Gnuplot2dFunction const &', 'arg0')]) + ## gnuplot.h: ns3::Gnuplot2dFunction::Gnuplot2dFunction(std::string const & title="Untitled", std::string const & function="") [constructor] + cls.add_constructor([param('std::string const &', 'title', default_value='"Untitled"'), param('std::string const &', 'function', default_value='""')]) + ## gnuplot.h: void ns3::Gnuplot2dFunction::SetFunction(std::string const & function) [member function] + cls.add_method('SetFunction', + 'void', + [param('std::string const &', 'function')]) + return + +def register_Ns3Gnuplot3dDataset_methods(root_module, cls): + ## gnuplot.h: ns3::Gnuplot3dDataset::Gnuplot3dDataset(ns3::Gnuplot3dDataset const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Gnuplot3dDataset const &', 'arg0')]) + ## gnuplot.h: ns3::Gnuplot3dDataset::Gnuplot3dDataset(std::string const & title="Untitled") [constructor] + cls.add_constructor([param('std::string const &', 'title', default_value='"Untitled"')]) + ## gnuplot.h: static void ns3::Gnuplot3dDataset::SetDefaultStyle(std::string const & style) [member function] + cls.add_method('SetDefaultStyle', + 'void', + [param('std::string const &', 'style')], + is_static=True) + ## gnuplot.h: void ns3::Gnuplot3dDataset::SetStyle(std::string const & style) [member function] + cls.add_method('SetStyle', + 'void', + [param('std::string const &', 'style')]) + ## gnuplot.h: void ns3::Gnuplot3dDataset::Add(double x, double y, double z) [member function] + cls.add_method('Add', + 'void', + [param('double', 'x'), param('double', 'y'), param('double', 'z')]) + ## gnuplot.h: void ns3::Gnuplot3dDataset::AddEmptyLine() [member function] + cls.add_method('AddEmptyLine', + 'void', + []) + return + +def register_Ns3Gnuplot3dFunction_methods(root_module, cls): + ## gnuplot.h: ns3::Gnuplot3dFunction::Gnuplot3dFunction(ns3::Gnuplot3dFunction const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Gnuplot3dFunction const &', 'arg0')]) + ## gnuplot.h: ns3::Gnuplot3dFunction::Gnuplot3dFunction(std::string const & title="Untitled", std::string const & function="") [constructor] + cls.add_constructor([param('std::string const &', 'title', default_value='"Untitled"'), param('std::string const &', 'function', default_value='""')]) + ## gnuplot.h: void ns3::Gnuplot3dFunction::SetFunction(std::string const & function) [member function] + cls.add_method('SetFunction', + 'void', + [param('std::string const &', 'function')]) + return + def register_functions(root_module): module = root_module register_functions_ns3_Config(module.get_submodule('Config'), root_module) From dece4c8aa4ba21f7593c66e500f9893aeb1449a2 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 9 Jan 2009 11:05:10 +0100 Subject: [PATCH 29/29] add tex package for nakagami doc formula --- doc/doxygen.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/doxygen.conf b/doc/doxygen.conf index b4d10dab9..1460ba842 100644 --- a/doc/doxygen.conf +++ b/doc/doxygen.conf @@ -846,7 +846,7 @@ PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. -EXTRA_PACKAGES = +EXTRA_PACKAGES = amsmath # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until