void SaveDataToFile(Metrics &metrics, int chooseAlgorithm, int chooseHeuristic) { ofstream saveFile; saveFile.open("Metrics/metrics000.txt"); //Which algorithm is used saveFile << "Algorithm used: "; switch (chooseAlgorithm) { case 0: saveFile << "A Star. "; break; case 1: saveFile << "Theta Star. "; break; case 2: saveFile << "HPA Star. "; break; case 3: saveFile << "IDA Star. "; break; default: saveFile << "Does not exist"; break; } //In combination with which heuristic is being used saveFile << "\nHeuristic used: "; switch (chooseHeuristic) { case 0: saveFile << "Manhattan. "; break; case 1: saveFile << "Chebyshev. "; break; case 2: saveFile << "Octile. "; break; case 3: saveFile << "Euclidean. "; break; default: saveFile << "Does not exist"; break; } //The number of opened nodes by the algorithm saveFile << "\nNumber of opened nodes: " << metrics.getNrOfOpenedNodes(); saveFile << "\nNumber of expanded nodes: " << metrics.getNrOfExpandedNodes(); //TODO Lägg till grejer här som metrics kan mäta }
void MetricsAction(const CMDOptions& options) { DotReader parser; DotGraph g = parser.ReadGraph(options.getOption("")); Metrics m; m.Compute(g); m.Output(options.getOption("-o")); }
int main(int argc, char* argv[]) { if (argc != 3) { displayUsage(); return 1; } unsigned short port = static_cast<unsigned short>(strtoul(argv[2], NULL, 10)); s_shutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (s_shutdownEvent == NULL) { return 1; } if (!SetConsoleCtrlHandler(&consoleCtrlHandler, TRUE)) { return 1; } // Startup the communication library int err = CLStartup(); if (err != CL_ERR_OK) { std::cout << "\r\nCLStartup() failed, err=" << err << "\r\n" << std::flush; return 1; } // Create the listening socket CLSrvSocket srvSkt = 0; err = CLCreateSrvSocket(argv[1], port, conPending, srvSocketClosed, 200, NULL, &srvSkt); if (err == CL_ERR_OK) { static const DWORD DISPLAY_INTERVAL = 5 * 60 * 1000; // 5 mins while (WaitForSingleObject(s_shutdownEvent, DISPLAY_INTERVAL) != WAIT_OBJECT_0) { s_metrics.displayMetrics(); } } else { std::cout << "\r\nCLCreateSrvSocket() failed, err=" << err << "\r\n" << std::flush; } // Cleanup the communication library CLCleanup(); s_metrics.displayMetrics(); return 0; }
bool Metrics::IsLessThan(Metrics other, char mode) { if (mode == 's') return (data[0] < other.GetMetric(0)); else if (mode == 'c') { if (data[0] < other.GetMetric(0) && data[1] < other.GetMetric(1)) return true; else return false; } }
void showMetrics(const Metrics& metrics, String pre) { std::cout << "========================================================" << std::endl; std::cout << pre << std::endl; std::cout << "========================================================" << std::endl; std::cout << "\tLoss = " << metrics.getLoss() << std::endl; std::cout << "\tCost = " << metrics.getCost() << std::endl; std::cout << "\tError = " << 100. * metrics.getError() << std::endl; std::cout << "--------------------------------------------------------" << std::endl; }
void dataRecv(CLSocket skt, const char* buf, int len, void* arg) { s_metrics.updateRecvThroughput(len); // Echo the string back to the client int err = CLSendData(skt, buf, len); if (err == CL_ERR_OK) { s_metrics.updateSendThroughput(len); } else { s_metrics.incErrorCount(Metrics::SEND_DATA, err); } }
bool IDAStar::findPath(Metrics& metrics) { float g = 0.0f; _nrOfPathNodes = 0; //It's 1 because there's an offset in the loop later. Vec2D currentPos = _start; float threshold = getHeuristicDistance(_start, _goal); while (currentPos != _goal) { currentPos = evaluateNode(_start, 0.0f, threshold); threshold = _grid[currentPos._x][currentPos._y]._gCost + getHeuristicDistance(currentPos, _goal); if (threshold >= _width * _height || !isPositionValid(currentPos)) { return false; } } while (currentPos != _start) //traces the route back to start { _nrOfPathNodes++; currentPos = _grid[currentPos._x][currentPos._y]._parent->_position; } _path = new Vec2D[_nrOfPathNodes]; int c = 0; currentPos = _goal; while (currentPos != _start) //traces the route back to start { _path[c++] = currentPos; currentPos = _grid[currentPos._x][currentPos._y]._parent->_position; } metrics.setPathNodes(_path, _nrOfPathNodes, _grid[_goal._x][_goal._y]._gCost); return true; }
void conPending(CLSrvSocket srvSkt, void* srvArg) { // We have a connection pending from the client. Accept the connection char clientIpAddr[80]; int clientIpAddrLen = sizeof(clientIpAddr); unsigned short clientPort = 0; CLSocket clientSkt = 0; int err = CLAcceptCon(srvSkt, dataRecv, socketClosed, NULL, &clientSkt, clientIpAddr, clientIpAddrLen, &clientPort); if (err == CL_ERR_OK) { s_metrics.incAcceptedCons(); } else { s_metrics.incErrorCount(Metrics::ACCEPT_CON, err); } }
void LoopTick(bool first) { if (!tSock) return; if (first) { // Triggered from the timer metrics.lastLoopTime = std::clock(); ServerInstance->AtomicActions.AddAction(action); } else if (metrics.lastLoopTime) { // Triggered from the atomic call metrics.addLoopTime(std::clock()); } }
void StopMetrics(bool error = false) { ServerInstance->GlobalCulls.AddItem(tSock); if (!silent) { if (!error) { ServerInstance->SNO->WriteGlobalSno('a', "METRICS: Telegraf metrics stopped."); } else { ServerInstance->SNO->WriteGlobalSno('a', "METRICS: Socket error occurred: %s", tSock->getError().c_str()); } } tSock = NULL; metrics.clear(); }
bool ThetaStar::findPath(Metrics& metrics) { if (_goal == _start) { return false; } _nrOfPathNodes = 0; //It's 1 because there's an offset in the loop later. Vec2D currentPos = _start; _grid[_start._x][_start._y]._open = 2; while (currentPos != _goal) //loops until a path has been found { metrics.addExpandedNode(currentPos); for (int i = 0; i < 8 && (_heuristicType != MANHATTAN || i < 4); i++) //Manhattan skips diagonals { Vec2D checkedPos = currentPos + NEIGHBOUR_OFFSETS[i]; if (isPositionValid(checkedPos) && _grid[checkedPos._x][checkedPos._y]._open != 2 && _grid[checkedPos._x][checkedPos._y]._traversable && //checks for borders and already visited (_grid[checkedPos._x][currentPos._y]._traversable || _grid[currentPos._x][checkedPos._y]._traversable)) //checks for corners { bool openedBefore = true; if (_grid[checkedPos._x][checkedPos._y]._open == 0) //check that node is not already in open list { calculateHCost(checkedPos); //As the program works now, h must be calculated before g. openedBefore = false; } if (_grid[currentPos._x][currentPos._y]._parent != nullptr) { Vec2D parentPos = _grid[currentPos._x][currentPos._y]._parent->_position; if (lineOfSightRay(parentPos, checkedPos)) { calculateGCost(parentPos, checkedPos); } else { calculateGCost(currentPos, checkedPos); } } else { calculateGCost(currentPos, checkedPos); } if (!openedBefore && _grid[checkedPos._x][checkedPos._y]._open == 1) //Check that node was added to open list { metrics.addOpenedNode(checkedPos); } } } if (_openQueue.size() <= 0) { return false; } else { currentPos = _openQueue.removeMin()->_position; while (_grid[currentPos._x][currentPos._y]._open == 2) { if (_openQueue.size() <= 0) { return false; } currentPos = _openQueue.removeMin()->_position; } _grid[currentPos._x][currentPos._y]._open = 2; } } while (currentPos != _start) //traces the route back to start { _nrOfPathNodes++; currentPos = _grid[currentPos._x][currentPos._y]._parent->_position; } _path = new Vec2D[_nrOfPathNodes]; int c = 0; currentPos = _goal; while (currentPos != _start) //traces the route back to start { _path[c++] = currentPos; currentPos = _grid[currentPos._x][currentPos._y]._parent->_position; } // _path[c++] = currentPos; //Excluding start position since it should already be known metrics.setPathNodes(_path, _nrOfPathNodes, _grid[_goal._x][_goal._y]._gCost); return true; }
PartGeometry::PartGeometry(const dom::Part& part, const ScoreProperties& scoreProperties, const Metrics& metrics) : _part(part), _scoreProperties(scoreProperties), _metrics(metrics) { _staffDistance = metrics.staffDistance(); }
int main(int argc, char** argv) { try { Params params(argc, argv); String modelFile = params("embed"); String trainFile = params("train"); String evalFile = params("eval"); const double Lambda = 1e-4; const double Eta = 0.1; int epochs = valueOf<int>(params("epochs", "5")); std::cout << "Model file: " << modelFile << std::endl; SumEmbeddedDatasetReader reader(modelFile); long l0 = sgdtk::currentTimeSeconds(); auto trainingSet = reader.load(trainFile); #ifdef __DEBUG // Shuffle deterministically WeightHacks::shuffle(trainingSet); #else std::random_shuffle(trainingSet.begin(), trainingSet.end()); #endif double elapsed = sgdtk::currentTimeSeconds() - l0; std::cout << "Training data (" << trainingSet.size() << " examples) + loaded in " << elapsed << "s" << std::endl; trainingSet.resize(30000); std::vector<FeatureVector*> evalSet; if (!evalFile.empty()) { evalSet = reader.load(evalFile); #ifdef __DEBUG // Shuffle deterministically WeightHacks::shuffle(evalSet); #else std::random_shuffle(evalSet.begin(), evalSet.end()); #endif evalSet.resize(3590); } int vSz = reader.getLargestVectorSeen(); Learner* learner = nullptr; if (params("type", "nbow") == "nbow") { learner = new SGDLearner(new LogLoss, Lambda, Eta, new NeuralNetModelFactory<>({ new FullyConnectedLayer(100, vSz), new TanhLayer(), new FullyConnectedLayer(1, 100), new TanhLayer() })); } else { learner = new SGDLearner(new LogLoss(), Lambda, Eta, new LinearModelFactory()); } Model* model = learner->create(&vSz); double totalTrainingElapsed = 0.; for (int i = 0; i < epochs; ++i) { std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl; std::cout << "EPOCH: " << (i + 1) << std::endl; Metrics metrics; double t0 = sgdtk::currentTimeSeconds(); learner->trainEpoch(model, trainingSet);//trainingSet.subList(0, 1000)); double elapsedThisEpoch = sgdtk::currentTimeSeconds() - t0; std::cout << "Epoch training time " << elapsedThisEpoch << "s" << std::endl; totalTrainingElapsed += elapsedThisEpoch; learner->eval(model, trainingSet, metrics); showMetrics(metrics, "Training Set Eval Metrics"); metrics.clear(); if (!evalSet.empty()) { //evaluate(evalSet, model); learner->eval(model, evalSet, metrics); showMetrics(metrics, "Test Set Eval Metrics"); metrics.clear(); } } std::cout << "Total training time " << totalTrainingElapsed << "s" << std::endl; for (auto x : trainingSet) { delete x; } for (auto x : evalSet) { delete x; } delete learner; delete model; } catch (Exception& ex) { std::cout << "Exception: " << ex.getMessage() << std::endl; } return 0; }
int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); int timer = 0; MapReader mr = MapReader(); //Map data string* map = nullptr; //map = mr.ReadMap("Maps/Randomized128x128-29-0.map"); map = mr.ReadMap("Maps/maze512-1-1.map"); //map = mr.ReadMap("Maps/adaptive-depth-1.map"); //map = mr.ReadMap("Maps/32room_008.map"); //map = GenerateMap(10, 10, 1.0f, mr); int width = mr.GetWidth(); int height = mr.GetHeight(); int nrOfWalls = mr.GetNrOfWalls(map); Vec2D startPos = {1, 1}; Vec2D goalPos = {width-1, height-1}; int clusterSize = 16; Vec2D* wallPos = new Vec2D[nrOfWalls]; sf::RectangleShape* walls = new sf::RectangleShape[nrOfWalls]; AStarNode** grid = nullptr; if (map != nullptr) { if (width > 0 && height > 0) { grid = new AStarNode*[width]; //Initiate the grid** with walkable or non-walkable tiles int wallCounter = 0; for (int i = 0; i < width; i++) { grid[i] = new AStarNode[height]; for (int j = 0; j < height; j++) { grid[i][j] = AStarNode(i, j); if (map[j*width + i] != "@") { grid[i][j]._traversable = true; } else { grid[i][j]._traversable = false; walls[wallCounter] = sf::RectangleShape(sf::Vector2f((float)tileWidth, (float)tileHeight)); walls[wallCounter].setFillColor(sf::Color::White); walls[wallCounter].setPosition(sf::Vector2f(10.0f + (float)(tileWidth * i), 10.0f + (float)(tileHeight * j))); wallCounter++; } } } } } sf::View view; view.setCenter(0.5f * width * tileWidth, 0.5f * height * tileHeight); view.setSize(1.6f * width * tileWidth, 1.2f * height * tileHeight); sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "AI test"); window.setFramerateLimit(60); window.setView(view); ImGui::SFML::SetRenderTarget(window); ImGui::SFML::InitImGuiRendering(); ImGui::SFML::SetWindow(window); ImGui::SFML::InitImGuiEvents(); sf::RectangleShape* openedTiles = nullptr; sf::RectangleShape* expandedTiles = nullptr; sf::Vertex* pathTiles = nullptr; //Mainly for the highlevel graph of HPA* sf::Vertex* abstractGraph = nullptr; sf::Vertex* openedGraph = nullptr; sf::Vertex* expandedGraph = nullptr; Metrics metrics; sf::CircleShape startNode = sf::CircleShape(0.4f*tileHeight); startNode.setPosition(sf::Vector2f(10.0f + startPos._x * (float)tileWidth, 10.0f + startPos._y * (float)tileHeight)); startNode.setFillColor(sf::Color::Red); sf::CircleShape goalNode = sf::CircleShape(0.4f*tileHeight);; goalNode.setPosition(sf::Vector2f(10.0f + goalPos._x * (float)tileWidth, 10.0f + goalPos._y * (float)tileHeight)); goalNode.setFillColor(sf::Color::Yellow); //Other variables bool calculatePaths = false; int choosePathfinding = 0; int chooseHeuristic = 0; //Movement variable int delta = width * 0.05f; float blockSize = 32.0f; //Randomize map variables bool randomizeMap = false; char widthBuffer[4] = "512"; char heightBuffer[4] = "512"; char densityBuffer[3] = "30"; //Set start/goal position variables int startOrGoal = 0; //0 == start pos, 1 == goal pos char xBuffer[4] = "0"; char yBuffer[4] = "0"; //What should be drawn? bool showWalls = false; bool showExpandedNodes = false; bool showOpenedNodes = false; while (window.isOpen()) { ImGui::SFML::UpdateImGui(); ImGui::SFML::UpdateImGuiRendering(); sf::Event event; while (window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { window.close(); } } ImGuiIO &io = ImGui::GetIO(); //ImGui::ShowTestWindow(); window.clear(); /**************************************/ /* Start of GUI code */ /**************************************/ if (ImGui::CollapsingHeader("Choose pathfinding")) { ImGui::RadioButton("A*", &choosePathfinding, 0); ImGui::SameLine(); ImGui::RadioButton("Theta*", &choosePathfinding, 1); ImGui::SameLine(); ImGui::RadioButton("HPA*", &choosePathfinding, 2); ImGui::SameLine(); ImGui::RadioButton("IDA*", &choosePathfinding, 3); ImGui::SameLine(); ImGui::RadioButton("Dijkstra", &choosePathfinding, 4); ImGui::RadioButton("Manhattan", &chooseHeuristic, 0); ImGui::SameLine(); ImGui::RadioButton("Chebyshev", &chooseHeuristic, 1); ImGui::SameLine(); ImGui::RadioButton("Octile", &chooseHeuristic, 2); ImGui::SameLine(); ImGui::RadioButton("Euclidean", &chooseHeuristic, 3); } if (ImGui::CollapsingHeader("Randomize a map")) { //Set width, height and obstacle density ImGui::InputText("Width", widthBuffer, IM_ARRAYSIZE(widthBuffer)); ImGui::InputText("Height", heightBuffer, IM_ARRAYSIZE(heightBuffer)); ImGui::InputText("Density (%)", densityBuffer, IM_ARRAYSIZE(densityBuffer)); if (ImGui::SmallButton("Generate map")) { mr.GenerateRandomMap(stoi(string(widthBuffer)), stoi(string(heightBuffer)), 0.01f*stof(string(densityBuffer))); } } if (ImGui::CollapsingHeader("Set start/goal")) { ImGui::RadioButton("Set start position", &startOrGoal, 0); ImGui::SameLine(); ImGui::RadioButton("Set goal position", &startOrGoal, 1); //Set xPos and yPos ImGui::InputText("X position", xBuffer, IM_ARRAYSIZE(xBuffer)); ImGui::InputText("Y position", yBuffer, IM_ARRAYSIZE(yBuffer)); if (ImGui::SmallButton("Set position")) { Vec2D pos = {stoi(string(xBuffer)), stoi(string(yBuffer))}; if (startOrGoal == 0) //Start pos { startPos = pos; startNode.setPosition(sf::Vector2f(10.0f + startPos._x * (float)tileWidth, 10.0f + startPos._y * (float)tileHeight)); } else if (startOrGoal == 1) //Goal pos { goalPos = pos; goalNode.setPosition(sf::Vector2f(10.0f + goalPos._x * (float)tileWidth, 10.0f + goalPos._y * (float)tileHeight)); } } } if (ImGui::CollapsingHeader("Choose what will be drawn")) { ImGui::Checkbox("Walls", &showWalls); ImGui::Checkbox("Opened nodes", &showOpenedNodes); ImGui::Checkbox("Expanded nodes", &showExpandedNodes); } if (ImGui::SmallButton("Calculate paths")) { calculatePaths = !calculatePaths; } /**************************************/ /* End of GUI code */ /**************************************/ //Moving of the camera if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) //Move camera west { view.setCenter(view.getCenter().x, view.getCenter().y - delta); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) //Move camera east { view.setCenter(view.getCenter().x - delta, view.getCenter().y); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) //Move camera south { view.setCenter(view.getCenter().x, view.getCenter().y + delta); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) //Move camera north { view.setCenter(view.getCenter().x + delta, view.getCenter().y); } //Zooming with the camera if (sf::Keyboard::isKeyPressed(sf::Keyboard::PageUp) && blockSize <= 32.0f) //Zoom out { view.setSize(sf::Vector2f(width * tileWidth * blockSize++ * 0.05f, height * tileHeight * blockSize++ * 0.0375f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::PageDown) && blockSize >= 1.0f) //Zoom in { view.setSize(sf::Vector2f(width * tileWidth * blockSize-- * 0.05f, height * tileHeight * blockSize-- * 0.0375f)); } window.setView(view); //Calculate pathfinding if (calculatePaths) { metrics.clean(); switch (choosePathfinding) { case 0: //A* CalculateAStar(metrics, (Pathfinding::Heuristic)chooseHeuristic, width, height, startPos, goalPos, grid); break; case 1: //Theta* CalculateThetaStar(metrics, (Pathfinding::Heuristic)chooseHeuristic, width, height, startPos, goalPos, grid); break; case 2: //HPA* CalculateHPAStar(metrics, (Pathfinding::Heuristic)chooseHeuristic, width, height, startPos, goalPos, grid, clusterSize); break; case 3: //IDA* CalculateIDAStar(metrics, (Pathfinding::Heuristic)chooseHeuristic, width, height, startPos, goalPos, grid); break; case 4: CalculateDijkstra(metrics, (Pathfinding::Heuristic)chooseHeuristic, width, height, startPos, goalPos, grid); default: break; } if (showOpenedNodes) { if (openedTiles != nullptr) { delete[] openedTiles; } openedTiles = new sf::RectangleShape[metrics.getNrOfOpenedNodes()]; for (int i = 0; i < metrics.getNrOfOpenedNodes(); i++) { openedTiles[i] = sf::RectangleShape(sf::Vector2f((float)tileWidth, (float)tileHeight)); openedTiles[i].setFillColor(sf::Color(0, 200, 200, 120)); openedTiles[i].setPosition(sf::Vector2f(10.0f + (float)tileWidth * metrics.getOpenedNodes()[i]._x, 10.0f + (float)tileHeight * metrics.getOpenedNodes()[i]._y)); window.draw(openedTiles[i]); } } if (showExpandedNodes) { if (expandedTiles != nullptr) { delete[] expandedTiles; } expandedTiles = new sf::RectangleShape[metrics.getNrOfExpandedNodes()]; for (int i = 0; i < metrics.getNrOfExpandedNodes(); i++) { expandedTiles[i] = sf::RectangleShape(sf::Vector2f((float)tileWidth, (float)tileHeight)); expandedTiles[i].setFillColor(sf::Color(200, 0, 0, 120)); expandedTiles[i].setPosition(sf::Vector2f(10.0f + (float)tileWidth * metrics.getExpandedNodes()[i]._x, 10.0f + (float)tileHeight * metrics.getExpandedNodes()[i]._y)); window.draw(expandedTiles[i]); } } if (pathTiles != nullptr) { delete[] pathTiles; } pathTiles = new sf::Vertex[metrics.getNrOfPathNodes() + 1]; for (int i = 0; i < metrics.getNrOfPathNodes(); i++) { pathTiles[i] = sf::Vertex(sf::Vector2f(10.0f + (float)tileWidth * (metrics.getPathNodes()[i]._x + 0.5f), 10.0f + (float)tileHeight * (metrics.getPathNodes()[i]._y + 0.5f))); pathTiles[i].color = sf::Color(200, 0, 200, 255); } pathTiles[metrics.getNrOfPathNodes()] = sf::Vector2f(10.0f + (float)tileWidth * (startPos._x + 0.5f), 10.0f + (float)tileHeight * (startPos._y + 0.5f)); SaveDataToFile(metrics, choosePathfinding, chooseHeuristic); calculatePaths = false; } //Draw the start and goal node(s) window.draw(startNode); window.draw(goalNode); if (choosePathfinding == 2) //Special case for HPA* { window.draw(abstractGraph, metrics.getNrOfGraphNodes(), sf::Lines); if (showOpenedNodes) { window.draw(openedGraph, metrics.getNrOfOpenedNodes(), sf::Lines); } if (showExpandedNodes) { window.draw(expandedGraph, metrics.getNrOfExpandedNodes(), sf::Lines); } } else { if (showOpenedNodes && openedTiles != nullptr) { for (int i = 0; i < metrics.getNrOfOpenedNodes(); i++) { window.draw(openedTiles[i]); } } if (showExpandedNodes) { for (int i = 0; i < metrics.getNrOfExpandedNodes(); i++) { window.draw(expandedTiles[i]); } } } window.draw(pathTiles, metrics.getNrOfPathNodes() + 1, sf::LinesStrip); //Draw all the walls if (showWalls) { for (int i = 0; i < nrOfWalls; i++) { window.draw(walls[i]); } } ImGui::Render(); window.display(); } delete[] expandedTiles; delete[] openedTiles; delete[] pathTiles; delete[] walls; delete[] map; delete[] wallPos; for (__int16 i = 0; i < width; i++) { delete[] grid[i]; } delete[] grid; ImGui::SFML::Shutdown(); return 0; }