void evaluate_bfs() { Maze maze(9, 9); maze.buildMaze(); BFS bfs; Plot *begin(maze.getPlot(0, 0)); Plot *goal(maze.getPlot(8, 8)); std::cout << "BFS" << std::endl << "begin: " << begin << std::endl; bool res = begin == goal; std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); auto node = bfs.search(maze.maze, *begin, *goal, maze.getMaxPlots()); end = std::chrono::system_clock::now(); int elapsed_seconds = std::chrono::duration_cast<std::chrono::nanoseconds> (end-start).count(); std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "path.length: " << node->x << "=> (" << node->node->x << ", " << node->node->y << ")" << std::endl; std::cout << "finished computation at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds << "s\n"; }
double Components::perform_connected_compontents(SearchInputType search_input_type_) { cout << endl << "Count connected components of graph "; double components = 0.; DFS * dfs; BFS * bfs; switch(search_input_type_){ case enum_DFS : dfs = new DFS (_graph, _debug); cout << "with DFS." << endl; break; case enum_BFS : bfs = new BFS (_graph, _debug); cout << "with BFS." << endl; break; } vector<Node *> nodes = _graph->get_nodes(); vector<Node *> visited_nodes; vector<Node *> found_nodes; for (size_t i = 0; i < nodes.size(); i++) { vector<Node *>::iterator it; it = find (visited_nodes.begin(), visited_nodes.end(), nodes[i]); if(it == visited_nodes.end()){ //No node found => not visited yet components++; switch(search_input_type_){ case enum_DFS : dfs->perform_recursive_DFS(i); found_nodes = dfs->get_found_nodes(); break; case enum_BFS : bfs->perform_iterative_BFS(i); found_nodes = bfs->get_found_nodes(); break; } visited_nodes.insert(visited_nodes.end(),found_nodes.begin(),found_nodes.end()); } } cout << endl << "The graph has " << components << " connected components." << endl; }
void main() { std::cout << "==== ALGORITHM REVIEW ====" << std::endl; //create a small tree Node<int> Root; Root.Data = 1; Root.ID = "root node"; Node<int> LeftRoot; LeftRoot.Data = 2; LeftRoot.Left = nullptr; LeftRoot.Right = nullptr; LeftRoot.ID = "roots left child"; Node<int> RightRoot; RightRoot.Data = 3; RightRoot.ID = "roots right child"; Root.Left = &LeftRoot; Root.Right = &RightRoot; Node<int> RightLeft; RightLeft.Data = 4; RightLeft.Left = nullptr; RightLeft.Right = nullptr; RightLeft.ID = "the left child of roots right child"; Node<int> RightRight; RightRight.Data = 5; RightRight.Left = nullptr; RightRight.Right = nullptr; RightRight.ID = "the right child of roots right child"; RightRoot.Left = &RightLeft; RightRoot.Right = &RightRight; BFS<int> bfs; std::vector<Node<int>> start; start.push_back(Root); std::cout << bfs.search(start, 2) << std::endl; std::getchar(); }
void EstimateDimension(Map *m) { // Graph *g = GraphSearchConstants::GetGraph(m); // GraphEnvironment ge(g); // std::vector<graphState> endPath; // node *n = g->GetRandomNode(); Graph *g = GraphSearchConstants::GetGraph(m); GraphEnvironment ge(g); std::vector<graphState> endPath; // 1. choose a random point node *n = g->GetRandomNode(); // 2. search to depth d (all g-costs >= d) double limit = 0; TemplateAStar<graphState, graphMove, GraphEnvironment> theSearch; theSearch.SetStopAfterGoal(false); theSearch.InitializeSearch(&ge, n->GetNum(), n->GetNum(), endPath); while (1) { double gCost; graphState s = theSearch.CheckNextNode(); theSearch.GetClosedListGCost(s, gCost); //printf("Expanding g-cost %f next\n", gCost); if (gCost >= limit) { printf("%d\t%d\n", (int)limit, theSearch.GetNodesExpanded()); limit++; } if (theSearch.DoSingleSearchStep(endPath)) break; } graphState start = n->GetNum(); BFS<graphState, graphMove> b; b.GetPath(&ge, start, start, endPath); }
int main (int argc, char* argv[]) { /** We create a command line parser. */ OptionsParser parser; parser.push_back (new OptionOneParam (STR_URI_INPUT, "graph file", true)); IProperties* params = 0; try { /** We parse the user options. */ params = parser.parse (argc, argv); } catch (OptionFailure& e) { e.getParser().displayErrors (stdout); e.getParser().displayHelp (stdout); return EXIT_FAILURE; } // We create the graph with the bank and other options Graph graph = Graph::load (params->getStr(STR_URI_INPUT)); // We create a graph marker. GraphMarker<BranchingNode> marker (graph); // We create an object for Breadth First Search for the de Bruijn graph. BFS<BranchingNode> bfs (graph); // We want to compute the distribution of connected components of the branching nodes. // - key is a connected component class (for a given number of branching nodes for this component) // - value is the number of times this component class occurs in the branching sub graph map<size_t,Entry> distrib; // We get an iterator for all nodes of the graph. We use a progress iterator to get some progress feedback ProgressGraphIterator<BranchingNode,ProgressTimer> itBranching (graph.iterator<BranchingNode>(), "statistics"); // We want to know the number of connected components size_t nbConnectedComponents = 0; // We define some kind of unique identifier for a couple (indegree,outdegree) map <InOut_t, size_t> topology; size_t simplePathSizeMin = ~0; size_t simplePathSizeMax = 0; // We want time duration of the iteration TimeInfo ti; ti.start ("compute"); // We loop the branching nodes for (itBranching.first(); !itBranching.isDone(); itBranching.next()) { // We get branching nodes neighbors for the current branching node. Graph::Vector<BranchingEdge> successors = graph.successors <BranchingEdge> (*itBranching); Graph::Vector<BranchingEdge> predecessors = graph.predecessors<BranchingEdge> (*itBranching); // We increase the occurrences number for the current couple (in/out) neighbors topology [make_pair(predecessors.size(), successors.size())] ++; // We loop the in/out neighbors and update min/max simple path size for (size_t i=0; i<successors.size(); i++) { simplePathSizeMax = std::max (simplePathSizeMax, successors[i].distance); simplePathSizeMin = std::min (simplePathSizeMin, successors[i].distance); } for (size_t i=0; i<predecessors.size(); i++) { simplePathSizeMax = std::max (simplePathSizeMax, predecessors[i].distance); simplePathSizeMin = std::min (simplePathSizeMin, predecessors[i].distance); } // We skip already visited nodes. if (marker.isMarked (*itBranching)) { continue; } // We launch the breadth first search; we get as a result the set of branching nodes in this component const set<BranchingNode>& component = bfs.run (*itBranching); // We mark the nodes for this connected component marker.mark (component); // We update our distribution distrib[component.size()].nbOccurs += 1; // We update the number of connected components. nbConnectedComponents++; } ti.stop ("compute"); // We compute the total number of branching nodes in all connected components. size_t sumOccurs = 0; size_t sumKmers = 0; for (map<size_t,Entry>::iterator it = distrib.begin(); it != distrib.end(); it++) { sumOccurs += it->first*it->second.nbOccurs; sumKmers += it->second.nbKmers; } // We sort the statistics by decreasing occurrence numbers. Since map have its own ordering, we need to put all // the data into a vector and sort it with our own sorting criteria. vector < pair<InOut_t,size_t> > stats; for (map <InOut_t, size_t>::iterator it = topology.begin(); it != topology.end(); it++) { stats.push_back (*it); } sort (stats.begin(), stats.end(), CompareFct); // Note: it must be equal to the number of branching nodes of the graph assert (sumOccurs == itBranching.size()); // We aggregate the computed information Properties props ("topology"); props.add (1, "graph"); props.add (2, "name", "%s", graph.getName().c_str()); props.add (2, "db_input", "%s", graph.getInfo().getStr("input").c_str()); props.add (2, "db_nb_seq", "%d", graph.getInfo().getInt("sequences_number")); props.add (2, "db_size", "%d", graph.getInfo().getInt("sequences_size")); props.add (2, "kmer_size", "%d", graph.getInfo().getInt("kmer_size")); props.add (2, "kmer_nks", "%d", graph.getInfo().getInt("nks")); props.add (2, "nb_nodes", "%d", graph.getInfo().getInt("kmers_nb_solid")); props.add (2, "nb_branching_nodes", "%d", graph.getInfo().getInt("nb_branching")); props.add (2, "percent_branching_nodes", "%.1f", graph.getInfo().getInt("kmers_nb_solid") > 0 ? 100.0 * (float)graph.getInfo().getInt("nb_branching") / (float) graph.getInfo().getInt("kmers_nb_solid") : 0 ); props.add (1, "branching_nodes"); props.add (2, "simple_path"); props.add (3, "size_min", "%d", simplePathSizeMin); props.add (3, "size_max", "%d", simplePathSizeMax); props.add (2, "neighborhoods"); for (size_t i=0; i<stats.size(); i++) { props.add (3, "neighborhood", "in=%d out=%d", stats[i].first.first, stats[i].first.second); props.add (4, "nb_bnodes", "%d", stats[i].second); props.add (4, "percentage", "%5.2f", itBranching.size() > 0 ? 100.0*(float)stats[i].second / (float)itBranching.size() : 0 ); } props.add (2, "connected_components"); props.add (3, "nb_classes", "%d", distrib.size()); props.add (3, "nb_components", "%d", nbConnectedComponents); for (map<size_t,Entry>::iterator it = distrib.begin(); it!=distrib.end(); it++) { props.add (3, "component_class"); props.add (4, "nb_occurs", "%d", it->second.nbOccurs); props.add (4, "nb_bnodes", "%d", it->first); props.add (4, "freq_bnodes", "%f", sumOccurs > 0 ? 100.0*(float)(it->first*it->second.nbOccurs) / (float)sumOccurs : 0 ); } props.add (1, ti.getProperties("time")); // We dump the results in a XML file in the current directory XmlDumpPropertiesVisitor v (graph.getName() + ".xml", false); props.accept (&v); return EXIT_SUCCESS; }
int main() { Graph *graph = Graph::create(9); graph_info info; info.source = 0; info.destination = 0; graph->addEdge(0, 1, 4); graph->addEdge(0, 7, 8); graph->addEdge(1, 2, 8); graph->addEdge(1, 7, 11); graph->addEdge(2, 3, 7); graph->addEdge(2, 8, 2); graph->addEdge(2, 5, 4); graph->addEdge(3, 4, 9); graph->addEdge(3, 5, 14); graph->addEdge(4, 5, 10); graph->addEdge(5, 6, 2); graph->addEdge(6, 7, 1); graph->addEdge(6, 8, 6); graph->addEdge(7, 8, 7); // DFS LOG("======== DFS start========"); DFS *dfs = DFS::create(graph, info); dfs->compute(); delete(dfs); LOG("======== DFS end========"); // BFS LOG("======== BFS start========"); BFS *bfs = BFS::create(graph, info); bfs->compute(); delete(bfs); LOG("======== BFS end========"); // dijkstra LOG("======== dijkstra start========"); dijkstra *dijkstra = dijkstra::create(graph, info); dijkstra->compute(); delete(bfs); LOG("======== dijkstra end========"); // PrimMST LOG("======== PrimMST start========"); PrimMST *prim = PrimMST::create(graph, info); prim->compute(); delete(prim); LOG("======== PrimMST end========"); // BellmanFord LOG("======== BellmanFord start========"); BellmanFord *bellman_ford = BellmanFord::create(graph, info); bellman_ford->compute(); delete(bellman_ford); LOG("======== BellmanFord end========"); // ShortestPath LOG("======== ShortestPath start========"); ShortestPath *shortest_path = ShortestPath::create(graph, info); shortest_path->compute(); delete(shortest_path); LOG("======== ShortestPath end========"); // Detect Cycle LOG("======== Detect Cycle start========"); isCyclic(graph, info); LOG("======== Detect Cycle end========"); // Detect Cycle using Disjoint set LOG("======== Detect Cycle using Disjoint set start========"); LOG(isCyclicUsingDisjointSet(graph, info)); LOG("======== Detect Cycle using Disjoint set end========"); // Graph Coloring LOG("======== Graph Coloring start========"); GraphColoring *graph_color = GraphColoring::create(graph, info); graph_color->color(); graph_color->print(); LOG("======== Graph Coloring end========"); // Hamilton Cycle LOG("======== Hamilton Cycle start========"); HamiltonCycle *hamiton = HamiltonCycle::create(graph, info); hamiton->checkHamiltonCycle(); LOG("======== Hamilton Cycle end========"); delete graph; // Directed Graph graph = Graph::create(6); graph->addDirectedEdge(0, 1); graph->addDirectedEdge(0, 5); graph->addDirectedEdge(1, 2); graph->addDirectedEdge(1, 3); graph->addDirectedEdge(1, 4); graph->addDirectedEdge(2, 3); graph->addDirectedEdge(2, 4); graph->addDirectedEdge(3, 4); graph->addDirectedEdge(5, 2); LOG("======== Topological Sort start========"); TopologicalSort *tsort = TopologicalSort::create(graph, info); tsort->sort(); tsort->print(); LOG("======== Topological Sort end========"); return 0; }
int main (int argc, char* argv[]) { /** We create a command line parser. */ OptionsParser parser ("GraphStats"); parser.push_back (new OptionOneParam (STR_URI_GRAPH, "graph input", true)); try { /** We parse the user options. */ IProperties* options = parser.parse (argc, argv); // We load the graph Graph graph = Graph::load (options->getStr(STR_URI_GRAPH)); // We create a graph marker. GraphMarker marker (graph); // We create an object for Breadth First Search for the de Bruijn graph. BFS bfs (graph); // We want to compute the distribution of connected components of the branching nodes. // - key is a connected component class (for a given number of branching nodes for this component) // - value is the number of times this component class occurs in the branching sub graph map<size_t,size_t> distrib; // We get an iterator for all nodes of the graph. We use a progress iterator to get some progress feedback ProgressGraphIterator<BranchingNode,ProgressTimer> itBranching (graph.iteratorBranching(), "statistics"); // We want time duration of the iteration TimeInfo ti; ti.start ("compute"); // We need to keep each connected component. list<set<BranchingNode> > components; // We loop the branching nodes for (itBranching.first(); !itBranching.isDone(); itBranching.next()) { // We skip already visited nodes. if (marker.isMarked (*itBranching)) { continue; } // We launch the breadth first search; we get as a result the set of branching nodes in this component const set<BranchingNode>& component = bfs.run (*itBranching); // We memorize the component components.push_back (component); // We mark the nodes for this connected component marker.mark (component); // We update our distribution distrib[component.size()] ++; } ti.stop ("compute"); // We compute the total number of branching nodes in all connected components. size_t sum = 0; for (map<size_t,size_t>::iterator it = distrib.begin(); it != distrib.end(); it++) { sum += it->first*it->second; } // Note: it must be equal to the number of branching nodes of the graph assert (sum == itBranching.size()); size_t idx1=0; size_t cc=0; // We check that each component has no intersection with all other components. // Note: this check may take a long time since we have N^2 intersections to compute. for (list<set<BranchingNode> >::iterator it1 = components.begin(); it1 != components.end(); it1++, idx1++) { size_t idx2=0; for (list<set<BranchingNode> >::iterator it2 = components.begin(); it2 != components.end(); it2++, idx2++) { if (it1 != it2) { set<BranchingNode> inter; set_intersection (it1->begin(),it1->end(),it2->begin(),it2->end(), std::inserter(inter,inter.begin())); if (inter.size()!=0) { printf ("ERROR, intersection should be empty...\n"); exit(EXIT_FAILURE); } } if (++cc % 50 == 0) { cc = 0; printf ("[check] %.1f %.1f\r", 100.0*(float)idx1/(float)components.size(), 100.0*(float)idx2/(float)components.size()); fflush (stdout); } } } printf ("\n"); // We aggregate the computed information Properties props ("connected_components"); props.add (1, "graph_name", "%s", graph.getName().c_str()); props.add (1, "nb_branching_nodes", "%d", sum); props.add (1, "nb_connected_components", "%d", distrib.size()); for (map<size_t,size_t>::iterator it = distrib.begin(); it!=distrib.end(); it++) { props.add (2, "component"); props.add (3, "nb_nodes", "%d", it->first); props.add (3, "nb_occurs", "%d", it->second); props.add (3, "freq_nodes", "%f", 100.0*(float)(it->first*it->second) / (float)sum); props.add (3, "freq_occurs", "%f", 100.0*(float)it->second / (float)sum); } props.add (1, ti.getProperties("time")); // We dump the results in a XML file in the current directory XmlDumpPropertiesVisitor v (graph.getName() + ".xml", false); props.accept (&v); } catch (OptionFailure& e) { return e.displayErrors (std::cout); } catch (Exception& e) { std::cerr << "EXCEPTION: " << e.getMessage() << std::endl; } return EXIT_SUCCESS; }
void MyStrategy::move(const Car& self, const World& world, const Game& game, Move& move) { if (!inited) { inited = true; gr = ToGrid(world.getTilesXY()); gr = gr.Transposed(); ::grid << gr; for (auto& w : world.getWaypoints()) { tiles << "col: " << w[0] << " row: " << w[1] << endl; waypoints.emplace_back(w[1], w[0]); } auto is_neighbor = [&](const Position& p, grid::Direction d) { return neighbors[static_cast<int>(gr[p])][d]; }; // shouldn't use grid at all here... or push values inside is_neighbor // but there maybe some cool logic BFS<TileType, decltype(is_neighbor)> bfs; bfs.Init(gr, is_neighbor); bfs.FindShortestPaths({14,2}, {13,13}); for (int i = 0; i < world.getWaypoints().size(); ++i) { int i_next = (i+1) % world.getWaypoints().size(); auto res = bfs.FindShortestPaths(waypoints[i], waypoints[i_next]); ways << waypoints[i] << "; " << waypoints[i_next] << endl; for (auto r : res) { for (auto p : r) { ways << p << "; "; } ways << endl; } ways << endl; } } Position next_tile{self.getNextWaypointY(), self.getNextWaypointX()}; Point target; target.x = (next_tile.col + 0.5) * game.getTrackTileSize(); target.y = (next_tile.row + 0.5) * game.getTrackTileSize(); // if (next_tile.ManhattanDistance(currentTile(self)) <= 2) { switch (world.getTilesXY()[next_tile.col][next_tile.row]) { case LEFT_TOP_CORNER: target.x += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; target.y += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; // nextWaypointX += cornerTileOffset; // nextWaypointY += cornerTileOffset; break; case RIGHT_TOP_CORNER: target.x -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); target.y += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; // nextWaypointX -= cornerTileOffset; // nextWaypointY += cornerTileOffset; break; case LEFT_BOTTOM_CORNER: target.x += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; target.y -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); // nextWaypointX += cornerTileOffset; // nextWaypointY -= cornerTileOffset; break; case RIGHT_BOTTOM_CORNER: target.x -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); target.y -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); // nextWaypointX -= cornerTileOffset; // nextWaypointY -= cornerTileOffset; break; case RIGHT_HEADED_T: break; case LEFT_HEADED_T: break; case TOP_HEADED_T: break; case BOTTOM_HEADED_T: break; case CROSSROADS: break; default: break; } // } double angleToWaypoint = self.getAngleTo(target.x, target.y); double speedModule = hypot(self.getSpeedX(), self.getSpeedY()); move.setWheelTurn(angleToWaypoint * 100. / PI); move.setEnginePower(1.); if (speedModule != prevSpeed) { stats << speedModule << endl; } prevSpeed = speedModule; if (speedModule * speedModule * abs(angleToWaypoint) > 2.5 * 2.5 * PI || speedModule > 30 ) { move.setBrake(true); } }