int main(int argc, char *argv[]) try { AdjacencyList adjacency; int num_nodes = ReadInputOrDie(argc, argv, &adjacency); std::cout << "Graph read from file: \n"; for (auto begin = adjacency.begin(); begin != adjacency.end(); begin++) { for (Edge edge : begin->second) { auto nodes = edge.GetNodes(); //don't print duplicates if (nodes[1] > nodes[0]) { edge.Print(); } } } std::cout << "Minimum Spanning Tree:\n"; SpanningTree mst(num_nodes, adjacency); if (mst.BuildMinSpanningTree()) { for (Edge edge : *mst.GetOptimalEdgeList()) { edge.Print(); } } std::cout << "MST Weight: " << mst.GetWeight() << "\n"; } catch (std::exception &e) { std::cerr << "Error: " << e.what() << "\n"; return -1; } catch (...) { std::cerr << "unknown error\n"; return -1; }
LowestCommonAncestor( int root, const AdjacencyList<EdgeType> &graph) : m_depth_table(graph.size(), -1) , m_skip_table( graph.size(), std::vector<int>(32 - __builtin_clz(graph.size()), -1)) { std::vector<int> s; build_tables(root, s, graph); }
int main(int argc, char *argv[]) { int minCutEdges = N_NODES; AdjacencyList adjList(N_NODES); std::ifstream infile; infile.open("../kargerMinCut.txt"); if (!infile) { std::cout << "Opening file failed." << std::endl; return -1; } std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int u, v; iss >> u; while (iss >> v) { if (iss.fail()) { std::cout << "Reading error or incorrect type." << std::endl; return -1; } if (u < 1 || u > N_NODES || v < 1 || v > N_NODES) { std::cout << "Vertex ID out of range" << std::endl; return -1; } adjList.insertEdge(u-1, v-1); } } SteadyClockTimer timer; timer.start(); for (int i = 0; i < ITERATIONS; ++i) { srand(i); AdjacencyList adjListCopy = adjList; while (adjListCopy.nodeCount() > 2) { adjListCopy.contractRandomEdge(); } if (adjListCopy.edgeCount() < minCutEdges) { minCutEdges = adjListCopy.edgeCount(); } } std::cout << "After " << ITERATIONS << " iterations," << std::endl; std::cout << "Possible min cut edge count is: " << minCutEdges << std::endl; std::cout << "time taken is: " << timer.getMs() << " ms" << std::endl; return 0; }
SymmetricCSlRMatrix::SymmetricCSlRMatrix(AdjacencyList const & adjList) : AbstractSparseMatrix(adjList.size(), adjList.size()) , _iptr(adjList.size() + 1) , _diag(adjList.size()) { for (size_t i = 0; i < adjList.size(); i++) _iptr[i + 1] = _iptr[i] + adjList[i].size(); _jptr.reserve(_iptr[_w]); for (size_t i = 0; i < adjList.size(); i++) for (auto neighbour : adjList[i]) _jptr.emplace_back(neighbour); _lval.resize(_iptr[_w]); }
AdjacencyList Reverse(const AdjacencyList& graph) { size_t n = graph.NumVertices(); AdjacencyList rg(n); for (Vertex u = 0; u < n; ++u) { for (const Neighbor& neighbor : graph.GetNeighbors(u)) { Vertex v; double ignored_cost; std::tie(v, ignored_cost) = neighbor; rg.AddEdge(v, u); } } return rg; }
void StronglyConnectedComponents(const AdjacencyList& graph, std::vector<int>& cc) { cc.resize(graph.NumVertices()); const AdjacencyList& reverse_graph = Reverse(graph); vector<Vertex> sorted; TopologicalSort(reverse_graph, sorted); vector<bool> visited(graph.NumVertices(), false); int cc_num = 1; for (Vertex u : sorted) { if (!visited[u]) { cc[u] = cc_num++; Explore(graph, u, visited, cc); } } }
//#################### CONSTRUCTORS #################### AdjacencyTable::AdjacencyTable(const AdjacencyList& adjList) : m_size(adjList.size()) { m_table.resize(m_size); for(int i=0; i<m_size; ++i) { m_table[i].resize(m_size, (float)INT_MAX); // use a very large weight to represent +inf (i.e. no edge) m_table[i][i] = 0.0f; const std::list<AdjacencyList::Edge>& adjEdges = adjList.adjacent_edges(i); for(std::list<AdjacencyList::Edge>::const_iterator jt=adjEdges.begin(), jend=adjEdges.end(); jt!=jend; ++jt) { m_table[i][jt->to_node()] = jt->length(); } } }
std::vector<int> compute_subtree_size( const AdjacencyList<EdgeType> &conn, int root) const { const int n = conn.size(); std::vector<int> subtree_size(n); std::vector<bool> passed(n), gathered(n); std::stack<pii> count_stack; count_stack.push(pii(root, 0)); while(!count_stack.empty()){ const pii p = count_stack.top(); count_stack.pop(); const int u = p.first, i = p.second; if(i == 0){ passed[u] = true; count_stack.push(pii(u, 1)); for(size_t j = 0; j < conn[u].size(); ++j){ const int v = conn[u][j].to; if(passed[v]){ continue; } count_stack.push(pii(v, 0)); } }else{ int sum = 1; gathered[u] = true; for(size_t j = 0; j < conn[u].size(); ++j){ const int v = conn[u][j].to; if(!gathered[v]){ continue; } sum += subtree_size[v]; } subtree_size[u] = sum; } } return subtree_size; }
unsigned int min_distance(const AdjacencyList& graph) { vector<unsigned int> distances(graph.size(), infinity); MinHeap cut; distances[0] = 0; cut.push(make_pair(0, 0)); while (!cut.empty()) { unsigned int closest = cut.top().second; unsigned int to_closest = cut.top().first; cut.pop(); if (distances[closest] < to_closest) { continue; } for (unsigned int i = 0; i < graph[closest].size(); ++i) { unsigned int adjacent = graph[closest][i].first; unsigned int distance = graph[closest][i].second; if (distances[adjacent] > to_closest + distance) { distances[adjacent] = to_closest + distance; cut.push(make_pair(distances[adjacent], adjacent)); } } } return distances.back(); }
void enumerate_maximal_independent_sets( const AdjacencyList<EdgeType> &graph, Func func) { const int n = graph.size(); std::vector<uint64_t> bit_graph(n), incr_bit_graph(n + 1); for(int i = n - 1; i >= 0; --i){ uint64_t mask = (1ull << i); for(const auto &e : graph[i]){ mask |= (1ull << e.to); } bit_graph[i] = mask; incr_bit_graph[i] = mask | incr_bit_graph[i + 1]; } std::function<void(int, uint64_t, uint64_t)> recur = [&, n](int i, uint64_t picked, uint64_t eliminated) -> void { if(i == n){ func(picked); return; } const bool force_ignore = ((eliminated & (1ull << i)) != 0); int flags = 1; // 1: select v_i, 2: ignore v_i if(bit_graph[i] & ~(incr_bit_graph[i + 1] | eliminated)){ flags = (force_ignore ? 2 : 1); }else if((incr_bit_graph[i + 1] | eliminated) & (1ull << i)){ flags = (force_ignore ? 2 : 3); } if(flags & 1){ recur(i + 1, picked | (1ull << i), eliminated | bit_graph[i]); } if(flags & 2){ recur(i + 1, picked, eliminated); } }; recur(0, 0, 0); }
void BreakpointGraph::renumber() { int *oldToNew = new int[n+2]; oldToNew[0] = 0; int renumbered = 1; AdjacencyListIterator it(adjlist); int current = 0; while(renumbered <= n+1) { it.setTo(-current); it.nextDesire(); current = it.get().vertex; oldToNew[-current] = renumbered; ++renumbered; } AdjacencyList *newAdjlist = new AdjacencyList(); newAdjlist->setN(n); AdjacencyList &newAdjacencies = *newAdjlist; AdjacencyListIterator it2(adjlist); int newvertex; for(int i = 0; i <= n+1; ++i) { it2.setTo(i); Adjacency &old = it2.get(); if( (old.reality != 0) && (old.desire != 0) ) { newvertex = remap(old.vertex); newAdjacencies[newvertex].vertex = newvertex; newAdjacencies[newvertex].reality = remap(old.reality); newAdjacencies[newvertex].desire = remap(old.desire); } it2.setTo(-i); old = it2.get(); newvertex = remap(old.vertex); newAdjacencies[newvertex].vertex = newvertex; newAdjacencies[newvertex].reality = remap(old.reality); newAdjacencies[newvertex].desire = remap(old.desire); } delete adjlist; adjlist = newAdjlist; delete oldToNew; }
explicit HeavyLightDecomposer( const AdjacencyList<EdgeType> &conn, int root = 0) : m_paths(0) , m_path_ids(conn.size(), -1) , m_local_indices(conn.size(), -1) { const std::vector<int> subtree_size = compute_subtree_size(conn, root); std::stack<pii> decompose_stack; decompose_stack.push(pii(root, -1)); while(!decompose_stack.empty()){ const pii p = decompose_stack.top(); decompose_stack.pop(); const int parent_vertex = p.second; const int pid = m_paths.size(); m_paths.push_back(Path()); Path &path = m_paths.back(); path.parent_vertex = parent_vertex; if(parent_vertex >= 0){ const int parent_pid = m_path_ids[parent_vertex]; const int parent_index = m_local_indices[parent_vertex]; m_paths[parent_pid].children.push_back( Connection(parent_index, pid)); path.depth = m_paths[parent_pid].depth + 1; }else{ path.depth = 0; } int cur = p.first; while(cur >= 0){ const int st_size = subtree_size[cur], threshold = st_size / 2; m_path_ids[cur] = pid; m_local_indices[cur] = path.vertices.size(); path.vertices.push_back(cur); int heavy_edge = -1; for(size_t i = 0; i < conn[cur].size(); ++i){ const int v = conn[cur][i].to; if(subtree_size[v] > subtree_size[cur]){ continue; } if(heavy_edge < 0 && subtree_size[v] >= threshold){ heavy_edge = v; }else{ decompose_stack.push(pii(v, cur)); } } cur = heavy_edge; } } }
void HyperbolicRoutingCalculator::calculatePaths(Map& map, RoutingTable& rt, Lsdb& lsdb, AdjacencyList& adjacencies) { _LOG_TRACE("Calculating hyperbolic paths"); int thisRouter = map.getMappingNoByRouterName(m_thisRouterName); // Iterate over directly connected neighbors std::list<Adjacent> neighbors = adjacencies.getAdjList(); for (std::list<Adjacent>::iterator adj = neighbors.begin(); adj != neighbors.end(); ++adj) { // Don't calculate nexthops using an inactive router if (adj->getStatus() == Adjacent::STATUS_INACTIVE) { _LOG_TRACE(adj->getName() << " is inactive; not using it as a nexthop"); continue; } ndn::Name srcRouterName = adj->getName(); // Don't calculate nexthops for this router to other routers if (srcRouterName == m_thisRouterName) { continue; } std::string srcFaceUri = adj->getConnectingFaceUri(); // Install nexthops for this router to the neighbor; direct neighbors have a 0 cost link addNextHop(srcRouterName, srcFaceUri, 0, rt); int src = map.getMappingNoByRouterName(srcRouterName); if (src == ROUTER_NOT_FOUND) { _LOG_WARN(adj->getName() << " does not exist in the router map!"); continue; } // Get hyperbolic distance from direct neighbor to every other router for (int dest = 0; dest < static_cast<int>(m_nRouters); ++dest) { // Don't calculate nexthops to this router or from a router to itself if (dest != thisRouter && dest != src) { ndn::Name destRouterName = map.getRouterNameByMappingNo(dest); double distance = getHyperbolicDistance(map, lsdb, srcRouterName, destRouterName); // Could not compute distance if (distance == UNKNOWN_DISTANCE) { _LOG_WARN("Could not calculate hyperbolic distance from " << srcRouterName << " to " << destRouterName); continue; } addNextHop(destRouterName, srcFaceUri, distance, rt); } } } }
bool AVC::calculateRec(AdjacencyList& graph, std::vector<int>* vertexCover, std::vector<int> deleted) { if (vertexCover != NULL){ return false; } if (graph.getEdges()->empty()){ vertexCover = &deleted; return true; } random_device r; std::default_random_engine e1(r()); uniform_int_distribution<int>* uid; uid = new uniform_int_distribution<int>(0, graph.getEdges()->size()); Edge e = graph.getEdges()->at(uid -> operator ()(e1)); //Choisir arete aléatoire //Construire graphe G1 sans le vertex u, et graphe G2 sans le vertex v //return fonction sur G1 v G2 }
ConnectivityGraph::EdgeIP ConnectivityGraph::getFromList( VertexID uvxid, VertexID vvxid, AdjacencyList & edges, ETForestLevel lvl ) const { EdgeIP e = NULL; for ( auto rit = edges.end(), rend = edges.begin(); rit != rend; ) { --rit; if ( (*rit)->level != lvl ) { std::cout << "CG ERR: getFromList " << uvxid << "," << vvxid << ": " << **rit << ", lvl " << lvl << std::endl; } assert( (*rit)->level == lvl ); if ( (*rit)->isequal( uvxid, vvxid ) ) { e = *rit; edges.erase( rit ); break; } } return e; }
void Explore(const AdjacencyList& graph, Vertex u, vector<bool>& visited, vector<int>& cc) { visited[u] = true; for (const Neighbor& neighbor : graph.GetNeighbors(u)) { Vertex v; double ignored_cost; std::tie(v, ignored_cost) = neighbor; if (!visited[v]) { cc[v] = cc[u]; Explore(graph, v, visited, cc); } } }
void TopologicalSort(const AdjacencyList& graph, vector<Vertex>& sorted) { size_t n = graph.NumVertices(); vector<bool> visited(n, false); for (size_t i = 0; i < n; ++i) { if (!visited[i]) { Explore(graph, i, visited, sorted); } } // By the time DFS finished, nodes in *sorted* are in increasing // order in terms of finishing time. Reverse it to get topological // ordering. std::reverse(sorted.begin(), sorted.end()); }
void Explore(const AdjacencyList& graph, Vertex u, vector<bool>& visited, vector<Vertex>& sorted) { visited[u] = true; for (const Neighbor& neighbor : graph.GetNeighbors(u)) { Vertex v; double ignored_cost; std::tie(v, ignored_cost) = neighbor; if (!visited[v]) { Explore(graph, v, visited, sorted); } } // When DFS is finished on this node, add itself to *sorted* list. sorted.push_back(u); }
void Graph::PrintHamiltonianCycle() { for (const auto &kv : adjacency_list_) { Tracker tracker(adjacency_list_.size(), kv.first); if (Visit(kv.first, tracker)) { std::cout << tracker.walk[0]; for (int i = 1; i < tracker.walk.size(); ++i) { std::cout << " " << tracker.walk[i]; } std::cout << std::endl; return; } } printf("N\n"); }
AdjLsa::AdjLsa(const ndn::Name& origR, uint32_t lsn, const ndn::time::system_clock::TimePoint& lt, uint32_t nl , AdjacencyList& adl) : Lsa(AdjLsa::TYPE_STRING) { m_origRouter = origR; m_lsSeqNo = lsn; m_expirationTimePoint = lt; m_noLink = nl; std::list<Adjacent> al = adl.getAdjList(); for (std::list<Adjacent>::iterator it = al.begin(); it != al.end(); it++) { if (it->getStatus() == Adjacent::STATUS_ACTIVE) { addAdjacent((*it)); } } }
//Faire un autre avec un K a décrémenter à chaque appel recursif; std::vector<Vertex*> AVC::calculate(AdjacencyList& graph) { vector<int>* vertexCover; vector<Vertex*> vc; vector<int> vertexDeleted; calculateRec(graph, vertexCover, vertexDeleted); if (vertexCover != NULL){ cout << "Vertex cover de taille: " << vertexCover->size() << endl; for (auto i : *vertexCover){ //Copie des adresses des vertex dans le vector vc.push_back(&graph.getGraph().at(i)); } return vc; } else { return NULL; } }
vector<unsigned int> dijkstra(const AdjacencyList& graph, unsigned int start_node) { vector<unsigned int> distances(graph.size(), infinity); distances[start_node] = 0; priority_queue< pair<unsigned int, unsigned int>, vector<pair<unsigned int, unsigned int>>, greater<pair<unsigned int, unsigned int>> > cut; cut.push(make_pair(0, start_node)); while (!cut.empty()) { unsigned int closest_node {cut.top().second}; unsigned int to_closest {cut.top().first}; cut.pop(); if (distances[closest_node] < to_closest) { continue; } for (const auto& adjacent : graph[closest_node]) { unsigned int adjacent_node {adjacent.first}; unsigned int edge_weight {adjacent.second}; if (distances[adjacent_node] > to_closest + edge_weight) { distances[adjacent_node] = to_closest + edge_weight; cut.push(make_pair(distances[adjacent_node], adjacent_node)); } } } return distances; }
void read_input(AdjacencyList& graph) { unsigned int nodes; unsigned int edges; cin >> nodes >> edges; graph.resize(nodes); for (unsigned int i = 0; i < edges; ++i) { unsigned int from; unsigned int to; unsigned int distance; cin >> from >> to >> distance; graph[from - 1].push_back(make_pair(to - 1, distance)); graph[to - 1].push_back(make_pair(from - 1, distance)); } }
int main() { std::map<unsigned int, unsigned int> hexToVertex; std::map<unsigned int, unsigned int> vertexToHex; int hex1 = 0, hex2 =0; string weight; string hex1_str; string hex2_str; ifstream file("mapedges.data"); AdjacencyList mygameboard; //while(!file.eof()) while(file >> hex1 >> hex2 >> weight) { if(weight == "w") continue; if(hexToVertex.count(hex1)==0) { unsigned int v1=mygameboard.add_vertex(); //x will be ?? //cout << "vertex " << v1 << " hex " << hex1 << endl; hexToVertex[hex1]=v1; vertexToHex[v1]=hex1; } if(hexToVertex.count(hex2)==0) { unsigned int v2=mygameboard.add_vertex(); //x will be ?? //cout << "vertex " << v2 << " hex " << hex2 << endl; hexToVertex[hex2]=v2; vertexToHex[v2]=hex2; } mygameboard.add_edge(hexToVertex[hex1], hexToVertex[hex2]); } //end of while loop //file read //Add edges to map Graph *g = new AdjacencyList(hexToVertex.size()); for(int i =0; i < mygameboard.order(); i++) { set<unsigned int> neighbor = mygameboard.neighbors(i); for(auto it = neighbor.begin(); it != neighbor.end(); it++) { g->add_edge(i, *it); } } //TODO- test if the graph g is correct //cout << "************* Graph " << endl; //g->display(); //cout << "************* Graph " << endl; /* int size = g->order(); cout << " size is " << size << endl; for(int i =0; i < size; i++) { cout << i << "(" << vertexToHex[i] << ")"; set<unsigned int> n = g->neighbors(i); for(auto it = n.begin(); it != n.end(); it++) { cout << ", " << *it << "(" << vertexToHex[*it] << ")"; } cout << endl; } */ unsigned int startVertex = hexToVertex[1605]; unsigned int endVertex = hexToVertex[309]; //cout << "start " << startVertex << " end " << endVertex << endl; //Implement BFS on the graph g map<unsigned int, unsigned int> sc; HexMap hexMap(309); //hexMap.add(endVertex); sc = g->breadth_first_search(startVertex); /* cout << "size of the sc " << sc.size() << endl; for(auto it = sc.begin(); it != sc.end(); it++) { cout << vertexToHex[it->first] << "-->" << vertexToHex[it->second] << endl; } */ while(sc.count(endVertex)==1) { int hex = vertexToHex[endVertex]; //cout << hex << endl; hexMap.add(hex); endVertex=sc[endVertex]; //assigns the previous } return 0; }
bool foldConstants(BasicBlock* block) { bool changed = false; m_state.beginBasicBlock(block); for (unsigned indexInBlock = 0; indexInBlock < block->size(); ++indexInBlock) { if (!m_state.isValid()) break; Node* node = block->at(indexInBlock); bool alreadyHandled = false; bool eliminated = false; switch (node->op()) { case BooleanToNumber: { if (node->child1().useKind() == UntypedUse && !m_interpreter.needsTypeCheck(node->child1(), SpecBoolean)) node->child1().setUseKind(BooleanUse); break; } case CheckArgumentsNotCreated: { if (!isEmptySpeculation( m_state.variables().operand( m_graph.argumentsRegisterFor(node->origin.semantic)).m_type)) break; node->convertToPhantom(); eliminated = true; break; } case CheckStructure: case ArrayifyToStructure: { AbstractValue& value = m_state.forNode(node->child1()); StructureSet set; if (node->op() == ArrayifyToStructure) set = node->structure(); else set = node->structureSet(); if (value.m_structure.isSubsetOf(set)) { m_interpreter.execute(indexInBlock); // Catch the fact that we may filter on cell. node->convertToPhantom(); eliminated = true; break; } break; } case CheckArray: case Arrayify: { if (!node->arrayMode().alreadyChecked(m_graph, node, m_state.forNode(node->child1()))) break; node->convertToPhantom(); eliminated = true; break; } case PutStructure: { if (m_state.forNode(node->child1()).m_structure.onlyStructure() != node->transition()->next) break; node->convertToPhantom(); eliminated = true; break; } case CheckFunction: { if (m_state.forNode(node->child1()).value() != node->function()->value()) break; node->convertToPhantom(); eliminated = true; break; } case CheckInBounds: { JSValue left = m_state.forNode(node->child1()).value(); JSValue right = m_state.forNode(node->child2()).value(); if (left && right && left.isInt32() && right.isInt32() && static_cast<uint32_t>(left.asInt32()) < static_cast<uint32_t>(right.asInt32())) { node->convertToPhantom(); eliminated = true; break; } break; } case MultiGetByOffset: { Edge baseEdge = node->child1(); Node* base = baseEdge.node(); MultiGetByOffsetData& data = node->multiGetByOffsetData(); // First prune the variants, then check if the MultiGetByOffset can be // strength-reduced to a GetByOffset. AbstractValue baseValue = m_state.forNode(base); m_interpreter.execute(indexInBlock); // Push CFA over this node after we get the state before. alreadyHandled = true; // Don't allow the default constant folder to do things to this. for (unsigned i = 0; i < data.variants.size(); ++i) { GetByIdVariant& variant = data.variants[i]; variant.structureSet().filter(baseValue); if (variant.structureSet().isEmpty()) { data.variants[i--] = data.variants.last(); data.variants.removeLast(); changed = true; } } if (data.variants.size() != 1) break; emitGetByOffset( indexInBlock, node, baseValue, data.variants[0], data.identifierNumber); changed = true; break; } case MultiPutByOffset: { Edge baseEdge = node->child1(); Node* base = baseEdge.node(); MultiPutByOffsetData& data = node->multiPutByOffsetData(); AbstractValue baseValue = m_state.forNode(base); m_interpreter.execute(indexInBlock); // Push CFA over this node after we get the state before. alreadyHandled = true; // Don't allow the default constant folder to do things to this. for (unsigned i = 0; i < data.variants.size(); ++i) { PutByIdVariant& variant = data.variants[i]; variant.oldStructure().filter(baseValue); if (variant.oldStructure().isEmpty()) { data.variants[i--] = data.variants.last(); data.variants.removeLast(); changed = true; continue; } if (variant.kind() == PutByIdVariant::Transition && variant.oldStructure().onlyStructure() == variant.newStructure()) { variant = PutByIdVariant::replace( variant.oldStructure(), variant.offset()); changed = true; } } if (data.variants.size() != 1) break; emitPutByOffset( indexInBlock, node, baseValue, data.variants[0], data.identifierNumber); changed = true; break; } case GetById: case GetByIdFlush: { Edge childEdge = node->child1(); Node* child = childEdge.node(); unsigned identifierNumber = node->identifierNumber(); AbstractValue baseValue = m_state.forNode(child); m_interpreter.execute(indexInBlock); // Push CFA over this node after we get the state before. alreadyHandled = true; // Don't allow the default constant folder to do things to this. if (baseValue.m_structure.isTop() || baseValue.m_structure.isClobbered() || (node->child1().useKind() == UntypedUse || (baseValue.m_type & ~SpecCell))) break; GetByIdStatus status = GetByIdStatus::computeFor( vm(), baseValue.m_structure.set(), m_graph.identifiers()[identifierNumber]); if (!status.isSimple()) break; for (unsigned i = status.numVariants(); i--;) { if (!status[i].constantChecks().isEmpty() || status[i].alternateBase()) { // FIXME: We could handle prototype cases. // https://bugs.webkit.org/show_bug.cgi?id=110386 break; } } if (status.numVariants() == 1) { emitGetByOffset(indexInBlock, node, baseValue, status[0], identifierNumber); changed = true; break; } if (!isFTL(m_graph.m_plan.mode)) break; MultiGetByOffsetData* data = m_graph.m_multiGetByOffsetData.add(); data->variants = status.variants(); data->identifierNumber = identifierNumber; node->convertToMultiGetByOffset(data); changed = true; break; } case PutById: case PutByIdDirect: case PutByIdFlush: { NodeOrigin origin = node->origin; Edge childEdge = node->child1(); Node* child = childEdge.node(); unsigned identifierNumber = node->identifierNumber(); ASSERT(childEdge.useKind() == CellUse); AbstractValue baseValue = m_state.forNode(child); m_interpreter.execute(indexInBlock); // Push CFA over this node after we get the state before. alreadyHandled = true; // Don't allow the default constant folder to do things to this. if (baseValue.m_structure.isTop() || baseValue.m_structure.isClobbered()) break; PutByIdStatus status = PutByIdStatus::computeFor( vm(), m_graph.globalObjectFor(origin.semantic), baseValue.m_structure.set(), m_graph.identifiers()[identifierNumber], node->op() == PutByIdDirect); if (!status.isSimple()) break; ASSERT(status.numVariants()); if (status.numVariants() > 1 && !isFTL(m_graph.m_plan.mode)) break; changed = true; for (unsigned i = status.numVariants(); i--;) addChecks(origin, indexInBlock, status[i].constantChecks()); if (status.numVariants() == 1) { emitPutByOffset(indexInBlock, node, baseValue, status[0], identifierNumber); break; } ASSERT(isFTL(m_graph.m_plan.mode)); MultiPutByOffsetData* data = m_graph.m_multiPutByOffsetData.add(); data->variants = status.variants(); data->identifierNumber = identifierNumber; node->convertToMultiPutByOffset(data); break; } case ToPrimitive: { if (m_state.forNode(node->child1()).m_type & ~(SpecFullNumber | SpecBoolean | SpecString)) break; node->convertToIdentity(); changed = true; break; } case GetMyArgumentByVal: { InlineCallFrame* inlineCallFrame = node->origin.semantic.inlineCallFrame; JSValue value = m_state.forNode(node->child1()).m_value; if (inlineCallFrame && value && value.isInt32()) { int32_t index = value.asInt32(); if (index >= 0 && static_cast<size_t>(index + 1) < inlineCallFrame->arguments.size()) { // Roll the interpreter over this. m_interpreter.execute(indexInBlock); eliminated = true; int operand = inlineCallFrame->stackOffset + m_graph.baselineCodeBlockFor(inlineCallFrame)->argumentIndexAfterCapture(index); m_insertionSet.insertNode( indexInBlock, SpecNone, CheckArgumentsNotCreated, node->origin); m_insertionSet.insertNode( indexInBlock, SpecNone, Phantom, node->origin, node->children); node->convertToGetLocalUnlinked(VirtualRegister(operand)); break; } } break; } case Check: { alreadyHandled = true; m_interpreter.execute(indexInBlock); for (unsigned i = 0; i < AdjacencyList::Size; ++i) { Edge edge = node->children.child(i); if (!edge) break; if (edge.isProved() || edge.willNotHaveCheck()) { node->children.removeEdge(i--); changed = true; } } break; } default: break; } if (eliminated) { changed = true; continue; } if (alreadyHandled) continue; m_interpreter.execute(indexInBlock); if (!m_state.isValid()) { // If we invalidated then we shouldn't attempt to constant-fold. Here's an // example: // // c: JSConstant(4.2) // x: ValueToInt32(Check:Int32:@const) // // It would be correct for an analysis to assume that execution cannot // proceed past @x. Therefore, constant-folding @x could be rather bad. But, // the CFA may report that it found a constant even though it also reported // that everything has been invalidated. This will only happen in a couple of // the constant folding cases; most of them are also separately defensive // about such things. break; } if (!node->shouldGenerate() || m_state.didClobber() || node->hasConstant()) continue; // Interesting fact: this freezing that we do right here may turn an fragile value into // a weak value. See DFGValueStrength.h. FrozenValue* value = m_graph.freeze(m_state.forNode(node).value()); if (!*value) continue; NodeOrigin origin = node->origin; AdjacencyList children = node->children; m_graph.convertToConstant(node, value); if (!children.isEmpty()) { m_insertionSet.insertNode( indexInBlock, SpecNone, Phantom, origin, children); } changed = true; } m_state.reset(); m_insertionSet.execute(block); return changed; }
bool foldConstants(BasicBlock* block) { bool changed = false; m_state.beginBasicBlock(block); for (unsigned indexInBlock = 0; indexInBlock < block->size(); ++indexInBlock) { if (!m_state.isValid()) break; Node* node = block->at(indexInBlock); bool eliminated = false; switch (node->op()) { case BooleanToNumber: { if (node->child1().useKind() == UntypedUse && !m_interpreter.needsTypeCheck(node->child1(), SpecBoolean)) node->child1().setUseKind(BooleanUse); break; } case CheckArgumentsNotCreated: { if (!isEmptySpeculation( m_state.variables().operand( m_graph.argumentsRegisterFor(node->origin.semantic)).m_type)) break; node->convertToPhantom(); eliminated = true; break; } case CheckStructure: case ArrayifyToStructure: { AbstractValue& value = m_state.forNode(node->child1()); StructureSet set; if (node->op() == ArrayifyToStructure) set = node->structure(); else set = node->structureSet(); if (value.m_currentKnownStructure.isSubsetOf(set)) { m_interpreter.execute(indexInBlock); // Catch the fact that we may filter on cell. node->convertToPhantom(); eliminated = true; break; } StructureAbstractValue& structureValue = value.m_futurePossibleStructure; if (structureValue.isSubsetOf(set) && structureValue.hasSingleton()) { Structure* structure = structureValue.singleton(); m_interpreter.execute(indexInBlock); // Catch the fact that we may filter on cell. AdjacencyList children = node->children; children.removeEdge(0); if (!!children.child1()) m_insertionSet.insertNode(indexInBlock, SpecNone, Phantom, node->origin, children); node->children.setChild2(Edge()); node->children.setChild3(Edge()); node->convertToStructureTransitionWatchpoint(structure); eliminated = true; break; } break; } case CheckArray: case Arrayify: { if (!node->arrayMode().alreadyChecked(m_graph, node, m_state.forNode(node->child1()))) break; node->convertToPhantom(); eliminated = true; break; } case CheckFunction: { if (m_state.forNode(node->child1()).value() != node->function()) break; node->convertToPhantom(); eliminated = true; break; } case CheckInBounds: { JSValue left = m_state.forNode(node->child1()).value(); JSValue right = m_state.forNode(node->child2()).value(); if (left && right && left.isInt32() && right.isInt32() && static_cast<uint32_t>(left.asInt32()) < static_cast<uint32_t>(right.asInt32())) { node->convertToPhantom(); eliminated = true; break; } break; } case MultiGetByOffset: { Edge childEdge = node->child1(); Node* child = childEdge.node(); MultiGetByOffsetData& data = node->multiGetByOffsetData(); Structure* structure = m_state.forNode(child).bestProvenStructure(); if (!structure) break; for (unsigned i = data.variants.size(); i--;) { const GetByIdVariant& variant = data.variants[i]; if (!variant.structureSet().contains(structure)) continue; if (variant.chain()) break; emitGetByOffset(indexInBlock, node, structure, variant, data.identifierNumber); eliminated = true; break; } break; } case MultiPutByOffset: { Edge childEdge = node->child1(); Node* child = childEdge.node(); MultiPutByOffsetData& data = node->multiPutByOffsetData(); Structure* structure = m_state.forNode(child).bestProvenStructure(); if (!structure) break; for (unsigned i = data.variants.size(); i--;) { const PutByIdVariant& variant = data.variants[i]; if (variant.oldStructure() != structure) continue; emitPutByOffset(indexInBlock, node, structure, variant, data.identifierNumber); eliminated = true; break; } break; } case GetById: case GetByIdFlush: { Edge childEdge = node->child1(); Node* child = childEdge.node(); unsigned identifierNumber = node->identifierNumber(); if (childEdge.useKind() != CellUse) break; Structure* structure = m_state.forNode(child).bestProvenStructure(); if (!structure) break; GetByIdStatus status = GetByIdStatus::computeFor( vm(), structure, m_graph.identifiers()[identifierNumber]); if (!status.isSimple() || status.numVariants() != 1) { // FIXME: We could handle prototype cases. // https://bugs.webkit.org/show_bug.cgi?id=110386 break; } emitGetByOffset(indexInBlock, node, structure, status[0], identifierNumber); eliminated = true; break; } case PutById: case PutByIdDirect: { NodeOrigin origin = node->origin; Edge childEdge = node->child1(); Node* child = childEdge.node(); unsigned identifierNumber = node->identifierNumber(); ASSERT(childEdge.useKind() == CellUse); Structure* structure = m_state.forNode(child).bestProvenStructure(); if (!structure) break; PutByIdStatus status = PutByIdStatus::computeFor( vm(), m_graph.globalObjectFor(origin.semantic), structure, m_graph.identifiers()[identifierNumber], node->op() == PutByIdDirect); if (!status.isSimple()) break; if (status.numVariants() != 1) break; emitPutByOffset(indexInBlock, node, structure, status[0], identifierNumber); eliminated = true; break; } case ToPrimitive: { if (m_state.forNode(node->child1()).m_type & ~(SpecFullNumber | SpecBoolean | SpecString)) break; node->convertToIdentity(); break; } default: break; } if (eliminated) { changed = true; continue; } m_interpreter.execute(indexInBlock); if (!m_state.isValid()) { // If we invalidated then we shouldn't attempt to constant-fold. Here's an // example: // // c: JSConstant(4.2) // x: ValueToInt32(Check:Int32:@const) // // It would be correct for an analysis to assume that execution cannot // proceed past @x. Therefore, constant-folding @x could be rather bad. But, // the CFA may report that it found a constant even though it also reported // that everything has been invalidated. This will only happen in a couple of // the constant folding cases; most of them are also separately defensive // about such things. break; } if (!node->shouldGenerate() || m_state.didClobber() || node->hasConstant()) continue; JSValue value = m_state.forNode(node).value(); if (!value) continue; // Check if merging the abstract value of the constant into the abstract value // we've proven for this node wouldn't widen the proof. If it widens the proof // (i.e. says that the set contains more things in it than it previously did) // then we refuse to fold. AbstractValue oldValue = m_state.forNode(node); AbstractValue constantValue; constantValue.set(m_graph, value); constantValue.fixTypeForRepresentation(node); if (oldValue.merge(constantValue)) continue; NodeOrigin origin = node->origin; AdjacencyList children = node->children; if (node->op() == GetLocal) m_graph.dethread(); else ASSERT(!node->hasVariableAccessData(m_graph)); m_graph.convertToConstant(node, value); m_insertionSet.insertNode( indexInBlock, SpecNone, Phantom, origin, children); changed = true; } m_state.reset(); m_insertionSet.execute(block); return changed; }
OSMReader ( const char * osm_file, AdjacencyList & alist, AdjacencyList & palist, WaynodeLocations & waynode_locations, WayNodesMap & busWayNodesMap, Way2Nodes & way2nodes ) : alist ( alist ), palist ( palist ), waynode_locations ( waynode_locations ), busWayNodesMap ( busWayNodesMap ), way2nodes ( way2nodes ) { try { #ifdef DEBUG std::cout << "\n OSMReader is running... " << std::endl; #endif osmium::io::File infile ( osm_file ); osmium::io::Reader reader ( infile, osmium::osm_entity_bits::all ); using SparseLocations = osmium::index::map::SparseMemMap<osmium::unsigned_object_id_type, osmium::Location>; osmium::handler::NodeLocationsForWays<SparseLocations> node_locations ( locations ); osmium::apply ( reader, node_locations, *this ); reader.close(); #ifdef DEBUG std::cout << " #OSM Nodes: " << nOSM_nodes << "\n"; std::cout << " #OSM Highways: " << nOSM_ways << "\n"; std::cout << " #Kms (Total length of highways) = " << sum_highhway_length/1000.0 << std::endl; std::cout << " #OSM Relations: " << nOSM_relations << "\n"; std::cout << " #Highway Nodes: " << sum_highhway_nodes << "\n"; std::cout << " #Unique Highway Nodes: " << sum_unique_highhway_nodes << "\n"; std::cout << " E= (#Highway Nodes - #OSM Highways): " << sum_highhway_nodes - nOSM_ways << "\n"; std::cout << " V= (#Unique Highway Nodes):" << sum_unique_highhway_nodes << "\n"; std::cout << " V^2/E= " << ( ( long ) sum_unique_highhway_nodes * ( long ) sum_unique_highhway_nodes ) / ( double ) ( sum_highhway_nodes - nOSM_ways ) << "\n"; std::cout << " Edge_multiplicity: " << edge_multiplicity << std::endl; std::cout << " max edle length: " << max_edge_length << std::endl; std::cout << " edle length mean: " << mean_edge_length/cedges << std::endl; std::cout << " cedges: " << cedges << std::endl; std::cout << " #Buses = " << busWayNodesMap.size() << std::endl; std::cout << " Node locations " << locations.used_memory() /1024.0/1024.0 << " Mbytes" << std::endl; //std::cout << " Waynode locations " << waynode_locations.used_memory() /1024.0/1024.0 << " Mbytes" << std::endl; std::cout << " Vertices " << vert.used_memory() /1024.0/1024.0 << " Mbytes" << std::endl; std::cout << " way2nodes " << way2nodes.size() << "" << std::endl; std::set<osmium::unsigned_object_id_type> sum_vertices; std::map<osmium::unsigned_object_id_type, size_t> word_map; int sum_edges {0}; for ( auto busit = begin ( alist ); busit != end ( alist ); ++busit ) { sum_vertices.insert ( busit->first ); sum_edges+=busit->second.size(); for ( const auto &v : busit->second ) { sum_vertices.insert ( v ); } } std::cout << " #citymap edges = "<< sum_edges<< std::endl; std::cout << " #citymap vertices = "<< sum_vertices.size() << std::endl; std::cout << " #citymap vertices (deg- >= 1) = "<< alist.size() << std::endl; std::cout << " #onewayc = "<< onewayc<< std::endl; #endif m_estimator *= 8; } catch ( std::exception &err ) { google::protobuf::ShutdownProtobufLibrary(); throw; } }
void Graph::RunColoring() { this->coloring = new Coloring(this->adjGraph->GetNumVertex()); AdjacencyList* adjList = static_cast<AdjacencyList*>(this->adjGraph); coloring->Run(adjList->GetLists()); }
std::vector<Vertex*> GreedyVC::calculate(AdjacencyList& graph) { vector<int> VC; cout << "Step 1" << endl; vector<Edge> E; //copy graphe edges; for (auto it = graph.getEdges() -> begin(); it != graph.getEdges()->end(); it++){ Edge edgeToCopy; edgeToCopy.debut = it -> debut; edgeToCopy.fin = it -> fin; E.push_back(edgeToCopy); } vector<Edge> E2; random_device r; std::default_random_engine e1(r()); uniform_int_distribution<int>* uid; Edge currentEdge; cout << "Step 2: debut de la boucle" << endl; while (!E.empty()){ //Choix de l'arete a ajouter uid = new uniform_int_distribution<int>(0, E.size()-1); int pos = uid -> operator ()(e1); currentEdge = E.at(pos); cout << "Edge: " << currentEdge.debut << " - " << currentEdge.fin << endl; //Ajout des deux vertex de l'arete au VC VC.push_back(currentEdge.debut); VC.push_back(currentEdge.fin); cout << "Step 3 : Vertex adjacent a u" << endl; for (int i = 0; i < graph.getGraph()[currentEdge.debut].adjacentVertex.size(); ++i){ Edge edgeCovered; edgeCovered.debut = currentEdge.debut; edgeCovered.fin = graph.getGraph()[currentEdge.debut].adjacentVertex[i]->num; if (! (edgeCovered == currentEdge)){ E2.push_back(edgeCovered); } } cout << "Step 4 : Vertex adjacent a v" << endl; for (int i = 0; i < graph.getGraph()[currentEdge.fin].adjacentVertex.size(); ++i){ Edge edgeCovered; edgeCovered.debut = currentEdge.fin; edgeCovered.fin = graph.getGraph()[currentEdge.fin].adjacentVertex[i]->num; if (! (edgeCovered == currentEdge)){ E2.push_back(edgeCovered); } } E.erase(E.begin()+pos); cout << "Step 5 : Suppression de E' " << endl; for (auto edgeToRemove : E2){ auto it = find(E.begin(), E.end(), edgeToRemove); if (it != E.end()){ E.erase(it); } } E2.clear(); //pick edges in E //V' += E.vertex //E' = Aretes incidentes au vertex de E //E -= E' } vector<Vertex*> vcToReturn; cout << VC.size() << " solutions trouvées pour Vertex Cover: " << endl; for (auto v : VC){ cout << graph.getGraph().at(v).num << " "; vcToReturn.push_back(&graph.getGraph().at(v)); } cout << endl; return vcToReturn; }