<commit_before>#include "ImGuiEngineStatsSystem.hpp"

#include "kengine.hpp"
#include "impl/GlobalState.hpp"

#include "data/NameComponent.hpp"
#include "data/ImGuiToolComponent.hpp"
#include "functions/Execute.hpp"

#include "imgui.h"

namespace kengine {
	EntityCreator * ImGuiEngineStatsSystem() noexcept {
		static bool * enabled;

		struct impl {
			static void init(Entity & e) noexcept {
				e += NameComponent{ "Engine stats" };
				auto & tool = e.attach<ImGuiToolComponent>();
				tool.enabled = true;
				enabled = &tool.enabled;

				e += functions::Execute{ execute };
			}

			static void execute(float deltaTime) noexcept {
				if (!*enabled)
					return;

				if (ImGui::Begin("Engine stats")) {
					const auto entityCount = std::count_if(
						kengine::impl::state->_entities.begin(), kengine::impl::state->_entities.end(),
						[](const kengine::impl::GlobalState::EntityMetadata & e) {
							return e.active && e.mask != 0;
						}
					);

					ImGui::Text("Entities: %zu", entityCount);
					ImGui::Text("\tEntity pool size: %zu", kengine::impl::state->_entities.size());
					ImGui::Text("Archetypes: %zu", kengine::impl::state->_archetypes.size());
					ImGui::Text("Component types: %zu", kengine::impl::state->_components.size());
				}
				ImGui::End();
			}
		};

		return impl::init;
	}
}
<commit_msg>engine stats -- add option to track specific collections<commit_after>#include "ImGuiEngineStatsSystem.hpp"

#include <fstream>

#include "kengine.hpp"
#include "impl/GlobalState.hpp"

#include "data/NameComponent.hpp"
#include "data/ImGuiToolComponent.hpp"

#include "functions/Execute.hpp"

#include "meta/Count.hpp"
#include "meta/Has.hpp"

#include "helpers/sortHelper.hpp"

#include "json.hpp"
#include "imgui.h"

#ifndef KENGINE_STATS_TRACKED_COLLECTIONS_SAVE_FILE
# define KENGINE_STATS_TRACKED_COLLECTIONS_SAVE_FILE "trackedEntityCollections.json"
#endif

namespace kengine {
	EntityCreator * ImGuiEngineStatsSystem() noexcept {
		static bool * enabled;

		struct impl {
			static void init(Entity & e) noexcept {
				e += NameComponent{ "Engine stats" };
				auto & tool = e.attach<ImGuiToolComponent>();
				tool.enabled = true;
				enabled = &tool.enabled;

				e += functions::Execute{ execute };
			}

			static void execute(float deltaTime) noexcept {
				if (!*enabled)
					return;

				if (ImGui::Begin("Engine stats")) {
					const auto entityCount = std::count_if(
						kengine::impl::state->_entities.begin(), kengine::impl::state->_entities.end(),
						[](const kengine::impl::GlobalState::EntityMetadata & e) {
							return e.active && e.mask != 0;
						}
					);

					ImGui::Text("Entities: %zu", entityCount);
					ImGui::Text("\tEntity pool size: %zu", kengine::impl::state->_entities.size());
					ImGui::Text("Archetypes: %zu", kengine::impl::state->_archetypes.size());
					ImGui::Text("Component types: %zu", kengine::impl::state->_components.size());
					displayTrackedCombinations();
				}
				ImGui::End();
			}

			struct Collection {
				std::string name;
				std::vector<EntityID> components;
				std::vector<std::string> missingComponents;
			};

			static void displayTrackedCombinations() noexcept {
				static std::vector<Collection> tracked = loadTrackedCollections();

				const auto newCollection = displayCombinationCreator();
				if (newCollection) {
					tracked.push_back(*newCollection);
					saveTrackedCollections(tracked);
				}

				for (size_t i = 0; i < tracked.size(); ++i) {
					auto & collection = tracked[i];
					if (collection.missingComponents.empty()) {
						const auto count = getCollectionCount(collection);
						ImGui::Text("%s: %zu", collection.name.c_str(), count);
					}
					else {
						std::string missingComponents;

						bool first = true;
						for (const auto & s : collection.missingComponents) {
							if (first)
								missingComponents += ", ";
							first = false;
							missingComponents += s;
						}

						ImGui::Text("%s: missing Component Entities for %s", collection.name.c_str(), missingComponents.c_str());
						findMissingComponentEntities(collection);
					}

					if (ImGui::BeginPopupContextItem("Remove collection")) {
						if (ImGui::MenuItem("Remove")) {
							tracked.erase(tracked.begin() + i);
							--i;
						}
						ImGui::EndPopup();
					}
				}
				for (const auto & collection : tracked) {
				}
			}

			static std::optional<Collection> displayCombinationCreator() noexcept {
				if (ImGui::Button("Track new collection", { -1.f, 0.f }))
					ImGui::OpenPopup("Create collection");

				if (ImGui::BeginPopup("Create collection")) {
					static Collection creating;

					if (ImGui::Button("Track", { -1.f, 0.f })) {
						ImGui::CloseCurrentPopup();
						if (!creating.components.empty()) {
							Collection ret;
							std::swap(ret, creating);

							bool first = true;
							for (const auto id : ret.components) {
								if (!first)
									ret.name += " + ";
								ret.name += entities[id].get<NameComponent>().name;
								first = false;
							}

							ImGui::EndPopup();
							return ret;
						}
					}

					const auto sortedEntities = sortHelper::getNameSortedEntities<meta::Has>();

					for (const auto [e, name, has] : sortedEntities) {
						const auto it = std::find(creating.components.begin(), creating.components.end(), e.id);
						bool inCreating = it != creating.components.end();
						if (ImGui::Checkbox(name->name, &inCreating)) {
							if (inCreating)
								creating.components.push_back(e.id);
							else
								creating.components.erase(it);
						}
					}
					ImGui::EndPopup();
				}

				return std::nullopt;
			}

			static size_t getCollectionCount(const Collection & collection) noexcept {
				if (collection.components.size() == 1) {
					const auto comp = entities[collection.components[0]];
					const auto count = comp.tryGet<meta::Count>();
					if (count)
						return count->call();
				}

				size_t ret = 0;
				for (const auto & e : entities) {
					bool good = true;

					for (const auto id : collection.components) {
						const auto comp = entities[id];
						const auto & has = comp.get<meta::Has>();
						if (!has(e)) {
							good = false;
							break;
						}
					}

					if (good)
						++ret;
				}

				return ret;
			}

			static void saveTrackedCollections(const std::vector<Collection> & collections) noexcept {
				std::ofstream f(KENGINE_STATS_TRACKED_COLLECTIONS_SAVE_FILE);
				if (!f) {
					kengine_assert_failed("Failed to open '", KENGINE_STATS_TRACKED_COLLECTIONS_SAVE_FILE, "' for writing");
					return;
				}

				putils::json fileJSON;

				for (const auto & collection : collections) {
					putils::json collectionJSON;
					for (const auto id : collection.components) {
						const auto & name = entities[id].get<NameComponent>();
						collectionJSON.push_back(name.name.c_str());
					}
					fileJSON.push_back(collectionJSON);
				}

				f << fileJSON;
			}

			static std::vector<Collection> loadTrackedCollections() noexcept {
				std::vector<Collection> ret;

				std::ifstream f(KENGINE_STATS_TRACKED_COLLECTIONS_SAVE_FILE);
				if (!f)
					return ret;

				const auto fileJSON = putils::json::parse(f);
				for (const auto & collectionJSON : fileJSON) {
					Collection collection;

					bool first = true;
					for (const auto & nameJSON : collectionJSON) {
						if (!first)
							collection.name += " + ";
						first = false;
						collection.name += nameJSON;

						bool found = false;
						for (const auto & [e, name, has] : entities.with<NameComponent, meta::Has>())
							if (name.name.c_str() == nameJSON) {
								collection.components.push_back(e.id);
								found = true;
								break;
							}

						if (!found)
							collection.missingComponents.push_back(nameJSON);
					}

					ret.push_back(std::move(collection));
				}

				return ret;
			}

			static void findMissingComponentEntities(Collection & collection) noexcept {
				for (size_t i = 0; i < collection.missingComponents.size(); ++i) {
					const auto & compName = collection.missingComponents[i];
					for (const auto & [e, name] : entities.with<NameComponent>())
						if (compName == name.name) {
							collection.components.push_back(e.id);
							collection.missingComponents.erase(collection.missingComponents.begin() + i);
							--i;
							break;
						}
				}
			}
		};

		return impl::init;
	}
}
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * 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: Vikas Pushkar (Adapted from third.cc)
 */

#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
#include "ns3/basic-energy-source.h"
#include "ns3/simple-device-energy-model.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WirelessAnimationExample");
int
main (int argc, char *argv[])
{

  //LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
  //LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
  uint32_t nWifi = 20;
  CommandLine cmd;
  cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);

  cmd.Parse (argc,argv);
  NodeContainer allNodes;
  NodeContainer wifiStaNodes;
  wifiStaNodes.Create (nWifi);
  allNodes.Add (wifiStaNodes);
  NodeContainer wifiApNode ;
  wifiApNode.Create (1);
  allNodes.Add (wifiApNode);

  YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
  YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
  phy.SetChannel (channel.Create ());

  WifiHelper wifi;
  wifi.SetRemoteStationManager ("ns3::AarfWifiManager");

  WifiMacHelper mac;
  Ssid ssid = Ssid ("ns-3-ssid");
  mac.SetType ("ns3::StaWifiMac",
               "Ssid", SsidValue (ssid),
               "ActiveProbing", BooleanValue (false));

  NetDeviceContainer staDevices;
  staDevices = wifi.Install (phy, mac, wifiStaNodes);
  mac.SetType ("ns3::ApWifiMac",
               "Ssid", SsidValue (ssid));

  NetDeviceContainer apDevices;
  apDevices = wifi.Install (phy, mac, wifiApNode);

  NodeContainer p2pNodes;
  p2pNodes.Add (wifiApNode);
  p2pNodes.Create (1);
  allNodes.Add (p2pNodes.Get (1));

  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

  NetDeviceContainer p2pDevices;
  p2pDevices = pointToPoint.Install (p2pNodes);

  NodeContainer csmaNodes;
  csmaNodes.Add (p2pNodes.Get (1));
  csmaNodes.Create (1);
  allNodes.Add (csmaNodes.Get (1));

  CsmaHelper csma;
  csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
  csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

  NetDeviceContainer csmaDevices;
  csmaDevices = csma.Install (csmaNodes);

  // Mobility

  MobilityHelper mobility;
  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (10.0), //
                                 "MinY", DoubleValue (10.0), //
                                 "DeltaX", DoubleValue (10.0), // Distância entre nós
                                 "DeltaY", DoubleValue (10.0), // Distância entre nós
                                 "GridWidth", UintegerValue (5), // Quantidade de colunas em uma linha
                                 "LayoutType", StringValue ("RowFirst")); // Definindo posições em linha
  // Mudança de parâmetros de RandomWalkingPosition para ConstantPosition
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (wifiStaNodes);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");

  mobility.Install (wifiApNode);
  AnimationInterface::SetConstantPosition (p2pNodes.Get (1), 40, 35);
  AnimationInterface::SetConstantPosition (csmaNodes.Get (1), 50, 30);

  Ptr<BasicEnergySource> energySource = CreateObject<BasicEnergySource>();
  Ptr<SimpleDeviceEnergyModel> energyModel = CreateObject<SimpleDeviceEnergyModel>();

  energySource->SetInitialEnergy (300);
  energyModel->SetEnergySource (energySource);
  energySource->AppendDeviceEnergyModel (energyModel);
  energyModel->SetCurrentA (20);

  // aggregate energy source to node
  wifiApNode.Get (0)->AggregateObject (energySource);

  // Install internet stack

  InternetStackHelper stack;
  stack.Install (allNodes);

  // Install Ipv4 addresses

  Ipv4AddressHelper address;
  address.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer p2pInterfaces;
  p2pInterfaces = address.Assign (p2pDevices);
  address.SetBase ("10.1.2.0", "255.255.255.0");
  Ipv4InterfaceContainer csmaInterfaces;
  csmaInterfaces = address.Assign (csmaDevices);
  address.SetBase ("10.1.3.0", "255.255.255.0");
  Ipv4InterfaceContainer staInterfaces;
  staInterfaces = address.Assign (staDevices);
  Ipv4InterfaceContainer apInterface;
  apInterface = address.Assign (apDevices);

  // Install applications

  UdpEchoServerHelper echoServer (9);
  ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (1));
  serverApps.Start (Seconds (1.0));
  serverApps.Stop (Seconds (15.0));
  UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (1), 9);
  echoClient.SetAttribute ("MaxPackets", UintegerValue (10));
  echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));
  echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
  ApplicationContainer clientApps = echoClient.Install (wifiStaNodes);
  clientApps.Start (Seconds (2.0));
  clientApps.Stop (Seconds (15.0));

  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
  Simulator::Stop (Seconds (15.0));

  AnimationInterface anim ("animacao-wireless.xml"); // Mandatory
  for (uint32_t i = 0; i < wifiStaNodes.GetN (); ++i)
    {
      anim.UpdateNodeDescription (wifiStaNodes.Get (i), "STA"); // Optional
      anim.UpdateNodeColor (wifiStaNodes.Get (i), 255, 0, 0); // Optional
    }
  for (uint32_t i = 0; i < wifiApNode.GetN (); ++i)
    {
      anim.UpdateNodeDescription (wifiApNode.Get (i), "AP"); // Optional
      anim.UpdateNodeColor (wifiApNode.Get (i), 0, 255, 0); // Optional
    }
  for (uint32_t i = 0; i < csmaNodes.GetN (); ++i)
    {
      anim.UpdateNodeDescription (csmaNodes.Get (i), "CSMA"); // Optional
      anim.UpdateNodeColor (csmaNodes.Get (i), 0, 0, 255); // Optional
    }

  anim.EnablePacketMetadata (); // Optional
  anim.EnableIpv4RouteTracking ("roteavel-wireless.xml", Seconds (0), Seconds (5), Seconds (0.25)); //Optional
  anim.EnableWifiMacCounters (Seconds (0), Seconds (10)); //Optional
  anim.EnableWifiPhyCounters (Seconds (0), Seconds (10)); //Optional
  Simulator::Run ();
  Simulator::Destroy ();
  return 0;
}
<commit_msg>alteracao_trace_limpeza<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * 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: Vikas Pushkar (Adapted from third.cc)
 */

#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
#include "ns3/basic-energy-source.h"
#include "ns3/simple-device-energy-model.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WirelessAnimationExample");
int
main (int argc, char *argv[])
{

  LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
  LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
  uint32_t nWifi = 20;
  CommandLine cmd;
  cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
  cmd.Parse (argc,argv);

  NodeContainer allNodes;
  NodeContainer wifiStaNodes;
  wifiStaNodes.Create (nWifi);
  allNodes.Add (wifiStaNodes);

  NodeContainer wifiApNode ;
  wifiApNode.Create (1);
  allNodes.Add (wifiApNode);

  YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
  YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
  phy.SetChannel (channel.Create ());

  WifiHelper wifi;
  wifi.SetRemoteStationManager ("ns3::AarfWifiManager");

  WifiMacHelper mac;
  Ssid ssid = Ssid ("ns-3-ssid");
  mac.SetType ("ns3::StaWifiMac",
               "Ssid", SsidValue (ssid),
               "ActiveProbing", BooleanValue (false));

  NetDeviceContainer staDevices;
  staDevices = wifi.Install (phy, mac, wifiStaNodes);
  mac.SetType ("ns3::ApWifiMac",
               "Ssid", SsidValue (ssid));

  NetDeviceContainer apDevices;
  apDevices = wifi.Install (phy, mac, wifiApNode);

  NodeContainer p2pNodes;
  p2pNodes.Add (wifiApNode);
  p2pNodes.Create (1);
  allNodes.Add (p2pNodes.Get (1));

  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
  NetDeviceContainer p2pDevices;
  p2pDevices = pointToPoint.Install (p2pNodes);

  NodeContainer csmaNodes;
  csmaNodes.Add (p2pNodes.Get (1));
  csmaNodes.Create (1);
  allNodes.Add (csmaNodes.Get (1));

  CsmaHelper csma;
  csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
  csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

  NetDeviceContainer csmaDevices;
  csmaDevices = csma.Install (csmaNodes);

  // Mobility

  MobilityHelper mobility;
  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (10.0), //onde inicia no eixo X
                                 "MinY", DoubleValue (10.0), //onde inicia no eixo Y
                                 "DeltaX", DoubleValue (10.0), // Distância entre nós
                                 "DeltaY", DoubleValue (10.0), // Distância entre nós
                                 "GridWidth", UintegerValue (5), // Quantidade de colunas em uma linha
                                 "LayoutType", StringValue ("RowFirst")); // Definindo posições em linha
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (wifiStaNodes);
  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (30.0), //
                                 "MinY", DoubleValue (25.0), //
                                 "DeltaX", DoubleValue (0.0), // Distância entre nós
                                 "DeltaY", DoubleValue (0.0), // Distância entre nós
                                 "GridWidth", UintegerValue (1), // Quantidade de colunas em uma linha
                                 "LayoutType", StringValue ("RowFirst"));
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (wifiApNode);
  AnimationInterface::SetConstantPosition (p2pNodes.Get (1), 40, 50);
  AnimationInterface::SetConstantPosition (csmaNodes.Get (1), 50, 50);

  Ptr<BasicEnergySource> energySource = CreateObject<BasicEnergySource>();
  Ptr<SimpleDeviceEnergyModel> energyModel = CreateObject<SimpleDeviceEnergyModel>();

  energySource->SetInitialEnergy (300);
  energyModel->SetEnergySource (energySource);
  energySource->AppendDeviceEnergyModel (energyModel);
  energyModel->SetCurrentA (20);

  // aggregate energy source to node
  wifiApNode.Get (0)->AggregateObject (energySource);

  // Install internet stack

  InternetStackHelper stack;
  stack.Install (allNodes);

  // Install Ipv4 addresses

  Ipv4AddressHelper address;
  address.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer p2pInterfaces;
  p2pInterfaces = address.Assign (p2pDevices);
  address.SetBase ("10.1.2.0", "255.255.255.0");
  Ipv4InterfaceContainer csmaInterfaces;
  csmaInterfaces = address.Assign (csmaDevices);
  address.SetBase ("10.1.3.0", "255.255.255.0");
  Ipv4InterfaceContainer staInterfaces;
  staInterfaces = address.Assign (staDevices);
  Ipv4InterfaceContainer apInterface;
  apInterface = address.Assign (apDevices);

  // Install applications

  UdpEchoServerHelper echoServer (9);
  ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (1));
  serverApps.Start (Seconds (1.0));
  serverApps.Stop (Seconds (15.0));
  UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (1), 9);
  echoClient.SetAttribute ("MaxPackets", UintegerValue (10));
  echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));
  echoClient.SetAttribute ("PacketSize", UintegerValue (2048));
  ApplicationContainer clientApps = echoClient.Install (wifiStaNodes);
  clientApps.Start (Seconds (2.0));
  clientApps.Stop (Seconds (15.0));

  AsciiTraceHelper ascii;
  csma.EnableAsciiAll (ascii.CreateFileStream ("wifi-segundo-real-tempo.tr"));
  csma.EnablePcapAll ("wifi-segundo-real-tempo", false);

  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
  Simulator::Stop (Seconds (15.0));

  AnimationInterface anim ("animacao-wireless.xml"); // Mandatory
  for (uint32_t i = 0; i < wifiStaNodes.GetN (); ++i)
    {
      anim.UpdateNodeDescription (wifiStaNodes.Get (i), "STA"); // Optional
      anim.UpdateNodeColor (wifiStaNodes.Get (i), 255, 0, 0); // Optional
    }
  for (uint32_t i = 0; i < wifiApNode.GetN (); ++i)
    {
      anim.UpdateNodeDescription (wifiApNode.Get (i), "AP"); // Optional
      anim.UpdateNodeColor (wifiApNode.Get (i), 0, 255, 0); // Optional
    }
  for (uint32_t i = 0; i < csmaNodes.GetN (); ++i)
    {
      anim.UpdateNodeDescription (csmaNodes.Get (i), "CSMA"); // Optional
      anim.UpdateNodeColor (csmaNodes.Get (i), 0, 0, 255); // Optional
    }

  anim.EnablePacketMetadata (); // Optional
  Simulator::Run ();
  Simulator::Destroy ();
  return 0;
}
 <|endoftext|>


<commit_before>#include "matrix.hpp"
#include "scggm_evaluate.hpp"
#include "scggm_penalty.hpp"
#include "scggm_soft_threshold.hpp"
#include "scggm_theta.hpp"
#include <cstdio>
#include <memory>

#ifndef SCGGM_SPARSE_STEP_HPP
#define SCGGM_SPARSE_STEP_HPP

struct scggm_sparse_obj {
  scggm_theta theta;
  SMatrix obj;
};

scggm_sparse_obj scggm_sparse_step(int lambda1, int lambda2, SMatrix cx,
                                   SMatrix cy, int maxiter, double tol,
                                   bool verbose, double eta,
                                   scggm_theta theta0) {
  scggm_sparse_obj ret;
  auto transposedCx = cx->transpose();
  auto Sx = transposedCx * cx, Sy = cy->transpose() * cy,
       Sxy = transposedCx * cy;
  auto N = cx->rows;
  int nobj = 10;
  int bconv = 0;
  ret.obj = std::make_shared<Matrix>(maxiter, 1);
  auto theta = theta0;
  double L = 1;
  double thk_0 = 2.0 / 3.0;
  int ls_maxiter = 300;
  scggm_evaluate_obj er = scggm_evaluate(theta, Sx, Sxy, Sy, N, 'n', verbose);
  auto obj1 = er.value;
  if (er.error == 1 && verbose) {
    puts("sCGGM: error! initial Theta_yy not positive definite!");
  }
  ret.obj->set_position(1, obj1 + scggm_penalty(theta, lambda1, lambda2));
  auto xk = theta, zk = theta;
  double thk = thk_0;
  for (int iter = 2; iter <= maxiter; ++iter) {
    thk = (sqrt(pow(thk, 4) + 4 * pow(thk, 2)) - pow(thk, 2)) / 2.0;
    scggm_theta y;
    y.xy = xk.xy->scalar(1 - thk) + zk.xy->scalar(thk);
    y.yy = xk.yy->scalar(1 - thk) + zk.yy->scalar(thk);
    auto er2 = scggm_evaluate(y, Sx, Sxy, Sy, N, 'y', verbose);
    double fyk = er2.value;
    auto grady = er2.grad;
    int ik = 0;
    double fxk1 = 0.0;
    while (true) {
      // gradient step
      scggm_theta zk_grady;
      zk_grady.xy = (zk.xy->subtract(1.0 / (L * thk))) * grady.xy;
      zk_grady.yy = (zk.yy->subtract(1.0 / (L * thk))) * grady.yy;
      // proximal step
      auto zk1 = scggm_soft_threshold(zk_grady, 2.0 * lambda1 / (thk * L),
                                      2.0 * lambda2 / (thk * L));
      // gradient step
      scggm_theta y_grady;
      y_grady.xy = y.xy - grady.xy->scalar(1.0 / L);
      y_grady.yy = y.yy - grady.yy->scalar(1.0 / L);
      // proximal step
      auto xk1 =
          scggm_soft_threshold(y_grady, 2.0 * lambda1 / L, 2.0 * lambda2 / L);
      auto er3 = scggm_evaluate(xk1, Sx, Sxy, Sy, N, 'n', verbose);
      fxk1 = er3.value;
      if (!zk1.yy->cholesky().error && !er2.error &&
          !er3.error) { // xk1, zk1, y all positive definite
        scggm_theta xk1_y;
        xk1_y.xy = xk1.xy - y.xy;
        xk1_y.yy = xk1.yy - y.yy;

        double lfxk1_y = fyk +
                         (grady.xy->list_elems_by_position()->transpose() *
                          xk1_y.xy->list_elems_by_position())
                             ->value() +
                         (grady.yy->list_elems_by_position()->transpose() *
                          xk1_y.yy->list_elems_by_position())
                             ->value();
        scggm_theta diffxk1y;
        diffxk1y.xy = xk1.xy - y.xy;
        diffxk1y.yy = xk1.yy - y.yy;
        double RHS =
            lfxk1_y +
            L / 2.0 *
                ((diffxk1y.xy->list_elems_by_position()->power(2))->sumValue() +
                 (diffxk1y.yy->list_elems_by_position()->power(2))->sumValue());
        if (fxk1 <= RHS + tol) {
          xk = xk1;
          zk = zk1;
          bconv = 1;
          break; // line search converged
        }
      }
      ++ik;
      if (ik > ls_maxiter) {
        if (verbose) {
          printf("sCGGM: line search not converging,ik = %d\n", ik);
        }
        bconv = 0;
        iter = std::max(1, iter - 1);
        ret.theta = xk;
        break;
      }
      L = L * eta;
    }
    ret.obj->set_position(iter, fxk1 + scggm_penalty(xk, lambda1, lambda2));
    if (bconv == 0) {
      break;
    }
    if (iter > nobj + 1) {
      double value = ret.obj->get_position(iter);
      double prevVals = ret.obj->get_position(iter - nobj);
      double avgimprovement = std::abs(prevVals - value) / nobj;
      double relAvgImpr = avgimprovement / std::abs(value);
      if (relAvgImpr < tol) {
        bconv = 1;
        break;
      }
    }
  }
  ret.theta = xk;
  /*
  TODO
  ret.obj   = ret.obj(1:iter);
  */
  return ret;
}

#endif
<commit_msg>Complete code<commit_after>#include "matrix.hpp"
#include "scggm_evaluate.hpp"
#include "scggm_penalty.hpp"
#include "scggm_soft_threshold.hpp"
#include "scggm_theta.hpp"
#include <cstdio>
#include <memory>

#ifndef SCGGM_SPARSE_STEP_HPP
#define SCGGM_SPARSE_STEP_HPP

struct scggm_sparse_obj {
  scggm_theta theta;
  SMatrix obj;
};

scggm_sparse_obj scggm_sparse_step(int lambda1, int lambda2, SMatrix cx,
                                   SMatrix cy, int maxiter, double tol,
                                   bool verbose, double eta,
                                   scggm_theta theta0) {
  scggm_sparse_obj ret;
  auto transposedCx = cx->transpose();
  auto Sx = transposedCx * cx, Sy = cy->transpose() * cy,
       Sxy = transposedCx * cy;
  auto N = cx->rows;
  int nobj = 10;
  int bconv = 0;
  ret.obj = std::make_shared<Matrix>(maxiter, 1);
  auto theta = theta0;
  double L = 1;
  double thk_0 = 2.0 / 3.0;
  int ls_maxiter = 300;
  scggm_evaluate_obj er = scggm_evaluate(theta, Sx, Sxy, Sy, N, 'n', verbose);
  auto obj1 = er.value;
  if (er.error == 1 && verbose) {
    puts("sCGGM: error! initial Theta_yy not positive definite!");
  }
  ret.obj->set_position(1, obj1 + scggm_penalty(theta, lambda1, lambda2));
  auto xk = theta, zk = theta;
  double thk = thk_0;
  int iter;
  for (iter = 2; iter <= maxiter; ++iter) {
    thk = (sqrt(pow(thk, 4) + 4 * pow(thk, 2)) - pow(thk, 2)) / 2.0;
    scggm_theta y;
    y.xy = xk.xy->scalar(1 - thk) + zk.xy->scalar(thk);
    y.yy = xk.yy->scalar(1 - thk) + zk.yy->scalar(thk);
    auto er2 = scggm_evaluate(y, Sx, Sxy, Sy, N, 'y', verbose);
    double fyk = er2.value;
    auto grady = er2.grad;
    int ik = 0;
    double fxk1 = 0.0;
    while (true) {
      // gradient step
      scggm_theta zk_grady;
      zk_grady.xy = (zk.xy->subtract(1.0 / (L * thk))) * grady.xy;
      zk_grady.yy = (zk.yy->subtract(1.0 / (L * thk))) * grady.yy;
      // proximal step
      auto zk1 = scggm_soft_threshold(zk_grady, 2.0 * lambda1 / (thk * L),
                                      2.0 * lambda2 / (thk * L));
      // gradient step
      scggm_theta y_grady;
      y_grady.xy = y.xy - grady.xy->scalar(1.0 / L);
      y_grady.yy = y.yy - grady.yy->scalar(1.0 / L);
      // proximal step
      auto xk1 =
          scggm_soft_threshold(y_grady, 2.0 * lambda1 / L, 2.0 * lambda2 / L);
      auto er3 = scggm_evaluate(xk1, Sx, Sxy, Sy, N, 'n', verbose);
      fxk1 = er3.value;
      if (!zk1.yy->cholesky().error && !er2.error &&
          !er3.error) { // xk1, zk1, y all positive definite
        scggm_theta xk1_y;
        xk1_y.xy = xk1.xy - y.xy;
        xk1_y.yy = xk1.yy - y.yy;

        double lfxk1_y = fyk +
                         (grady.xy->list_elems_by_position()->transpose() *
                          xk1_y.xy->list_elems_by_position())
                             ->value() +
                         (grady.yy->list_elems_by_position()->transpose() *
                          xk1_y.yy->list_elems_by_position())
                             ->value();
        scggm_theta diffxk1y;
        diffxk1y.xy = xk1.xy - y.xy;
        diffxk1y.yy = xk1.yy - y.yy;
        double RHS =
            lfxk1_y +
            L / 2.0 *
                ((diffxk1y.xy->list_elems_by_position()->power(2))->sumValue() +
                 (diffxk1y.yy->list_elems_by_position()->power(2))->sumValue());
        if (fxk1 <= RHS + tol) {
          xk = xk1;
          zk = zk1;
          bconv = 1;
          break; // line search converged
        }
      }
      ++ik;
      if (ik > ls_maxiter) {
        if (verbose) {
          printf("sCGGM: line search not converging,ik = %d\n", ik);
        }
        bconv = 0;
        iter = std::max(1, iter - 1);
        ret.theta = xk;
        break;
      }
      L = L * eta;
    }
    ret.obj->set_position(iter, fxk1 + scggm_penalty(xk, lambda1, lambda2));
    if (bconv == 0) {
      break;
    }
    if (iter > nobj + 1) {
      double value = ret.obj->get_position(iter);
      double prevVals = ret.obj->get_position(iter - nobj);
      double avgimprovement = std::abs(prevVals - value) / nobj;
      double relAvgImpr = avgimprovement / std::abs(value);
      if (relAvgImpr < tol) {
        bconv = 1;
        break;
      }
    }
  }
  ret.theta = xk;
  ret.obj = ret.obj->row_elems_by_position(1, iter);
  return ret;
}

#endif
<|endoftext|>


<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <limits>

stan::math::vector_d get_simplex_Phi(double lambda,
                                     const stan::math::vector_d& c) {
  using stan::math::Phi;
  int K = c.size() + 1;
  stan::math::vector_d theta(K);
  theta(0) = 1.0 - Phi(lambda - c(0));
  for (int k = 1; k < (K - 1); ++k)
    theta(k) = Phi(lambda - c(k - 1)) - Phi(lambda - c(k));
  // - 0.0
  theta(K - 1) = Phi(lambda - c(K - 2));
  return theta;
}

double old_ordered_probit(int y, double lambda, stan::math::vector_d c) {
  using stan::math::Phi;
  using stan::math::log1m;
  using stan::math::log;

  int K = c.size() + 1;

  if (y == 1) {
    return log1m(Phi(lambda - c(0)));
  } else if (y == K) {
    return log(Phi(lambda - c(K - 2)));
  } else {
    return log(Phi(lambda - c(y - 2)) - Phi(lambda - c(y - 1)));
  }
}

TEST(ProbDistributions, ordered_probit_stability) {
  using stan::math::is_inf;
  using stan::math::ordered_probit_log;

  Eigen::VectorXd c(3);
  c << -0.3, 0.1, 1.2;

  EXPECT_TRUE(is_inf(old_ordered_probit(1, 10, c)));
  EXPECT_TRUE(is_inf(old_ordered_probit(2, 10, c)));
  EXPECT_EQ(old_ordered_probit(4, 10, c), 0);

  EXPECT_EQ(old_ordered_probit(1, -38, c), 0);
  EXPECT_TRUE(is_inf(old_ordered_probit(2, -38, c)));
  EXPECT_TRUE(is_inf(old_ordered_probit(4, -38, c)));

  EXPECT_FALSE(is_inf(ordered_probit_log(1, 9, c)));
  EXPECT_FALSE(is_inf(ordered_probit_log(2, 9, c)));
  EXPECT_NE(ordered_probit_log(4, 10, c), 0);

  EXPECT_NE(ordered_probit_log(1, -38, c), 0);
  EXPECT_FALSE(is_inf(ordered_probit_log(2, -38, c)));
  EXPECT_FALSE(is_inf(ordered_probit_log(4, -38, c)));
}

TEST(ProbDistributions, ordered_probit_vals) {
  using Eigen::Dynamic;
  using Eigen::Matrix;

  using stan::math::ordered_probit_log;
  using stan::math::Phi;

  int K = 5;
  Matrix<double, Dynamic, 1> c(K - 1);
  c << -1.7, -0.3, 1.2, 2.6;
  double lambda = 1.1;

  stan::math::vector_d theta = get_simplex_Phi(lambda, c);

  double sum = 0.0;
  for (int k = 0; k < theta.size(); ++k)
    sum += theta(k);
  EXPECT_FLOAT_EQ(1.0, sum);

  for (int k = 0; k < K; ++k)
    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));

  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(6, lambda, c), std::domain_error);
}

TEST(ProbDistributions, ordered_probit_vals_2) {
  using Eigen::Dynamic;
  using Eigen::Matrix;

  using stan::math::ordered_probit_log;
  using stan::math::Phi;

  int K = 3;
  Matrix<double, Dynamic, 1> c(K - 1);
  c << -0.2, 4;
  double lambda = -0.9;

  stan::math::vector_d theta = get_simplex_Phi(lambda, c);

  double sum = 0.0;
  for (int k = 0; k < theta.size(); ++k)
    sum += theta(k);
  EXPECT_FLOAT_EQ(1.0, sum);

  for (int k = 0; k < K; ++k)
    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));

  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(4, lambda, c), std::domain_error);
}

TEST(ProbDistributions, ordered_probit) {
  using stan::math::ordered_probit_log;
  int K = 4;
  Eigen::Matrix<double, Eigen::Dynamic, 1> c(K - 1);
  c << -0.3, 0.1, 1.2;
  double lambda = 0.5;
  EXPECT_THROW(ordered_probit_log(-1, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(5, lambda, c), std::domain_error);
  for (int k = 1; k <= K; ++k)
    EXPECT_NO_THROW(ordered_probit_log(k, lambda, c));

  // init size zero
  Eigen::Matrix<double, Eigen::Dynamic, 1> c_zero;
  EXPECT_EQ(0, c_zero.size());
  EXPECT_THROW(ordered_probit_log(1, lambda, c_zero), std::invalid_argument);

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_neg(1);
  c_neg << -13.7;
  EXPECT_NO_THROW(ordered_probit_log(1, lambda, c_neg));

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord(3);
  c_unord << 1.0, 0.4, 2.0;
  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord_2(3);
  c_unord_2 << 1.0, 2.0, 0.4;
  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord_2), std::domain_error);

  double nan = std::numeric_limits<double>::quiet_NaN();
  double inf = std::numeric_limits<double>::infinity();

  EXPECT_THROW(ordered_probit_log(1, nan, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(1, inf, c), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad(2);
  cbad << 0.2, inf;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);
  cbad[1] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad1(1);
  cbad1 << inf;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);
  cbad1[0] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad3(3);
  cbad3 << 0.5, inf, 1.0;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);
  cbad3[1] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);
}

TEST(ProbDistributionOrderedProbit, error_check) {
  boost::random::mt19937 rng;
  double inf = std::numeric_limits<double>::infinity();
  Eigen::VectorXd c(4);
  c << -2, 2.0, 5, 10;
  EXPECT_NO_THROW(stan::math::ordered_probit_rng(4.0, c, rng));

  EXPECT_THROW(
      stan::math::ordered_probit_rng(stan::math::positive_infinity(), c, rng),
      std::domain_error);
  c << -inf, 2.0, -5, inf;
  EXPECT_THROW(stan::math::ordered_probit_rng(4.0, c, rng), std::domain_error);
}

TEST(ProbDistributionOrderedProbit, chiSquareGoodnessFitTest) {
  using stan::math::Phi;
  boost::random::mt19937 rng;
  int N = 10000;
  double eta = 1.0;
  Eigen::VectorXd theta(3);
  theta << -0.4, 4.0, 6.2;
  Eigen::VectorXd prob(4);
  prob(0) = 1 - Phi(eta - theta(0));
  prob(1) = Phi(eta - theta(0)) - Phi(eta - theta(1));
  prob(2) = Phi(eta - theta(1)) - Phi(eta - theta(2));
  prob(3) = Phi(eta - theta(2));
  int K = prob.rows();
  boost::math::chi_squared mydist(K - 1);

  Eigen::VectorXd loc(prob.rows());
  for (int i = 0; i < prob.rows(); i++)
    loc(i) = 0;

  for (int i = 0; i < prob.rows(); i++) {
    for (int j = i; j < prob.rows(); j++)
      loc(j) += prob(i);
  }

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N * prob(i);
  }

  while (count < N) {
    int a = stan::math::ordered_probit_rng(eta, theta, rng);
    bin[a - 1]++;
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <limits>

stan::math::vector_d get_simplex_Phi(double lambda,
                                     const stan::math::vector_d& c) {
  using stan::math::Phi;
  int K = c.size() + 1;
  stan::math::vector_d theta(K);
  theta(0) = 1.0 - Phi(lambda - c(0));
  for (int k = 1; k < (K - 1); ++k)
    theta(k) = Phi(lambda - c(k - 1)) - Phi(lambda - c(k));
  // - 0.0
  theta(K - 1) = Phi(lambda - c(K - 2));
  return theta;
}

double old_ordered_probit(int y, double lambda, stan::math::vector_d c) {
  using stan::math::log;
  using stan::math::log1m;
  using stan::math::Phi;

  int K = c.size() + 1;

  if (y == 1) {
    return log1m(Phi(lambda - c(0)));
  } else if (y == K) {
    return log(Phi(lambda - c(K - 2)));
  } else {
    return log(Phi(lambda - c(y - 2)) - Phi(lambda - c(y - 1)));
  }
}

TEST(ProbDistributions, ordered_probit_stability) {
  using stan::math::is_inf;
  using stan::math::ordered_probit_log;

  Eigen::VectorXd c(3);
  c << -0.3, 0.1, 1.2;

  EXPECT_TRUE(is_inf(old_ordered_probit(1, 10, c)));
  EXPECT_TRUE(is_inf(old_ordered_probit(2, 10, c)));
  EXPECT_EQ(old_ordered_probit(4, 10, c), 0);

  EXPECT_EQ(old_ordered_probit(1, -38, c), 0);
  EXPECT_TRUE(is_inf(old_ordered_probit(2, -38, c)));
  EXPECT_TRUE(is_inf(old_ordered_probit(4, -38, c)));

  EXPECT_FALSE(is_inf(ordered_probit_log(1, 9, c)));
  EXPECT_FALSE(is_inf(ordered_probit_log(2, 9, c)));
  EXPECT_NE(ordered_probit_log(4, 10, c), 0);

  EXPECT_NE(ordered_probit_log(1, -38, c), 0);
  EXPECT_FALSE(is_inf(ordered_probit_log(2, -38, c)));
  EXPECT_FALSE(is_inf(ordered_probit_log(4, -38, c)));
}

TEST(ProbDistributions, ordered_probit_vals) {
  using Eigen::Dynamic;
  using Eigen::Matrix;

  using stan::math::ordered_probit_log;
  using stan::math::Phi;

  int K = 5;
  Matrix<double, Dynamic, 1> c(K - 1);
  c << -1.7, -0.3, 1.2, 2.6;
  double lambda = 1.1;

  stan::math::vector_d theta = get_simplex_Phi(lambda, c);

  double sum = 0.0;
  for (int k = 0; k < theta.size(); ++k)
    sum += theta(k);
  EXPECT_FLOAT_EQ(1.0, sum);

  for (int k = 0; k < K; ++k)
    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));

  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(6, lambda, c), std::domain_error);
}

TEST(ProbDistributions, ordered_probit_vals_2) {
  using Eigen::Dynamic;
  using Eigen::Matrix;

  using stan::math::ordered_probit_log;
  using stan::math::Phi;

  int K = 3;
  Matrix<double, Dynamic, 1> c(K - 1);
  c << -0.2, 4;
  double lambda = -0.9;

  stan::math::vector_d theta = get_simplex_Phi(lambda, c);

  double sum = 0.0;
  for (int k = 0; k < theta.size(); ++k)
    sum += theta(k);
  EXPECT_FLOAT_EQ(1.0, sum);

  for (int k = 0; k < K; ++k)
    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));

  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(4, lambda, c), std::domain_error);
}

TEST(ProbDistributions, ordered_probit) {
  using stan::math::ordered_probit_log;
  int K = 4;
  Eigen::Matrix<double, Eigen::Dynamic, 1> c(K - 1);
  c << -0.3, 0.1, 1.2;
  double lambda = 0.5;
  EXPECT_THROW(ordered_probit_log(-1, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(5, lambda, c), std::domain_error);
  for (int k = 1; k <= K; ++k)
    EXPECT_NO_THROW(ordered_probit_log(k, lambda, c));

  // init size zero
  Eigen::Matrix<double, Eigen::Dynamic, 1> c_zero;
  EXPECT_EQ(0, c_zero.size());
  EXPECT_THROW(ordered_probit_log(1, lambda, c_zero), std::invalid_argument);

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_neg(1);
  c_neg << -13.7;
  EXPECT_NO_THROW(ordered_probit_log(1, lambda, c_neg));

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord(3);
  c_unord << 1.0, 0.4, 2.0;
  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord_2(3);
  c_unord_2 << 1.0, 2.0, 0.4;
  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord_2), std::domain_error);

  double nan = std::numeric_limits<double>::quiet_NaN();
  double inf = std::numeric_limits<double>::infinity();

  EXPECT_THROW(ordered_probit_log(1, nan, c), std::domain_error);
  EXPECT_THROW(ordered_probit_log(1, inf, c), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad(2);
  cbad << 0.2, inf;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);
  cbad[1] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad1(1);
  cbad1 << inf;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);
  cbad1[0] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);

  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad3(3);
  cbad3 << 0.5, inf, 1.0;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);
  cbad3[1] = nan;
  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);
}

TEST(ProbDistributionOrderedProbit, error_check) {
  boost::random::mt19937 rng;
  double inf = std::numeric_limits<double>::infinity();
  Eigen::VectorXd c(4);
  c << -2, 2.0, 5, 10;
  EXPECT_NO_THROW(stan::math::ordered_probit_rng(4.0, c, rng));

  EXPECT_THROW(
      stan::math::ordered_probit_rng(stan::math::positive_infinity(), c, rng),
      std::domain_error);
  c << -inf, 2.0, -5, inf;
  EXPECT_THROW(stan::math::ordered_probit_rng(4.0, c, rng), std::domain_error);
}

TEST(ProbDistributionOrderedProbit, chiSquareGoodnessFitTest) {
  using stan::math::Phi;
  boost::random::mt19937 rng;
  int N = 10000;
  double eta = 1.0;
  Eigen::VectorXd theta(3);
  theta << -0.4, 4.0, 6.2;
  Eigen::VectorXd prob(4);
  prob(0) = 1 - Phi(eta - theta(0));
  prob(1) = Phi(eta - theta(0)) - Phi(eta - theta(1));
  prob(2) = Phi(eta - theta(1)) - Phi(eta - theta(2));
  prob(3) = Phi(eta - theta(2));
  int K = prob.rows();
  boost::math::chi_squared mydist(K - 1);

  Eigen::VectorXd loc(prob.rows());
  for (int i = 0; i < prob.rows(); i++)
    loc(i) = 0;

  for (int i = 0; i < prob.rows(); i++) {
    for (int j = i; j < prob.rows(); j++)
      loc(j) += prob(i);
  }

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N * prob(i);
  }

  while (count < N) {
    int a = stan::math::ordered_probit_rng(eta, theta, rng);
    bin[a - 1]++;
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/grappler/optimizers/meta_optimizer.h"
#include "tensorflow/core/grappler/optimizers/constant_folding.h"
#include "tensorflow/core/grappler/optimizers/graph_optimizer.h"
#include "tensorflow/core/grappler/optimizers/layout_optimizer.h"
#include "tensorflow/core/grappler/optimizers/model_pruner.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {
namespace grappler {

std::unique_ptr<GraphOptimizer> MetaOptimizer::NewOptimizer(
    const string& optimizer) {
  VLOG(1) << "Adding graph optimization pass: " << optimizer;
  std::unique_ptr<GraphOptimizer> graph_optimizer;
  if (optimizer == "pruning") {
    graph_optimizer.reset(new ModelPruner());
  }
  if (optimizer == "constfold") {
    graph_optimizer.reset(new ConstantFolding());
  }
  if (optimizer == "layout") {
    graph_optimizer.reset(new LayoutOptimizer());
  }
  return graph_optimizer;
}

Status MetaOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item,
                               GraphDef* optimized_graph) {
  std::vector<std::unique_ptr<GraphOptimizer>> optimizers;
  if (cfg_.optimizers().empty()) {
    if (!cfg_.disable_model_pruning()) {
      optimizers.push_back(std::unique_ptr<GraphOptimizer>(new ModelPruner()));
    }
    if (cfg_.constant_folding()) {
      optimizers.push_back(
          std::unique_ptr<GraphOptimizer>(new ConstantFolding()));
    }
    if (cfg_.optimize_tensor_layout()) {
      optimizers.push_back(
          std::unique_ptr<GraphOptimizer>(new LayoutOptimizer()));
    }
  } else {
    std::set<string> avaliable_optimizers = {"pruning", "constfold", "layout"};
    for (const auto& optimizer : cfg_.optimizers()) {
      if (avaliable_optimizers.find(optimizer) != avaliable_optimizers.end()) {
        optimizers.push_back(NewOptimizer(optimizer));
      }
    }
  }

  if (optimizers.empty()) {
    *optimized_graph = item.graph;
    return Status::OK();
  }

  bool already_optimized = false;
  for (const auto& optimizer : optimizers) {
    if (!already_optimized) {
      TF_RETURN_IF_ERROR(optimizer->Optimize(nullptr, item, optimized_graph));
      already_optimized = true;
    } else {
      GrapplerItem optimized_item = item;
      optimized_item.graph = *optimized_graph;
      TF_RETURN_IF_ERROR(
          optimizer->Optimize(nullptr, optimized_item, optimized_graph));
    }
  }

  return Status::OK();
}

void MetaOptimizer::Feedback(Cluster* cluster, const GrapplerItem& item,
                             const GraphDef& pruned_graph, double result) {
  // Nothing to do for MetaOptimizer.
}

bool MetaOptimizerEnabled(const RewriterConfig& cfg) {
  return cfg.optimize_tensor_layout();
}

Status RunMetaOptimizer(const GrapplerItem& item, const RewriterConfig& cfg,
                        GraphDef* optimized_graph) {
  MetaOptimizer optimizer(cfg);
  return optimizer.Optimize(nullptr, item, optimized_graph);
}

}  // namespace grappler
}  // namespace tensorflow
<commit_msg>Preserve graph version during optimization Change: 152213262<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/grappler/optimizers/meta_optimizer.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/grappler/optimizers/constant_folding.h"
#include "tensorflow/core/grappler/optimizers/graph_optimizer.h"
#include "tensorflow/core/grappler/optimizers/layout_optimizer.h"
#include "tensorflow/core/grappler/optimizers/model_pruner.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {
namespace grappler {

std::unique_ptr<GraphOptimizer> MetaOptimizer::NewOptimizer(
    const string& optimizer) {
  VLOG(1) << "Adding graph optimization pass: " << optimizer;
  std::unique_ptr<GraphOptimizer> graph_optimizer;
  if (optimizer == "pruning") {
    graph_optimizer.reset(new ModelPruner());
  }
  if (optimizer == "constfold") {
    graph_optimizer.reset(new ConstantFolding());
  }
  if (optimizer == "layout") {
    graph_optimizer.reset(new LayoutOptimizer());
  }
  return graph_optimizer;
}

Status MetaOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item,
                               GraphDef* optimized_graph) {
  std::vector<std::unique_ptr<GraphOptimizer>> optimizers;
  if (cfg_.optimizers().empty()) {
    if (!cfg_.disable_model_pruning()) {
      optimizers.push_back(std::unique_ptr<GraphOptimizer>(new ModelPruner()));
    }
    if (cfg_.constant_folding()) {
      optimizers.push_back(
          std::unique_ptr<GraphOptimizer>(new ConstantFolding()));
    }
    if (cfg_.optimize_tensor_layout()) {
      optimizers.push_back(
          std::unique_ptr<GraphOptimizer>(new LayoutOptimizer()));
    }
  } else {
    std::set<string> avaliable_optimizers = {"pruning", "constfold", "layout"};
    for (const auto& optimizer : cfg_.optimizers()) {
      if (avaliable_optimizers.find(optimizer) != avaliable_optimizers.end()) {
        optimizers.push_back(NewOptimizer(optimizer));
      }
    }
  }

  if (optimizers.empty()) {
    *optimized_graph = item.graph;
    return Status::OK();
  }

  bool already_optimized = false;
  for (const auto& optimizer : optimizers) {
    if (!already_optimized) {
      TF_RETURN_IF_ERROR(optimizer->Optimize(nullptr, item, optimized_graph));
      already_optimized = true;
    } else {
      GrapplerItem optimized_item = item;
      optimized_item.graph = *optimized_graph;
      TF_RETURN_IF_ERROR(
          optimizer->Optimize(nullptr, optimized_item, optimized_graph));
    }
  }

  // Copy the graph version.
  *optimized_graph->mutable_versions() = item.graph.versions();

  return Status::OK();
}

void MetaOptimizer::Feedback(Cluster* cluster, const GrapplerItem& item,
                             const GraphDef& pruned_graph, double result) {
  // Nothing to do for MetaOptimizer.
}

bool MetaOptimizerEnabled(const RewriterConfig& cfg) {
  return cfg.optimize_tensor_layout();
}

Status RunMetaOptimizer(const GrapplerItem& item, const RewriterConfig& cfg,
                        GraphDef* optimized_graph) {
  MetaOptimizer optimizer(cfg);
  return optimizer.Optimize(nullptr, item, optimized_graph);
}

}  // namespace grappler
}  // namespace tensorflow
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <QDebug>

#include <qbluetoothuuid.h>

#include <arpa/inet.h>
#include <netinet/in.h>

QTM_USE_NAMESPACE

Q_DECLARE_METATYPE(quint128)

class tst_QBluetoothUuid : public QObject
{
    Q_OBJECT

public:
    tst_QBluetoothUuid();
    ~tst_QBluetoothUuid();

private slots:
    void initTestCase();

    void tst_construction();
    void tst_assignment();
    void tst_conversion_data();
    void tst_conversion();
    void tst_comparison_data();
    void tst_comparison();
};

tst_QBluetoothUuid::tst_QBluetoothUuid()
{
    qRegisterMetaType<quint128>("quint128");
}

tst_QBluetoothUuid::~tst_QBluetoothUuid()
{
}

void tst_QBluetoothUuid::initTestCase()
{
}

void tst_QBluetoothUuid::tst_construction()
{
    {
        QBluetoothUuid nullUuid;

        QVERIFY(nullUuid.isNull());
    }

    {
        QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

        QVERIFY(!uuid.isNull());

        bool ok;
        quint16 uuid16;

        uuid16 = uuid.toUInt16(&ok);

        QVERIFY(ok);
        QCOMPARE(uuid16, static_cast<quint16>(QBluetoothUuid::PublicBrowseGroup));
    }

    {
        QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

        QBluetoothUuid copy(uuid);

        QCOMPARE(uuid.toUInt16(), copy.toUInt16());
    }
}

void tst_QBluetoothUuid::tst_assignment()
{
    QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

    {
        QBluetoothUuid copy = uuid;

        QCOMPARE(uuid.toUInt16(), copy.toUInt16());
    }

    {
        QBluetoothUuid copy1;
        QBluetoothUuid copy2;

        QVERIFY(copy1.isNull());
        QVERIFY(copy2.isNull());

        copy1 = copy2 = uuid;

        QVERIFY(!copy1.isNull());
        QVERIFY(!copy2.isNull());

        QCOMPARE(uuid.toUInt16(), copy1.toUInt16());
        QCOMPARE(uuid.toUInt16(), copy2.toUInt16());
    }
}

#define BASEUUID "-0000-1000-8000-00805F9B34FB"

#define UUID128_32(x, a, b, c, d) \
    quint128 x = { \
        { \
            a, b, c, d, \
            0x00, 0x00, \
            0x10, 0x00, \
            0x80, 0x00, \
            0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB \
        } \
    }

#define UUID128_16(x, a, b) UUID128_32(x, 0, 0, a, b)

#define NEWROW16(text, a, b, s) \
do { \
    UUID128_16(uuid128, a, b); \
    quint32 uuid32 = a << 8 | b; \
    quint16 uuid16 = a << 8 | b; \
    QTest::newRow(text) << true << uuid16 << true << uuid32 << true << uuid128 \
                        << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \
} while (0)

#define NEWROW32(text, a, b, c, d, s) \
do { \
    UUID128_32(uuid128, a, b, c, d); \
    quint32 uuid32 = a << 24 | b << 16 | c << 8 | d; \
    quint16 uuid16; \
    bool constructUuid16 = (a == 0) && (b == 0); \
    if (constructUuid16) \
        uuid16 = c << 8 | d; \
    else \
        uuid16 = 0; \
    QTest::newRow(text) << constructUuid16 << uuid16 << true << uuid32 << true << uuid128 \
                        << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \
} while (0)

void tst_QBluetoothUuid::tst_conversion_data()
{
    QTest::addColumn<bool>("constructUuid16");
    QTest::addColumn<quint16>("uuid16");
    QTest::addColumn<bool>("constructUuid32");
    QTest::addColumn<quint32>("uuid32");
    QTest::addColumn<bool>("constructUuid128");
    QTest::addColumn<quint128>("uuid128");
    QTest::addColumn<QString>("uuidS");

    NEWROW32("base uuid", 0x00, 0x00, 0x00, 0x00, "00000000" BASEUUID);
    NEWROW16("0x0001", 0x00, 0x01, "00000001" BASEUUID);
    NEWROW16("0xffff", 0xff, 0xff, "0000FFFF" BASEUUID);
    NEWROW32("0x00010000", 0x00, 0x01, 0x00, 0x00, "00010000" BASEUUID);
    NEWROW32("0x0001ffff", 0x00, 0x01, 0xff, 0xff, "0001FFFF" BASEUUID);
    NEWROW32("0xffff0000", 0xff, 0xff, 0x00, 0x00, "FFFF0000" BASEUUID);
    NEWROW32("0xffffffff", 0xff, 0xff, 0xff, 0xff, "FFFFFFFF" BASEUUID);

    {
        quint128 uuid128 = {
            {
                0x00, 0x11, 0x22, 0x33,
                0x44, 0x55,
                0x66, 0x77,
                0x88, 0x99,
                0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
            }
        };

        QTest::newRow("00112233-4455-6677-8899-AABBCCDDEEFF")
            << false << quint16(0) << false << quint32(0) << true << uuid128
            << QString(QLatin1String("{00112233-4455-6677-8899-AABBCCDDEEFF}"));
    }
}

void tst_QBluetoothUuid::tst_conversion()
{
    QFETCH(bool, constructUuid16);
    QFETCH(quint16, uuid16);
    QFETCH(bool, constructUuid32);
    QFETCH(quint32, uuid32);
    QFETCH(bool, constructUuid128);
    QFETCH(quint128, uuid128);
    QFETCH(QString, uuidS);

    int minimumSize = 16;
    if (constructUuid16)
        minimumSize = 2;
    else if (constructUuid32)
        minimumSize = 4;

    if (constructUuid16) {
        QBluetoothUuid uuid(uuid16);

        bool ok;

        QCOMPARE(uuid.toUInt16(&ok), uuid16);
        QVERIFY(ok);

        QCOMPARE(uuid.toUInt32(&ok), uuid32);
        QVERIFY(ok);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }

    if (constructUuid32) {
        QBluetoothUuid uuid(uuid32);

        bool ok;

        quint16 tmp = uuid.toUInt16(&ok);
        QCOMPARE(ok, constructUuid16);
        if (ok) {
            QCOMPARE(tmp, uuid16);
        }

        QCOMPARE(uuid.toUInt32(&ok), uuid32);
        QVERIFY(ok);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }

    if (constructUuid128) {
        QBluetoothUuid uuid(uuid128);

        bool ok;

        quint16 tmpUuid16 = uuid.toUInt16(&ok);
        QCOMPARE(ok, constructUuid16);
        if (ok)
            QCOMPARE(tmpUuid16, uuid16);

        quint32 tmpUuid32 = uuid.toUInt32(&ok);
        QCOMPARE(ok, constructUuid32);
        if (ok)
            QCOMPARE(tmpUuid32, uuid32);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }
}

void tst_QBluetoothUuid::tst_comparison_data()
{
    tst_conversion_data();
}

void tst_QBluetoothUuid::tst_comparison()
{
    QFETCH(bool, constructUuid16);
    QFETCH(quint16, uuid16);
    QFETCH(bool, constructUuid32);
    QFETCH(quint32, uuid32);
    QFETCH(bool, constructUuid128);
    QFETCH(quint128, uuid128);

    QVERIFY(QBluetoothUuid() == QBluetoothUuid());

    if (constructUuid16) {
        QBluetoothUuid quuid16(uuid16);
        QBluetoothUuid quuid32(uuid32);
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid16 == quuid16);
        QVERIFY(quuid16 == quuid32);
        QVERIFY(quuid16 == quuid128);

        QVERIFY(quuid32 == quuid16);
        QVERIFY(quuid128 == quuid16);
    }

    if (constructUuid32) {
        QBluetoothUuid quuid32(uuid32);
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid32 == quuid32);
        QVERIFY(quuid32 == quuid128);

        QVERIFY(quuid128 == quuid32);
    }

    if (constructUuid128) {
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid128 == quuid128);
    }
}

QTEST_MAIN(tst_QBluetoothUuid)

#include "tst_qbluetoothuuid.moc"
<commit_msg>Symbian: Added more construcror test cases in qbluetootuuid unit test<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QUuid>

#include <QDebug>

#include <qbluetoothuuid.h>

#include <arpa/inet.h>
#include <netinet/in.h>

QTM_USE_NAMESPACE

Q_DECLARE_METATYPE(quint128)

class tst_QBluetoothUuid : public QObject
{
    Q_OBJECT

public:
    tst_QBluetoothUuid();
    ~tst_QBluetoothUuid();

private slots:
    void initTestCase();

    void tst_construction();
    void tst_assignment();
    void tst_conversion_data();
    void tst_conversion();
    void tst_comparison_data();
    void tst_comparison();
};

tst_QBluetoothUuid::tst_QBluetoothUuid()
{
    qRegisterMetaType<quint128>("quint128");
}

tst_QBluetoothUuid::~tst_QBluetoothUuid()
{
}

void tst_QBluetoothUuid::initTestCase()
{
}

void tst_QBluetoothUuid::tst_construction()
{
    {
        QBluetoothUuid nullUuid;

        QVERIFY(nullUuid.isNull());
    }

    {
        QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

        QVERIFY(!uuid.isNull());

        bool ok;
        quint16 uuid16;

        uuid16 = uuid.toUInt16(&ok);

        QVERIFY(ok);
        QCOMPARE(uuid16, static_cast<quint16>(QBluetoothUuid::PublicBrowseGroup));
    }

    {
        QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

        QBluetoothUuid copy(uuid);

        QCOMPARE(uuid.toUInt16(), copy.toUInt16());
    }

    {
        QBluetoothUuid uuid(QBluetoothUuid::L2cap);

        QVERIFY(!uuid.isNull());

        bool ok;
        quint16 uuid16;

        uuid16 = uuid.toUInt16(&ok);

        QVERIFY(ok);
        QCOMPARE(uuid16, static_cast<quint16>(QBluetoothUuid::L2cap));
    }

    {
        QUuid uuid(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee);
        QBluetoothUuid btUuid(uuid);
        QVERIFY(!btUuid.isNull());

        QString uuidString(btUuid.toString());
        QVERIFY(!uuidString.isEmpty());
        QCOMPARE(uuidString, QString("{67c8770b-44f1-410a-ab9a-f9b5446f13ee}"));
    }
}

void tst_QBluetoothUuid::tst_assignment()
{
    QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup);

    {
        QBluetoothUuid copy = uuid;

        QCOMPARE(uuid.toUInt16(), copy.toUInt16());
    }

    {
        QBluetoothUuid copy1;
        QBluetoothUuid copy2;

        QVERIFY(copy1.isNull());
        QVERIFY(copy2.isNull());

        copy1 = copy2 = uuid;

        QVERIFY(!copy1.isNull());
        QVERIFY(!copy2.isNull());

        QCOMPARE(uuid.toUInt16(), copy1.toUInt16());
        QCOMPARE(uuid.toUInt16(), copy2.toUInt16());
    }
}

#define BASEUUID "-0000-1000-8000-00805F9B34FB"

#define UUID128_32(x, a, b, c, d) \
    quint128 x = { \
        { \
            a, b, c, d, \
            0x00, 0x00, \
            0x10, 0x00, \
            0x80, 0x00, \
            0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB \
        } \
    }

#define UUID128_16(x, a, b) UUID128_32(x, 0, 0, a, b)

#define NEWROW16(text, a, b, s) \
do { \
    UUID128_16(uuid128, a, b); \
    quint32 uuid32 = a << 8 | b; \
    quint16 uuid16 = a << 8 | b; \
    QTest::newRow(text) << true << uuid16 << true << uuid32 << true << uuid128 \
                        << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \
} while (0)

#define NEWROW32(text, a, b, c, d, s) \
do { \
    UUID128_32(uuid128, a, b, c, d); \
    quint32 uuid32 = a << 24 | b << 16 | c << 8 | d; \
    quint16 uuid16; \
    bool constructUuid16 = (a == 0) && (b == 0); \
    if (constructUuid16) \
        uuid16 = c << 8 | d; \
    else \
        uuid16 = 0; \
    QTest::newRow(text) << constructUuid16 << uuid16 << true << uuid32 << true << uuid128 \
                        << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \
} while (0)

void tst_QBluetoothUuid::tst_conversion_data()
{
    QTest::addColumn<bool>("constructUuid16");
    QTest::addColumn<quint16>("uuid16");
    QTest::addColumn<bool>("constructUuid32");
    QTest::addColumn<quint32>("uuid32");
    QTest::addColumn<bool>("constructUuid128");
    QTest::addColumn<quint128>("uuid128");
    QTest::addColumn<QString>("uuidS");

    NEWROW32("base uuid", 0x00, 0x00, 0x00, 0x00, "00000000" BASEUUID);
    NEWROW16("0x0001", 0x00, 0x01, "00000001" BASEUUID);
    NEWROW16("0xffff", 0xff, 0xff, "0000FFFF" BASEUUID);
    NEWROW32("0x00010000", 0x00, 0x01, 0x00, 0x00, "00010000" BASEUUID);
    NEWROW32("0x0001ffff", 0x00, 0x01, 0xff, 0xff, "0001FFFF" BASEUUID);
    NEWROW32("0xffff0000", 0xff, 0xff, 0x00, 0x00, "FFFF0000" BASEUUID);
    NEWROW32("0xffffffff", 0xff, 0xff, 0xff, 0xff, "FFFFFFFF" BASEUUID);

    {
        quint128 uuid128 = {
            {
                0x00, 0x11, 0x22, 0x33,
                0x44, 0x55,
                0x66, 0x77,
                0x88, 0x99,
                0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
            }
        };

        QTest::newRow("00112233-4455-6677-8899-AABBCCDDEEFF")
            << false << quint16(0) << false << quint32(0) << true << uuid128
            << QString(QLatin1String("{00112233-4455-6677-8899-AABBCCDDEEFF}"));
    }
}

void tst_QBluetoothUuid::tst_conversion()
{
    QFETCH(bool, constructUuid16);
    QFETCH(quint16, uuid16);
    QFETCH(bool, constructUuid32);
    QFETCH(quint32, uuid32);
    QFETCH(bool, constructUuid128);
    QFETCH(quint128, uuid128);
    QFETCH(QString, uuidS);

    int minimumSize = 16;
    if (constructUuid16)
        minimumSize = 2;
    else if (constructUuid32)
        minimumSize = 4;

    if (constructUuid16) {
        QBluetoothUuid uuid(uuid16);

        bool ok;

        QCOMPARE(uuid.toUInt16(&ok), uuid16);
        QVERIFY(ok);

        QCOMPARE(uuid.toUInt32(&ok), uuid32);
        QVERIFY(ok);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }

    if (constructUuid32) {
        QBluetoothUuid uuid(uuid32);

        bool ok;

        quint16 tmp = uuid.toUInt16(&ok);
        QCOMPARE(ok, constructUuid16);
        if (ok) {
            QCOMPARE(tmp, uuid16);
        }

        QCOMPARE(uuid.toUInt32(&ok), uuid32);
        QVERIFY(ok);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }

    if (constructUuid128) {
        QBluetoothUuid uuid(uuid128);

        bool ok;

        quint16 tmpUuid16 = uuid.toUInt16(&ok);
        QCOMPARE(ok, constructUuid16);
        if (ok)
            QCOMPARE(tmpUuid16, uuid16);

        quint32 tmpUuid32 = uuid.toUInt32(&ok);
        QCOMPARE(ok, constructUuid32);
        if (ok)
            QCOMPARE(tmpUuid32, uuid32);

        QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0);

        QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper());

        QCOMPARE(uuid.minimumSize(), minimumSize);
    }
}

void tst_QBluetoothUuid::tst_comparison_data()
{
    tst_conversion_data();
}

void tst_QBluetoothUuid::tst_comparison()
{
    QFETCH(bool, constructUuid16);
    QFETCH(quint16, uuid16);
    QFETCH(bool, constructUuid32);
    QFETCH(quint32, uuid32);
    QFETCH(bool, constructUuid128);
    QFETCH(quint128, uuid128);

    QVERIFY(QBluetoothUuid() == QBluetoothUuid());

    if (constructUuid16) {
        QBluetoothUuid quuid16(uuid16);
        QBluetoothUuid quuid32(uuid32);
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid16 == quuid16);
        QVERIFY(quuid16 == quuid32);
        QVERIFY(quuid16 == quuid128);

        QVERIFY(quuid32 == quuid16);
        QVERIFY(quuid128 == quuid16);
    }

    if (constructUuid32) {
        QBluetoothUuid quuid32(uuid32);
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid32 == quuid32);
        QVERIFY(quuid32 == quuid128);

        QVERIFY(quuid128 == quuid32);
    }

    if (constructUuid128) {
        QBluetoothUuid quuid128(uuid128);

        QVERIFY(quuid128 == quuid128);
    }
}

QTEST_MAIN(tst_QBluetoothUuid)

#include "tst_qbluetoothuuid.moc"
<|endoftext|>


<commit_before>//===--- AMDGPU.cpp - AMDGPU ToolChain Implementations ----------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "AMDGPU.h"
#include "InputInfo.h"
#include "CommonArgs.h"
#include "clang/Driver/Compilation.h"
#include "llvm/Option/ArgList.h"

using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang::driver::toolchains;
using namespace clang;
using namespace llvm::opt;

void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
                                  const InputInfo &Output,
                                  const InputInfoList &Inputs,
                                  const ArgList &Args,
                                  const char *LinkingOutput) const {

  std::string Linker = getToolChain().GetProgramPath(getShortName());
  ArgStringList CmdArgs;
  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  CmdArgs.push_back("-shared");
  CmdArgs.push_back("-o");
  CmdArgs.push_back(Output.getFilename());
  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
                                          CmdArgs, Inputs));
}

/// AMDGPU Toolchain
AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
                                 const ArgList &Args)
  : Generic_ELF(D, Triple, Args) { }

Tool *AMDGPUToolChain::buildLinker() const {
  return new tools::amdgpu::Linker(*this);
}
<commit_msg>Test commit<commit_after>//===--- AMDGPU.cpp - AMDGPU ToolChain Implementations ----------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "AMDGPU.h"
#include "InputInfo.h"
#include "CommonArgs.h"
#include "clang/Driver/Compilation.h"
#include "llvm/Option/ArgList.h"

using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang::driver::toolchains;
using namespace clang;
using namespace llvm::opt;

void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
                                  const InputInfo &Output,
                                  const InputInfoList &Inputs,
                                  const ArgList &Args,
                                  const char *LinkingOutput) const {

  std::string Linker = getToolChain().GetProgramPath(getShortName());
  ArgStringList CmdArgs;
  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  CmdArgs.push_back("-shared");
  CmdArgs.push_back("-o");
  CmdArgs.push_back(Output.getFilename());
  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
                                          CmdArgs, Inputs));
}

/// AMDGPU Toolchain
AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
                                 const ArgList &Args)
  : Generic_ELF(D, Triple, Args) { }

Tool *AMDGPUToolChain::buildLinker() const {
  return new tools::amdgpu::Linker(*this);
}
<|endoftext|>