uint32_t BBSISPOptimizerWCP::generateOptimalILPFormulationForSequentialCode(CFGVertex start, CFGVertex end, uint32_t running_id, vector<CFGEdge>& leavingEdges) { vector<CFGVertex> processing; vector<CFGVertex> processed; processing.push_back(start); cfgOutEdgeIter ep; LOG_DEBUG(logger, "Processing from: " << start << " [" << get(startAddrStringNProp, start) << "]" << " to " << end << " [" << get(startAddrStringNProp, end) << "]" << "."); while(processing.size() != 0) { if(logger->isDebugEnabled()) { ostringstream s; for(uint32_t i = 0; i < processing.size(); i++) { s << "(" << processing[i] << ")"; } LOG_DEBUG(logger, "Size of processing list: " << processing.size() << " contains:" << s.str()); } CFGVertex actual_cfg = processing.back(); processing.pop_back(); LOG_DEBUG(logger, "Processing " << actual_cfg << " " << get(startAddrStringNProp, actual_cfg)); // ensure that each node is only handled once. bool node_already_processed = false; for(uint32_t j = 0; j<processed.size(); j++) { if(actual_cfg == processed[j]) { node_already_processed = true; } } if(!node_already_processed) { if(actual_cfg != end) { if(get(nodeTypeNProp, actual_cfg) == CallPoint) { // create virtual node for function CFGVertex v; uint32_t function_id = running_id; CFGVertex cfg_return_point = actual_cfg; // to temporally initialize the vertex cfgVertexIter vp; bool found_return = false; // find the right return point for the call point uint32_t context_addr = get(endAddrNProp, actual_cfg); for (vp = vertices(cfg); (vp.first != vp.second)&&(!found_return); ++vp.first) { v = *vp.first; if((get(nodeTypeNProp, v) == ReturnPoint) && (context_addr == get(endAddrNProp, v))) { found_return = true; cfg_return_point = v; } } assert(found_return); stringstream cfg_ilp; assert(out_degree(actual_cfg, cfg) == 1); cfgOutEdgeIter eop = out_edges(actual_cfg, cfg); CFGVertex function_entry_cfg = target(*eop.first, cfg); assert(in_degree(cfg_return_point, cfg) == 1); cfgInEdgeIter eip = in_edges(cfg_return_point, cfg); CFGVertex function_exit_cfg = source(*eip.first, cfg); FunctionMap::iterator pos = functionMap.find(function_entry_cfg); if(pos == functionMap.end()) { vector<CFGEdge> function_leaving_edges; // create ilp for the function body running_id = generateOptimalILPFormulationForSequentialCode(function_entry_cfg, function_exit_cfg, ++running_id, function_leaving_edges); LOG_DEBUG(logger, "Returned from function to processing from: " << start << " to " << end << "."); assert(function_leaving_edges.empty()); FunctionMap::iterator ins_pos; bool ins_bool; tie(ins_pos, ins_bool) = functionMap.insert(make_pair(function_entry_cfg, function_id)); assert(ins_bool); // create cost for the function with function_id cfg_ilp << "cf" << function_id << " = " << " w" << function_entry_cfg << ";" << endl; } else { function_id = pos->second; } // connect call point with virtual function node wfXctxY cfg_ilp << "w" << actual_cfg << " >= wf" << function_id << "c" << hex << context_addr << dec << getPenaltyForFunctionEntering(actual_cfg, function_entry_cfg) << ";" << endl; // connect virtual function node with return point, and taking cost of function into account // NOTICE the cost of the function exit node (which is an Exit node) to the node to which it is returned (which is an ReturnPoint node) does not need to be considered, because it is free of cost. cfg_ilp << "wf" << function_id << "c" << hex << context_addr << dec << " >= w" << cfg_return_point << " + cf" << function_id << getPenaltyForFunctionExit(cfg_return_point, function_exit_cfg) << ";" << endl; cfg_ilps.push_back(cfg_ilp.str()); processing.push_back(cfg_return_point); } else { for(ep = out_edges(actual_cfg, cfg); ep.first != ep.second; ++ep.first) { bool found_loop_head = false; uint32_t loop_id = running_id; vector<CFGVertex> loop_exits; vector<CFGEdge> irregular_loop_exit_edges; CFGEdge eo = *ep.first; CFGEdge back_edge; CFGVertex target_cfg = target(eo, cfg); edge_type_t etype = get(edgeTypeEProp, eo); if((etype == ForwardStep) || (etype == ForwardJump) || (etype == Meta)) { LOG_DEBUG(logger, "Checking out-edges From: " << actual_cfg << " " << get(startAddrStringNProp, actual_cfg) << " To: " << target_cfg << " " << get(startAddrStringNProp, target_cfg) << " Type: " << etype << " Edge " << eo); LoopDataMap::iterator pos = loopMap.find(target_cfg); if(pos != loopMap.end()) { if((target_cfg != start) && (pos->second.exitNode != end)) { LOG_DEBUG(logger, "Target of out edge " << eo << ". " << target_cfg << " is a loop head. Backedge is: " << pos->second.backEdge << " exit node is: " << pos->second.exitNode); loop_exits.push_back(pos->second.exitNode); found_loop_head = true; stringstream cfg_ilp; int32_t loop_bound = getLoopBoundForLoopHead(target_cfg, pos->second.backEdge); cfg_ilp << "cl" << loop_id << " = " << loop_bound+1 /* the value from the flow facts determines the number of invocations of the back_edge, i.e. the number of times the loop is entered */ << " w" << pos->second.startNode; if(get(nodeTypeNProp, pos->second.exitNode) == BasicBlock) { // charge the cost of the loop conserving edge, i.e. of the bottom node of the loop body // The cost of this basic block for the loop exiting edge is charged, on connection of the virtual loop node with the code after the loop (see calculation of wlXX and the usage of the variable loop_exits). if(!conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION)) { cfg_ilp << " + " << loop_bound << " ce" << source(pos->second.backEdge,cfg) << "t" << target(pos->second.backEdge, cfg); } else // conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION) { cfg_ilp << " + " << getEdgeCostConstraint(pos->second.backEdge, loop_bound); } } else { assert(false); // could there be a loop with a non basic block node at the end?? } cfg_ilp << ";" << endl; cfg_ilps.push_back(cfg_ilp.str()); // create ilp for the loop body running_id = generateOptimalILPFormulationForSequentialCode(pos->second.startNode, pos->second.exitNode, ++running_id, irregular_loop_exit_edges); LOG_DEBUG(logger, "Returned loop to processing from: " << start << " to " << end << "."); } } stringstream cfg_ilp; if(!found_loop_head) { bool is_on_path = isNodeOnPath(target_cfg, start, end, false); LOG_DEBUG(logger, "Successor of actual node " << actual_cfg << " " << get(startAddrStringNProp, actual_cfg) << " (edge: " << eo << ") is no loop head. The node is " << ((!is_on_path)?("not "):("")) << "within the sequential code part"); cfg_ilp << "w" << actual_cfg << " >= "; if(is_on_path) { cfg_ilp << "w" << target_cfg; } if(get(nodeTypeNProp, actual_cfg) == BasicBlock) { if(is_on_path) { cfg_ilp << " + "; } if(!conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION)) { cfg_ilp << "ce" << source(eo,cfg) << "t" << target(eo, cfg); } else // conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION) { cfg_ilp << getEdgeCostConstraint(eo); } } cfg_ilp << ";" << endl; cfg_ilps.push_back(cfg_ilp.str()); // checking if target node is within loop body if(is_on_path) { LOG_DEBUG(logger, "Pushing " << target_cfg << " " << get(startAddrStringNProp, target_cfg) << " to process list"); processing.push_back(target_cfg); } else { LOG_DEBUG(logger, "Node " << target_cfg << " " << get(startAddrStringNProp, target_cfg) << " is not within currently processing code part (function or loop body), cannot add to process list."); leavingEdges.push_back(eo); } } else { LOG_DEBUG(logger, "Successor of actual node " << actual_cfg << " " << get(startAddrStringNProp, actual_cfg) << " (edge: " << eo << ") is loop head"); cfg_ilp << "w" << actual_cfg << " >= wl" << loop_id; if(get(nodeTypeNProp, actual_cfg) == BasicBlock) { if(!conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION)) { cfg_ilp << " + ce" << source(eo,cfg) << "t" << target(eo, cfg); } else // conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION) { cfg_ilp << " + " << getEdgeCostConstraint(eo); } } cfg_ilp << ";" << endl; cfg_ilps.push_back(cfg_ilp.str()); for(uint32_t i = 0; i < loop_exits.size(); i++) { LOG_DEBUG(logger, "Loop exit nodes are: " << loop_exits[i]); for(cfgOutEdgeIter ep2 = out_edges(loop_exits[i], cfg); ep2.first != ep2.second; ++ep2.first) { CFGEdge el = *ep2.first; CFGVertex post_loop_node = target(el, cfg); edge_type_t etype = get(edgeTypeEProp, el); if((etype == ForwardStep) || (etype == ForwardJump) || (etype == Meta)) { stringstream tmp; // the wcet of the loop is the wcet of the following node + the cost of the loop + the cost of the loop out edge if(!conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION)) { tmp << "wl" << loop_id << " >= w" << post_loop_node << " + cl" << loop_id << " + ce" << source(el,cfg) << "t" << target(el, cfg) << ";" << endl; } else // conf->getBool(CONF_BBSISP_WCP_SHRINK_ILP_FORMULATION) { tmp << "wl" << loop_id << " >= w" << post_loop_node << " + cl" << loop_id << " + " << getEdgeCostConstraint(el) << ";" << endl; } cfg_ilps.push_back(tmp.str()); // checking if target node is within loop body if(isNodeOnPath(target_cfg, start, end, false)) { LOG_DEBUG(logger, "Pushing post loop node " << post_loop_node << " " << get(startAddrStringNProp, post_loop_node) << " to process list"); processing.push_back(post_loop_node); } else { LOG_DEBUG(logger, "Post loop node " << target_cfg << " " << get(startAddrStringNProp, target_cfg) << " is not on path, cannot add to process list."); leavingEdges.push_back(eo); assert(false); } } } } for(uint32_t i = 0; i < irregular_loop_exit_edges.size(); i++) { CFGEdge e = irregular_loop_exit_edges[i]; LOG_DEBUG(logger, "Irregular loop exit edge: " << e); // checking if the target of the loop leaving edge can be found whithin the currently activw loop body if(isNodeOnPath(target(e, cfg), start, end, false)) { stringstream tmp; // If a loop is unexpectively left by an edge e, the target of e may be reached by the loop body (in the worst case at the end of the loop, since the structure of the loop is hidden by the cost of the loop (clXX). // The cost of the irregular loop exit edge does not need to be charged here, because it is implicitely already in the cost of the loop (which is maximizes over all possible paths, including the dead end of an irregular leaving edge. tmp << "wl" << loop_id << " >= w" << target(e, cfg) << " + cl" << loop_id << ";" << endl; cfg_ilps.push_back(tmp.str()); } else { // The irregular loop leaving edge leaves multiple levels of loop nests. Delegate handling to next loop level. leavingEdges.push_back(e); assert(false); } } } } } } } else { LOG_DEBUG(logger, "Found end node"); stringstream cfg_ilp; // The cost of the loop conserving edge (the bottom basic block) is charged in the loop cost variable: clXX = loop_bound+1 * wLoopHead + ceLoopConservingEdgeXX // This is because the loop body is ececuted loop_bound+1, whereas the cost of the loop conserving edge needs to be taken only loop_bound times into account, because the last iteration of the loop uses another edge, which is charged in wlXX >= wYY + clXX + ceExitEdgeOfLoopXX cfg_ilp << "w" << actual_cfg << " = 0;" << endl; cfg_ilps.push_back(cfg_ilp.str()); } processed.push_back(actual_cfg); } } return running_id; }
void tie(Selection sel, Ts&... ts) { std::tuple<Ts...> tup = sel; tie(tup, typename detail::indicesBuilder<sizeof...(Ts)>::type{}, ts...); }
template < class Q1, class R1> BOOST_FORCEINLINE void do_it(A0& a0, const char& orient, Q1 & q1, R1 & r1) const { BOOST_AUTO_TPL(q, boost::proto::child_c<0>(a0)); BOOST_AUTO_TPL(r, boost::proto::child_c<1>(a0)); size_t j = boost::proto::child_c<2>(a0); table<value_t, nt2::of_size_<2, 2> > g; size_t n = size(r, 2); size_t m = size(r, 1); if (orient == 'c') { // remove the j-th column. n = number of columns in modified r. r1 = nt2::cath(r(nt2::_, nt2::_(1, j-1)), r(nt2::_,nt2::_(j+1, nt2::end_))); q1 = q; --n; // r now has nonzeros below the diagonal in columns j through n. // r = [x | x x x [x x x x // 0 | x x x 0 * * x // 0 | + x x g 0 0 * * // 0 | 0 + x ---> 0 0 0 * // 0 | 0 0 + 0 0 0 0 // 0 | 0 0 0] 0 0 0 0] // use givens rotations to zero the +'s, one at a time, from left to right. for(size_t k = j; k <= nt2::min(n,m-1); ++k) { BOOST_AUTO_TPL(p, nt2::cons(k, k+1)); tie(g,r1(p, k)) = nt2::planerot(r1(p,k)); if (k < n) { r1(p,nt2::_(k+1, n)) = nt2::mtimes(g,r1(p,nt2::_(k+1, n))); } q1(nt2::_,p) = nt2::mtimes(q1(nt2::_,p), nt2::ct(g)); } // if q is not square, q is from economy size qr(a,0). // both q and r need further adjustments. size_t mq = size(q, 1); size_t nq = size(q, 2); if (mq != nq) { r1(m,nt2::_)=_(); q1(nt2::_,nq)=_(); } } else { r1 = r; // this permutes row 1 of q*r to row j of q(p,:)*r if (j != 1) { BOOST_AUTO_TPL(p, nt2::cath(nt2::cath(j, nt2::_(size_t(1), j-1)), nt2::_(j+1, m))); q1 = q(p,nt2::_); } table<value_t, _1D> fqrt = nt2::colvect(q1(1,nt2::_)); // fqrt is the transpose of the first row of q. // fqrt = [x [1 // - - // + g 0 // + ---> 0 // + 0 // + 0 // +] 0] // // use givens rotations to zero the +'s, one at a time, from bottom to top. // the result will have a "1" in the first entry. // // apply the same rotations to r, which becomes upper hessenberg. // r = [x x x x [* * * * // ------- ------- // x x x g * * * * // x x ---> * * * // x * * // 0 0 0 0 * // 0 0 0 0] 0 0 0 0] // // under (the transpose of) the same rotations, q becomes // q = [x | x x x x x [1 | 0 0 0 0 0 // --|---------- --|---------- // x | x x x x x g' 0 | * * * * * // x | x x x x x ---> 0 | * * * * * // x | x x x x x 0 | * * * * * // x | x x x x x 0 | * * * * * // x | x x x x x] 0 | * * * * *] for(size_t i = m; i >= 2; --i) { BOOST_AUTO_TPL(p, nt2::cons(i-1, i)); nt2::tie(g, fqrt(p)) = nt2::planerot(fqrt(p)); // tab_t rr = r1(p,nt2::_(i-1, n)); r1(p,nt2::_(i-1, n)) = nt2::mtimes(g, r1(p,nt2::_(i-1, n))); // tab_t qq = q1(nt2::_,p); q1(nt2::_,p) = nt2::mtimes(q1(nt2::_,p), nt2::ct(g)); } // the boxed off (---) parts of q and r are the desired factors. tab_t qq = q1(nt2::_(2, nt2::end_),_(2, nt2::end_)); q1 = qq; tab_t rr = r1(_(2, nt2::end_),nt2::_); r1 = rr; } }
bool operator==(const ConstraintsVerificationResult& o) const { return tie(unsatisfiedConstraintDescriptionsBySubtaskId_, satisfiedButNotAssignedSubtaskIds_) == tie(o.unsatisfiedConstraintDescriptionsBySubtaskId_, o.satisfiedButNotAssignedSubtaskIds_); }
int read_dimacs_max_flow(Graph& g, CapacityMap capacity, ReverseEdgeMap reverse_edge, typename graph_traits<Graph>::vertex_descriptor& src, typename graph_traits<Graph>::vertex_descriptor& sink, std::istream& in=std::cin) { // const int MAXLINE = 100; /* max line length in the input file */ const int ARC_FIELDS = 3; /* no of fields in arc line */ const int NODE_FIELDS = 2; /* no of fields in node line */ const int P_FIELDS = 3; /* no of fields in problem line */ const char* PROBLEM_TYPE = "max"; /* name of problem type*/ typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor; typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor; std::vector<vertex_descriptor> verts; long m, n, /* number of edges and nodes */ i, head, tail, cap; long no_lines=0, /* no of current input line */ no_plines=0, /* no of problem-lines */ no_nslines=0, /* no of node-source-lines */ no_nklines=0, /* no of node-source-lines */ no_alines=0; /* no of arc-lines */ std::string in_line; /* for reading input line */ char pr_type[3]; /* for reading type of the problem */ char nd; /* source (s) or sink (t) */ int k, /* temporary */ err_no; /* no of detected error */ /* -------------- error numbers & error messages ---------------- */ const int EN1 = 0; const int EN2 = 1; const int EN3 = 2; const int EN4 = 3; // const int EN6 = 4; // const int EN10 = 5; // const int EN7 = 6; const int EN8 = 7; const int EN9 = 8; const int EN11 = 9; const int EN12 = 10; // const int EN13 = 11; const int EN14 = 12; const int EN16 = 13; const int EN15 = 14; const int EN17 = 15; const int EN18 = 16; const int EN21 = 17; const int EN19 = 18; const int EN20 = 19; const int EN22 = 20; static char *err_message[] = { /* 0*/ "more than one problem line.", /* 1*/ "wrong number of parameters in the problem line.", /* 2*/ "it is not a Max Flow problem line.", /* 3*/ "bad value of a parameter in the problem line.", /* 4*/ "can't obtain enough memory to solve this problem.", /* 5*/ "more than one line with the problem name.", /* 6*/ "can't read problem name.", /* 7*/ "problem description must be before node description.", /* 8*/ "this parser doesn't support multiply sources and sinks.", /* 9*/ "wrong number of parameters in the node line.", /*10*/ "wrong value of parameters in the node line.", /*11*/ " ", /*12*/ "source and sink descriptions must be before arc descriptions.", /*13*/ "too many arcs in the input.", /*14*/ "wrong number of parameters in the arc line.", /*15*/ "wrong value of parameters in the arc line.", /*16*/ "unknown line type in the input.", /*17*/ "reading error.", /*18*/ "not enough arcs in the input.", /*19*/ "source or sink doesn't have incident arcs.", /*20*/ "can't read anything from the input file." }; /* --------------------------------------------------------------- */ /* The main loop: - reads the line of the input, - analyses its type, - checks correctness of parameters, - puts data to the arrays, - does service functions */ while (std::getline(in, in_line)) { ++no_lines; switch (in_line[0]) { case 'c': /* skip lines with comments */ case '\n': /* skip empty lines */ case '\0': /* skip empty lines at the end of file */ break; case 'p': /* problem description */ if ( no_plines > 0 ) /* more than one problem line */ { err_no = EN1 ; goto error; } no_plines = 1; if ( /* reading problem line: type of problem, no of nodes, no of arcs */ sscanf ( in_line.c_str(), "%*c %3s %ld %ld", pr_type, &n, &m ) != P_FIELDS ) /*wrong number of parameters in the problem line*/ { err_no = EN2; goto error; } if ( strcmp ( pr_type, PROBLEM_TYPE ) ) /*wrong problem type*/ { err_no = EN3; goto error; } if ( n <= 0 || m <= 0 ) /*wrong value of no of arcs or nodes*/ { err_no = EN4; goto error; } { for (long vi = 0; vi < n; ++vi) verts.push_back(add_vertex(g)); } break; case 'n': /* source(s) description */ if ( no_plines == 0 ) /* there was not problem line above */ { err_no = EN8; goto error; } /* reading source or sink */ k = sscanf ( in_line.c_str(),"%*c %ld %c", &i, &nd ); --i; // index from 0 if ( k < NODE_FIELDS ) /* node line is incorrect */ { err_no = EN11; goto error; } if ( i < 0 || i > n ) /* wrong value of node */ { err_no = EN12; goto error; } switch (nd) { case 's': /* source line */ if ( no_nslines != 0) /* more than one source line */ { err_no = EN9; goto error; } no_nslines = 1; src = verts[i]; break; case 't': /* sink line */ if ( no_nklines != 0) /* more than one sink line */ { err_no = EN9; goto error; } no_nklines = 1; sink = verts[i]; break; default: /* wrong type of node-line */ err_no = EN12; goto error; } break; case 'a': /* arc description */ if ( no_nslines == 0 || no_nklines == 0 ) /* there was not source and sink description above */ { err_no = EN14; goto error; } if ( no_alines >= m ) /*too many arcs on input*/ { err_no = EN16; goto error; } if ( /* reading an arc description */ sscanf ( in_line.c_str(),"%*c %ld %ld %ld", &tail, &head, &cap ) != ARC_FIELDS ) /* arc description is not correct */ { err_no = EN15; goto error; } --tail; // index from 0, not 1 --head; if ( tail < 0 || tail > n || head < 0 || head > n ) /* wrong value of nodes */ { err_no = EN17; goto error; } { edge_descriptor e1, e2; bool in1, in2; tie(e1, in1) = add_edge(verts[tail], verts[head], g); tie(e2, in2) = add_edge(verts[head], verts[tail], g); if (!in1 || !in2) { std::cerr << "unable to add edge (" << head << "," << tail << ")" << std::endl; return -1; } capacity[e1] = cap; capacity[e2] = 0; reverse_edge[e1] = e2; reverse_edge[e2] = e1; } ++no_alines; break; default: /* unknown type of line */ err_no = EN18; goto error; } /* end of switch */ } /* end of input loop */ /* ----- all is red or error while reading ----- */ if ( feof (stdin) == 0 ) /* reading error */ { err_no=EN21; goto error; } if ( no_lines == 0 ) /* empty input */ { err_no = EN22; goto error; } if ( no_alines < m ) /* not enough arcs */ { err_no = EN19; goto error; } if ( out_degree(src, g) == 0 || out_degree(sink, g) == 0 ) /* no arc goes out of the source */ { err_no = EN20; goto error; } /* Thanks God! all is done */ return (0); /* ---------------------------------- */ error: /* error found reading input */ printf ( "\nline %ld of input - %s\n", no_lines, err_message[err_no] ); exit (1); return (0); /* to avoid warning */ }
bool operator<(P p) const { return tie(x,y) < tie(p.x,p.y); }
typename F::result_type operator()(Args&... args) { return apply_functor(f, bound_args, indexes(), tie(args...)); }
//! init virtual fucntion inheritance void Classhierarchy::inheritVirtualFunctions() { // prepare LUT for multiple declarations //map<SgNode *, set<SgNode *> > multDec; property_map< dbgType, boost::vertex_classhierarchy_t>::type chMap = boost::get( boost::vertex_classhierarchy, *this ); graph_traits< dbgType >::vertex_iterator vi,vend; tie(vi,vend) = vertices( *this ); //graph_traits< dbgType >::vertex_descriptor par=*vi, succ=*vi; // output info for(; vi!=vend; vi++) { //cerr << " BCH v i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; for( set<SgNode*>::iterator chd= chMap[*vi].defined.begin(); chd!= chMap[*vi].defined.end(); chd++) { SgFunctionDeclaration *funcDec = isSgFunctionDeclaration( *chd ); //cerr << " BCH chd " << funcDec->get_mangled_name().str()<< endl; // debug //cerr << " BCH chd " << funcDec->get_mangled_name().str()<< " "<< (int)funcDec->get_type() << endl; // debug } } // search for multiple declarations tie(vi,vend) = vertices( *this ); for(; vi!=vend; vi++) { for(set<SgNode*>::iterator chd= chMap[*vi].defined.begin(); chd!= chMap[*vi].defined.end(); chd++) { SgFunctionDeclaration *funcDec = isSgFunctionDeclaration( *chd ); bool found = true; while(found) { found = false; for(set<SgNode*>::iterator chdComp = chMap[*vi].defined.begin(); (chdComp!= chMap[*vi].defined.end())&&(!found); ) { SgFunctionDeclaration *compDec = isSgFunctionDeclaration( *chdComp ); if(chdComp != chd) { //if( compDec->get_type() == funcDec->get_type() ) { // ??? TODO fix type comparison? if(compareFunctionDeclarations(compDec, funcDec)) { //cerr << " BCH REM " << funcDec->get_mangled_name().str()<< " " << compDec->get_mangled_name().str() << endl; // debug chMap[*vi].multDeclarations[ funcDec ].insert( compDec ); found = true; chMap[*vi].defined.erase( chdComp ); // should return new iterator in newer STL standard?? //chVertexData::iterator chdComp2 = (chMap[*vi]).erase( chdComp ); //chdComp = chdComp2; //cerr << " BCH removing i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; } } if(!found) chdComp++; } } // found } //if( get( vertex_dbg_data, *this , *vi).get_id() == edges[i].get_sourceId() ) { //par = *vi; //parFound = true; //} } //typedef std::deque< boostVert > container; //cerr << " TOPO START " << endl; std::deque< dbgVertex > torder; try { boost::topological_sort(*this, std::back_inserter(torder)); } catch(boost::not_a_dag) { cerr << "CH - BOOST ERROR: NOT A DAG!!!!!??? " << endl; assert( false ); return; } //cerr << " TOPO END " << endl; //cerr << " -- " << endl; // debug for( std::deque< dbgVertex >::iterator vi=torder.begin(); vi!=torder.end(); vi++) { dbgVertex srcVert = *vi; // current vertex in the topo order //cerr << "XTOPO v i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { SgFunctionDeclaration *defMF = isSgFunctionDeclaration( *chd ); bool erased = true; while(erased) { erased = false; for(set<SgNode*>::iterator inhd= chMap[srcVert].inherited.begin(); inhd!= chMap[srcVert].inherited.end() && (!erased); ) { SgFunctionDeclaration *inhMF = isSgFunctionDeclaration( *inhd ); if(compareFunctionDeclarations(defMF, inhMF)) { // own function overrides, so delete old one chMap[srcVert].inherited.erase( *inhd ); erased = true; //cerr << " TOPO MF:"<< defMF->get_mangled_name().str()<< " overrides MF:"<< inhMF->get_mangled_name().str() << endl; // debug } if(!erased) inhd++; } } } // add to inherited functions for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { chMap[srcVert].inherited.insert( *chd ); } // inherit own methods to child classes graph_traits<dbgType>::in_edge_iterator ii,iend; tie(ii,iend) = in_edges(*vi, *this); for(; ii!=iend; ii++) { //dbgVertex srcVert = source(*ii,*this); // methods inherited from this class to the other one dbgVertex child = source(*ii, *this); //cerr << " T inherits to "<< get(vertex_index,*this,child)<< " i1" << get(vertex_index1, *this, child)<<","<< get(vertex_name, *this, child) << endl; //for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { for(set<SgNode*>::iterator chd= chMap[srcVert].inherited.begin(); chd!= chMap[srcVert].inherited.end(); chd++) { SgFunctionDeclaration *inhFunc = isSgFunctionDeclaration( *chd ); bool virt = false; //cerr << " TOPO v srch1" << endl; if(inhFunc->isVirtual()) virt = true; // also check multiple declarations //cerr << " TOPO v srch2" << endl; if(!virt) { for(set<SgNode *>::iterator si=chMap[srcVert].multDeclarations[inhFunc].begin(); si != chMap[srcVert].multDeclarations[inhFunc].end(); si++) { SgFunctionDeclaration *inhDup = isSgFunctionDeclaration( *si ); if(inhDup->isVirtual()) virt = true; //cerr << " TOPO v srch "<< inhDup->get_mangled_name().str() << endl; // debug } } // TODO check virtual inheritance? other declarations? if(virt) { //cerr << " VIRT " << inhFunc->get_mangled_name().str() << endl; // debug // and now... ?? } chMap[child].inherited.insert( inhFunc ); } //cerr << " BOOST v <<< " << get(vertex_index1, *this, boost::target(*ii,*this) )<<","<< get(vertex_name, *this, boost::target(*ii,*this) ) << endl; // debug } } // add own methods to all inherited ones for( std::deque< dbgVertex >::iterator vi=torder.begin(); vi!=torder.end(); vi++) { } }
/** Is there a selected vertex @return true if selected vertex exists */ bool cGraph::IsSelectedVertex() { vertex_iter_t vi, vi_end; tie(vi, vi_end) = vertices(myGraph); return mySelectedVertex != vi_end; }
inline size_t operator()(const tuple<int,int>& location) const { int x, y; tie (x, y) = location; return x * 1812433253 + y; }
//! search for all possible (virtual) function calls vector<SgMemberFunctionDeclaration*> Classhierarchy::searchMemberFunctionCalls(SgMemberFunctionDeclaration* mfCall) { vector<SgMemberFunctionDeclaration*> retvec; property_map< dbgType, boost::vertex_classhierarchy_t>::type chMap = boost::get( boost::vertex_classhierarchy, *this ); SgClassDefinition *classDef = mfCall->get_scope(); SgName classname = classDef->get_qualified_name(); // MANGLE string cnamestr = classname.str(); graph_traits< dbgType >::vertex_iterator vi,vend; dbgVertex vdesc = *vi; bool foundVertex = false; tie(vi,vend) = vertices( *this ); for(; vi!=vend; vi++) { //cerr << " BCH v i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; if( get(vertex_dbg_data, *this, *vi).get_typeName() == cnamestr ) { //cerr << " SMF srch "<< cnamestr <<" vi "<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; vdesc = *vi; foundVertex = true; break; } } if(!foundVertex) { cerr << " SMF srch "<< cnamestr <<" vi "<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; } assert( foundVertex ); set<dbgVertex> treeset; treeset.insert( vdesc ); // first find "highest" class in CH that still provides this MF dbgVertex vhighest = vdesc; // first assume its the current one graph_traits<dbgType>::out_edge_iterator oi,oend; tie(oi,oend) = out_edges( vdesc, *this); for(; oi!=oend; oi++) { //cerr << " SMF inherits from "<< get(vertex_index,*this,target(*oi,*this))<< " i1" << get(vertex_index1, *this, target(*oi,*this))<<","<< get(vertex_name, *this, target(*oi,*this)) << endl; // does any of the base classes implement the member function? bool noParentImpl = true; // check if this base class also implements MF for(set<SgNode*>::iterator chd= chMap[target(*oi,*this)].inherited.begin(); chd!= chMap[target(*oi,*this)].inherited.end(); chd++) { SgFunctionDeclaration *inhFunc = isSgFunctionDeclaration( *chd ); bool virt = false; //cerr << " TOPO v srch1" << endl; if(inhFunc->isVirtual()) virt = true; if( (virt) && (compareFunctionDeclarations(inhFunc,mfCall)) ) { // remeber for traversal treeset.insert( target(*oi, *this) ); noParentImpl = false; } } if(noParentImpl) { // we found it vhighest = target(*oi, *this); break; } } //cerr << " SMF high "<< cnamestr <<" vi "<< get(vertex_index,*this,vhighest)<< " i1" << get(vertex_index1, *this, vhighest)<<","<< get(vertex_name, *this, vhighest) << endl; // now traverse class hierachy downwards, for all children that implement this function, add to set set<dbgVertex> tovisit; set<dbgVertex> visited; tovisit.insert( vhighest ); //hier weiter while( tovisit.size() > 0 ) { dbgVertex currVert = *(tovisit.begin()); tovisit.erase( currVert ); visited.insert( currVert ); //cerr << " SMF visi "<< get(vertex_index,*this,currVert)<< " i1" << get(vertex_index1, *this, currVert)<<","<< get(vertex_name, *this, currVert) << endl; for(set<SgNode*>::iterator chd= chMap[currVert].defined.begin(); chd!= chMap[currVert].defined.end(); chd++) { SgMemberFunctionDeclaration*inhFunc = isSgMemberFunctionDeclaration( *chd ); if(compareFunctionDeclarations(inhFunc,mfCall)) { retvec.push_back( inhFunc ); } } graph_traits<dbgType>::in_edge_iterator ii,iend; tie(ii,iend) = in_edges( currVert, *this); for(; ii!=iend; ii++) { dbgVertex child = source(*ii, *this); // only insert of not already visited set<dbgVertex>::iterator found = visited.find( child ); if(found == visited.end()) tovisit.insert( child ); } } //retvec.push_back( mfCall ); return retvec; }
int main(int argc, char *argv[]) { string inputFile = "./dissect/as/as20000102.dimacs"; string outputFile = "./graph"; bool display_output = true; bool write_graph_files = true; bool gro_calc = false; bool ncp_calc = false; int core_to_start = -1; //User input for(int i=1;i<argc;i++) { stringstream ss; if(strcmp(argv[i], "-i")==0) inputFile = argv[i+1]; if(strcmp(argv[i], "-o")==0) outputFile = argv[i+1]; if(strcmp(argv[i], "-silent")==0) display_output = false; if(strcmp(argv[i], "-nofile")==0) write_graph_files = false; if(strcmp(argv[i], "-gromov")==0) gro_calc = true; if(strcmp(argv[i], "-ncp")==0) ncp_calc = true; if(strcmp(argv[i], "-core")==0) core_to_start = atoi(argv[i+1]); } ////Default values if(inputFile.length()==0) { cerr<<"You must provide an input file\n"; exit(EXIT_FAILURE); } ////////////////////////////////////////////////////////////// //----------------------------------------------------------- ////////////////////////////////////////////////////////////// Graph G_o = loadGraph(inputFile,"\t",false); Graph G = connected(G_o); vector<int> core; vector<v_size_t> distances; vector<v_size_t> num_paths; v_size_t N_paths,D,n; int max_core = 0; double A_d, A_p; A_d = 0; A_p = 0; D = 0; N_paths = 0; n = num_vertices(G); graph_traits<Graph>::vertex_iterator vi, vie; property_map<Graph, vertex_index_t>::type index = get(vertex_index,G); core = k_core(G); for(int i=0;i<core.size();++i) { if(core[i] > max_core) max_core = core[i]; } if(core_to_start<=0) core_to_start = max_core; for(tie(vi,vie) = vertices(G); vi != vie; ++vi) { Vert v = *vi; //cout<<G[v].core_num<<" "; BFS_source_all(v,G,distances,num_paths); size_t size = distances.size(); for(size_t i=0;i<size;++i) { if(distances[i] > D) D = distances[i]; A_p += num_paths[i] * distances[i]; A_d += distances[i]; N_paths += num_paths[i]; } } A_p /= N_paths; A_d /= (pow(n, 2) - n); cout<<"Max Core: "<<max_core<<" The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n<<"\n"; cout.flush(); string periph_diam = outputFile; string collapse_diam = outputFile; string core_diam = outputFile; ofstream file_periph; ofstream file_collapse; ofstream file_core; periph_diam.append("_periph_diam.out"); collapse_diam.append("_collapse_diam.out"); core_diam.append("_core_diam.out"); file_periph.open(periph_diam.c_str()); file_collapse.open(collapse_diam.c_str()); file_core.open(core_diam.c_str()); file_periph<<(max_core+1)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n"; file_collapse<<(max_core+1)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n"; file_core<<(max_core+1)<<"\t"<<0<<"\t"<<0<<"\t"<<"\n"; Graph G_core, G_periph, G_collapse; vector<v_size_t> core_list; vector<v_size_t> periph_list; for(int i=1;i<=max_core;i++) periph_list.push_back(i); for(int i=max_core; i>0; --i) { core_list.push_back(i); periph_list.pop_back(); if(i<=core_to_start) { G_core = get_k_shells(core_list,G); G_periph = get_k_shells(periph_list,G); G_collapse = collapse_core(i,G); stringstream ssperiph; ssperiph<<i; string outputPeriph = outputFile; string outputCore = outputFile; string outputCollapse = outputFile; outputPeriph.append("_periph_"); outputCore.append("_core_"); outputCollapse.append("_collapse_"); outputPeriph.append(ssperiph.str()); outputCore.append(ssperiph.str()); outputCollapse.append(ssperiph.str()); outputPeriph.append(".dimacs"); outputCore.append(".dimacs"); outputCollapse.append(".dimacs"); if(write_graph_files) { write_dimacs(G_periph,outputPeriph); write_dimacs(G_core,outputCore); write_dimacs(G_collapse,outputCollapse); } //Need to make something that checks number of connected components, and then runs this on each one. Just because the whole graph is connected doesn't mean the cores have to be. D = 0; v_size_t n_core = num_vertices(G_core); A_p = 0; A_d = 0; N_paths = 0; for(tie(vi,vie) = vertices(G_core); vi != vie; ++vi) { Vert v = *vi; BFS_source_all(v,G_core,distances,num_paths); size_t size = distances.size(); for(size_t j=0;j<size;++j) { if(distances[j] > D) D = distances[j]; A_p += num_paths[j]*distances[j]; A_d += distances[j]; N_paths += num_paths[j]; } } A_p /= N_paths; vector<bool> found(n_core,false); v_size_t current_comp = 0; vector<v_size_t> comp_size; vector<v_size_t> component(n_core); index = get(vertex_index,G_core); for(tie(vi,vie)=vertices(G_core);vi!=vie;++vi) { Vert v = *vi; v_size_t vind = index[v]; v_size_t current_comp_size = 0; if(!found[vind]) { BFS_vertices_found(v,G_core,found,current_comp,component,current_comp_size); comp_size.push_back(current_comp_size); ++current_comp; } } if(display_output) cout<<"\nCore: "<<i<<"\n"; double sum_of_components = 0; if(display_output) cout<<"# of components in core: "<<comp_size.size()<<" Size of core: "<<num_vertices(G_core)<<"\n"; for(size_t j=0;j<comp_size.size();++j) { if(comp_size[j] > (num_vertices(G_core)/10.0) && display_output) cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n"; sum_of_components += pow(comp_size[j],2)-comp_size[j]; } A_d /= sum_of_components; if(display_output) cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_core<<"\n"; file_core<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n"; cout.flush(); ////////////////////////////////////////////// if(gro_calc && n_core>4) { G_core = connected(G_core); //cout<<"Vertices in new core: "<<num_vertices(G_core)<<"\n"; BFS_distance(G_core); vector< vector<double> > delta = calc_gromov(G_core,D); stringstream ss,tt; ss<<i; unsigned long numQuad = 0; for(size_t j=0;j<delta.size();++j) numQuad += delta[j][0]; ofstream outGrom; string outputFileGrom = outputFile; outputFileGrom.append("_gromov_core_"); outputFileGrom.append(ss.str()); outputFileGrom.append(".txt"); outGrom.open(outputFileGrom.c_str()); tt<<i; ofstream outAvg; string outputFileAvg = outputFile; outputFileAvg.append("_avg_distr_core_"); outputFileAvg.append(tt.str()); outputFileAvg.append(".txt"); outAvg.open(outputFileAvg.c_str()); outGrom<<"#Note: Hyperbolicity only calculated on largest component of core\n"; outGrom<<"#Column format: \n"; outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n"; for(size_t j=0;j<delta.size();++j) { outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n"; } outGrom<<"#Column format: \n"; outGrom<<"#Delta\tPercent of quadruplets for each length\n"; for(size_t j=1;j<delta[0].size();j++) { //size_t size = delta[i].size(); outGrom<<(j-1)/2.0<<"\t"; for(size_t k=0;k<delta.size();k++) { if(delta[k][0]!=0) (delta[k])[j] = (delta[k])[j]/(delta[k])[0]; outGrom<<delta[k][j]<<"\t"; } outGrom<<"\n"; } for(size_t k=0;k<delta.size();k++) { double avg = 0; for(size_t j=1;j<delta[k].size();j++) { avg += delta[k][j]*(j-1)/2.0; } outAvg<<k+1<<"\t"<<avg<<"\n"; } outGrom.close(); outAvg.close(); } //////////////////////////////////////////////////////// v_size_t n_periph = num_vertices(G_periph); found.assign(n_periph,false); current_comp = 0; comp_size.clear(); component.assign(n_periph,0); index = get(vertex_index,G_periph); for(tie(vi,vie)=vertices(G_periph);vi!=vie;++vi) { Vert v = *vi; v_size_t vind = index[v]; v_size_t current_comp_size = 0; if(!found[vind]) { BFS_vertices_found(v,G_periph,found,current_comp,component,current_comp_size); comp_size.push_back(current_comp_size); ++current_comp; } } if(display_output) cout<<"# of components in periphery: "<<comp_size.size()<<" Size of periphery: "<<num_vertices(G_periph)<<"\n"; for(size_t j=0;j<comp_size.size();++j) if(comp_size[j] > (num_vertices(G_periph)/10.0) && display_output) cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n"; G_periph = connected(G_periph); n_periph = num_vertices(G_periph); ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //ncp ////////////////////////////////////////////////////////////////////// // v_size_t max_community = n_periph/2; // vector<double> ncp_periph = ncp_calc(G_periph,max_community,1,.001,false); // stringstream ssncp; // ssncp<<i; // string outputNcp = outputFile; // ofstream output_file_ncp; // outputNcp.append("_ncp_periph_"); // outputNcp.append(ssncp.str()); // outputNcp.append(".txt"); // output_file_ncp.open(outputNcp.c_str()); // for(v_size_t k=0; k<max_community;++k) // output_file_ncp<<(k+1)<<"\t"<<ncp_periph[k]<<"\n"; // output_file_ncp.close(); // string label = outputFile; // label.append(" ncp plot"); // string title = outputFile; // title.append(" NCP Plot"); // vector<int> int_to_vec; // int_to_vec.push_back(2); // vector<string> string_to_vec; // string_to_vec.push_back(label); // string outputPNG = ""; // outputPNG.append(outputFile); // outputPNG.append("_ncp_periph_"); // outputPNG.append(ssncp.str()); // outputPNG.append("_ncp_plot"); // produce_loglog_plot(outputNcp,outputPNG,outputPNG,int_to_vec,string_to_vec,title,"Community size", "Conductance","",false); // ///////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// D = 0; A_p = 0; A_d = 0; N_paths = 0; for(tie(vi,vie) = vertices(G_periph); vi != vie; ++vi) { Vert v = *vi; BFS_source_all(v,G_periph,distances,num_paths); size_t size = distances.size(); for(size_t j=0;j<size;++j) { if(distances[j] > D) D = distances[j]; A_p += num_paths[j]*distances[j]; A_d += distances[j]; N_paths += num_paths[j]; } } A_p /= N_paths; A_d /= (pow(n_periph,2)-n_periph); if(gro_calc && n_periph>4) { BFS_distance(G_periph); vector< vector<double> > delta = calc_gromov(G_periph,D); stringstream ss,tt; ss<<i; unsigned long numQuad = 0; for(size_t j=0;j<delta.size();++j) { numQuad += delta[j][0]; } ofstream outGrom; string outputFileGrom = outputFile; outputFileGrom.append("_gromov_periph_"); outputFileGrom.append(ss.str()); outputFileGrom.append(".txt"); outGrom.open(outputFileGrom.c_str()); tt<<i; ofstream outAvg; string outputFileAvg = outputFile; outputFileAvg.append("_avg_distr_periph_"); outputFileAvg.append(tt.str()); outputFileAvg.append(".txt"); outAvg.open(outputFileAvg.c_str()); outGrom<<"#Column format: \n"; outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n"; for(size_t j=0;j<delta.size();++j) { outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n"; } outGrom<<"#Column format: \n"; outGrom<<"#Delta\tPercent of quadruplets for each length\n"; for(size_t j=1;j<delta[0].size();j++) { //size_t size = delta[i].size(); outGrom<<(j-1)/2.0<<"\t"; for(size_t k=0;k<delta.size();k++) { if(delta[k][0]!=0) (delta[k])[j] = (delta[k])[j]/(delta[k])[0]; outGrom<<delta[k][j]<<"\t"; } outGrom<<"\n"; } for(size_t k=0;k<delta.size();k++) { double avg = 0; for(size_t j=1;j<delta[k].size();j++) { avg += delta[k][j]*(j-1)/2.0; } outAvg<<k+1<<"\t"<<avg<<"\n"; } outGrom.close(); outAvg.close(); } //cout<<"\nCore: "<<i<<"\n"; if(display_output) cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_periph<<"\n"; file_periph<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n"; cout.flush(); ////////////////////////////////////////////////// ////////////////////////////////////////////////// D = 0; v_size_t n_collapse = num_vertices(G_collapse); A_p = 0; A_d = 0; N_paths = 0; for(tie(vi,vie) = vertices(G_collapse); vi != vie; ++vi) { Vert v = *vi; BFS_source_all(v,G_collapse,distances,num_paths); size_t size = distances.size(); for(size_t j=0;j<size;++j) { if(distances[j] > D) D = distances[j]; A_p += num_paths[j]*distances[j]; A_d += distances[j]; N_paths += num_paths[j]; } } A_p /= N_paths; found.assign(n_collapse,false); current_comp = 0; comp_size.clear(); component.assign(n_collapse,0); index = get(vertex_index,G_collapse); for(tie(vi,vie)=vertices(G_collapse);vi!=vie;++vi) { Vert v = *vi; v_size_t vind = index[v]; v_size_t current_comp_size = 0; if(!found[vind]) { BFS_vertices_found(v,G_collapse,found,current_comp,component,current_comp_size); comp_size.push_back(current_comp_size); ++current_comp; } } sum_of_components = 0; if(display_output) cout<<"# of components in collapse: "<<comp_size.size()<<" Size of collapse: "<<num_vertices(G_collapse)<<"\n"; cout.flush(); for(size_t j=0;j<comp_size.size();++j) { if(comp_size[j] > (num_vertices(G_collapse)/10.0) && display_output) cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n"; sum_of_components += pow(comp_size[j],2)-comp_size[j]; } A_d /= sum_of_components; if(display_output) cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_collapse<<"\n"; file_collapse<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n"; cout.flush(); ////////////////////////////////////////////// if(gro_calc && n_collapse>4) { BFS_distance(G_collapse); vector< vector<double> > delta = calc_gromov(G_collapse,D); stringstream ss,tt; ss<<i; unsigned long numQuad = 0; for(size_t j=0;j<delta.size();j++) numQuad += delta[j][0]; ofstream outGrom; string outputFileGrom = outputFile; outputFileGrom.append("_gromov_collapse_"); outputFileGrom.append(ss.str()); outputFileGrom.append(".txt"); outGrom.open(outputFileGrom.c_str()); tt<<i; ofstream outAvg; string outputFileAvg = outputFile; outputFileAvg.append("_avg_distr_collapse_"); outputFileAvg.append(tt.str()); outputFileAvg.append(".txt"); outAvg.open(outputFileAvg.c_str()); outGrom<<"#Column format: \n"; outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n"; for(size_t j=0;j<delta.size();j++) { outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n"; } outGrom<<"#Column format: \n"; outGrom<<"#Delta\tPercent of quadruplets for each length\n"; for(size_t j=1;j<delta[0].size();j++) { //size_t size = delta[i].size(); outGrom<<(j-1)/2.0<<"\t"; for(size_t k=0;k<delta.size();k++) { if(delta[k][0]!=0) (delta[k])[j] = (delta[k])[j]/(delta[k])[0]; outGrom<<delta[k][j]<<"\t"; } outGrom<<"\n"; } for(size_t k=0;k<delta.size();k++) { double avg = 0; for(size_t j=1;j<delta[k].size();j++) { avg += delta[k][j]*(j-1)/2.0; } outAvg<<k+1<<"\t"<<avg<<"\n"; } outGrom.close(); outAvg.close(); } } //////////////////////////////////////////////////////// } file_periph.close(); file_collapse.close(); file_core.close(); return(0); }
void write_scaled_labeled_graphviz(Graph & G, string output_file, vector<double> color, vector<size_t> sizes, bool directed) { ofstream output; output.open(output_file.c_str()); double color_min = color[0]; double color_max = color[0]; size_t size_min = sizes[0]; size_t size_max = sizes[0]; v_size_t n = num_vertices(G); if (color.size() != sizes.size() || color.size() != n) { cout<<"Color vector, size vector must all be of length num_nodes in graph. Exiting. \n"; exit(EXIT_FAILURE); } for (size_t i = 0; i < color.size(); ++i) { if(color[i] > color_max) color_max = color[i]; if(color[i] < color_min) color_min = color[i]; if(sizes[i] > size_max) size_max = sizes[i]; if(sizes[i] < size_min) size_min = sizes[i]; } if (color_max > 1 or color_min < 0) { cout<<"Color vector must be in range [0,1]. Exiting.\n"; exit(EXIT_FAILURE); } output<<"Graph color {\n"; output<<"splines=false;\n"; graph_traits<Graph>::edge_iterator eit, eitend; graph_traits<Graph>::vertex_iterator vit, vitend; property_map<Graph, vertex_index_t>::type index = get(vertex_index,G); for(tie(vit,vitend)=vertices(G);vit!=vitend;++vit) { Vert v = *vit; v_size_t vi = index[v]; char rgb[8]; double width = .75; if (size_max != size_min) width = 0.1 + ((double) sizes[vi] - size_min) / (double) (size_max - size_min); double val = 0.5; val = color[vi]; get_rgb_value(rgb, val); stringstream ss; string label; ss<<vi; ss>>label; output<<vi<<"[label=\""<<label<<"\", width="<<width<<", shape=circle, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n"; } if(directed) { for(tie(eit,eitend)=edges(G);eit!=eitend;++eit) { Edge e = *eit; Vert u,v; u = source(e,G); v = target(e,G); v_size_t ui = index[u]; v_size_t vi = index[v]; output<<ui<<" -- "<<vi<<";\n"; } } else { cout<<"Graph viz undirected\n"; UGraph UG((v_Usize_t) n ); for(tie(eit,eitend)=edges(G);eit!=eitend;++eit) { Edge e = *eit; Vert s = source(e,G); Vert t = target(e,G); // cout<<"s "<<s<<" t "<<t<<"\n"; long ui = index[s]; long vi = index[t]; //cout<<"ui "<<ui<<" vi "<<vi<<"\n"; UVert u = vertex(ui,UG); UVert v = vertex(vi,UG); //cout<<"u "<<u<<" v "<<v<<"\n"; UEdge exist; bool yes1,yes2; tie(exist,yes1) = edge(u,v,UG); tie(exist,yes2) = edge(v,u,UG); if(!yes1 && !yes2) add_edge(u,v,UG); } graph_traits<UGraph>::edge_iterator uit, uitend; property_map<UGraph, vertex_index_t>::type u_index = get(vertex_index,UG); for(tie(uit,uitend)=edges(UG);uit!=uitend;++uit) { UEdge e = *uit; UVert u,v; u = source(e,UG); v = target(e,UG); long ui = u_index[u]; long vi = u_index[v]; output<<ui<<" -- "<<vi<<";\n"; } } output<<"}"; output.close(); }
/* This function produces a graphviz file of the graph passed to it, but it colors the nodes based on the colors provided in color. All nodes are same size, though the nodes in the vector square_nodes are doubled in size and square as a way of highlighting important nodes. */ void write_graphviz(Graph & G, string output_file, vector<double> color, vector<int> square_nodes, bool directed) { ofstream output; output.open(output_file.c_str()); double min = color[0]; double max = color[0]; v_size_t n = num_vertices(G); for(size_t i = 0; i < color.size(); ++i) { if(color[i]>max) max = color[i]; if(color[i]<min) min = color[i]; } output<<"Graph color {\n"; output<<"splines=false;\n"; graph_traits<Graph>::edge_iterator eit, eitend; graph_traits<Graph>::vertex_iterator vit, vitend; property_map<Graph, vertex_index_t>::type index = get(vertex_index,G); for (tie(vit,vitend) = vertices(G); vit != vitend; ++vit) { Vert v = *vit; v_size_t vi = index[v]; char rgb[8]; double width=0.2; double val; if (color.size() != n && G[v].prevIndices.size() != 0) val = ((double) color[G[v].prevIndices[0]] - min) / (double) (max - min); else val = ((double) color[vi] - min) / (double) (max - min); get_rgb_value(rgb,val); int found = binarySearch(square_nodes,vi); if(found==-1) output<<vi<<"[label=\"\", width="<<width<<", shape=circle, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n"; else output<<vi<<"[label=\"\", width="<<2.0*width<<", shape=square, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n"; } if(directed) { for(tie(eit,eitend)=edges(G);eit!=eitend;++eit) { Edge e = *eit; Vert u,v; u = source(e,G); v = target(e,G); v_size_t ui = index[u]; v_size_t vi = index[v]; output<<ui<<" -- "<<vi<<";\n"; } } else { cout<<"Graph viz undirected\n"; UGraph UG((v_Usize_t) n ); for(tie(eit,eitend)=edges(G);eit!=eitend;++eit) { Edge e = *eit; Vert s = source(e,G); Vert t = target(e,G); // cout<<"s "<<s<<" t "<<t<<"\n"; long ui = index[s]; long vi = index[t]; //cout<<"ui "<<ui<<" vi "<<vi<<"\n"; UVert u = vertex(ui,UG); UVert v = vertex(vi,UG); //cout<<"u "<<u<<" v "<<v<<"\n"; UEdge exist; bool yes1,yes2; tie(exist,yes1) = edge(u,v,UG); tie(exist,yes2) = edge(v,u,UG); if(!yes1 && !yes2) add_edge(u,v,UG); } graph_traits<UGraph>::edge_iterator uit, uitend; property_map<UGraph, vertex_index_t>::type u_index = get(vertex_index,UG); for(tie(uit,uitend)=edges(UG);uit!=uitend;++uit) { UEdge e = *uit; UVert u,v; u = source(e,UG); v = target(e,UG); long ui = u_index[u]; long vi = u_index[v]; output<<ui<<" -- "<<vi<<";\n"; } } output<<"}"; output.close(); }
bool johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1, DistanceMatrix& D, VertexID id1, Weight w1, const BinaryPredicate& compare, const BinaryFunction& combine, const Infinity& inf, DistanceZero zero) { typedef graph_traits<VertexAndEdgeListGraph> Traits1; typedef typename property_traits<Weight>::value_type DT; function_requires< BasicMatrixConcept<DistanceMatrix, typename Traits1::vertices_size_type, DT> >(); typedef typename Traits1::directed_category DirCat; bool is_undirected = is_same<DirCat, undirected_tag>::value; typedef adjacency_list<vecS, vecS, directedS, property< vertex_distance_t, DT>, property< edge_weight_t, DT, property< edge_weight2_t, DT > > > Graph2; typedef graph_traits<Graph2> Traits2; Graph2 g2(num_vertices(g1) + 1); typename property_map<Graph2, edge_weight_t>::type w = get(edge_weight, g2); typename property_map<Graph2, edge_weight2_t>::type w_hat = get(edge_weight2, g2); typename property_map<Graph2, vertex_distance_t>::type d = get(vertex_distance, g2); typedef typename property_map<Graph2, vertex_index_t>::type VertexID2; VertexID2 id2 = get(vertex_index, g2); // Construct g2 where V[g2] = V[g1] U {s} // and E[g2] = E[g1] U {(s,v)| v in V[g1]} std::vector<typename Traits1::vertex_descriptor> verts1(num_vertices(g1) + 1); typename Traits2::vertex_descriptor s = *vertices(g2).first; { typename Traits1::vertex_iterator v, v_end; int i = 1; for (tie(v, v_end) = vertices(g1); v != v_end; ++v, ++i) { typename Traits2::edge_descriptor e; bool z; tie(e, z) = add_edge(s, get(id1, *v) + 1, g2); put(w, e, zero); verts1[i] = *v; } typename Traits1::edge_iterator e, e_end; for (tie(e, e_end) = edges(g1); e != e_end; ++e) { typename Traits2::edge_descriptor e2; bool z; tie(e2, z) = add_edge(get(id1, source(*e, g1)) + 1, get(id1, target(*e, g1)) + 1, g2); put(w, e2, get(w1, *e)); if (is_undirected) { tie(e2, z) = add_edge(get(id1, target(*e, g1)) + 1, get(id1, source(*e, g1)) + 1, g2); put(w, e2, get(w1, *e)); } } } typename Traits2::vertex_iterator v, v_end, u, u_end; typename Traits2::edge_iterator e, e_end; shared_array_property_map<DT,VertexID2> h(num_vertices(g2), id2); for (tie(v, v_end) = vertices(g2); v != v_end; ++v) put(d, *v, inf); put(d, s, zero); // Using the non-named parameter versions of bellman_ford and // dijkstra for portability reasons. dummy_property_map pred; bellman_visitor<> bvis; if (bellman_ford_shortest_paths (g2, num_vertices(g2), w, pred, d, combine, compare, bvis)) { for (tie(v, v_end) = vertices(g2); v != v_end; ++v) put(h, *v, get(d, *v)); // Reweight the edges to remove negatives for (tie(e, e_end) = edges(g2); e != e_end; ++e) { typename Traits2::vertex_descriptor a = source(*e, g2), b = target(*e, g2); put(w_hat, *e, combine(get(w, *e), (get(h, a) - get(h, b)))); } for (tie(u, u_end) = vertices(g2); u != u_end; ++u) { dijkstra_visitor<> dvis; dijkstra_shortest_paths (g2, *u, pred, d, w_hat, id2, compare, combine, inf, zero,dvis); for (tie(v, v_end) = vertices(g2); v != v_end; ++v) { if (*u != s && *v != s) { typename Traits1::vertex_descriptor u1, v1; u1 = verts1[get(id2, *u)]; v1 = verts1[get(id2, *v)]; D[get(id2, *u)-1][get(id2, *v)-1] = combine(get(d, *v), (get(h, *v) - get(h, *u))); } } } return true; } else return false; }
pair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) { const BasicBlock* out; bool defined; tie(out, defined) = const_cast<const Function*>(this)->GetBlock(block_id); return make_pair(const_cast<BasicBlock*>(out), defined); }
/** \brief Draw track information on the image Go through each vertex. Draw it as a circle. For each adjacent vertex to it. Draw a line to it. */ void FeatureGrouperVisualizer::Draw(){ TracksConnectionGraph::vertex_iterator vi, viend; TracksConnectionGraph::out_edge_iterator ei, eiend; TracksConnectionGraph::vertex_descriptor other_v; TracksConnectionGraph & graph = feature_grouper_->tracks_connection_graph_; cv::Point2f position_in_image, position_in_image2, position_in_world, position_to_draw; CvScalar color; char position_text[256]; for (tie(vi, viend) = vertices(graph); vi != viend; ++vi ){ // Convert position to image coordinate position_in_world = (graph)[*vi].pos; convert_to_image_coordinate(position_in_world, homography_matrix_, &position_in_image); TracksConnectionGraph::vertices_size_type num_components; // std::vector<TracksConnectionGraph::vertices_size_type> connected_components_map = feature_grouper_->GetConnectedComponentsMap(num_components); if (is_draw_inactive){ // Draw this track with only two colors (blue for those tracked for a long time, red otherwise) if(graph[*vi].previous_displacements.size() >= feature_grouper_->maximum_previous_points_remembered_){ color = CV_RGB(0,0,255); } else { color = CV_RGB(255,0,0); } circle(image_, position_in_image, 1, color); } else { if (graph[*vi].activated){ // color this vertex based on its assigned component_id color = ColorPallete::colors[graph[*vi].component_id % ColorPallete::NUM_COLORS_IN_PALLETE]; circle(image_, position_in_image, 1, color); } } // Write Text Information for this track if (is_draw_coordinate){ sprintf(position_text, "%d(%5.1f,%5.1f)", (graph)[*vi].id, position_in_world.x, position_in_world.y); position_to_draw.x = position_in_image.x + 5; position_to_draw.y = position_in_image.y + 5; putText(image_, position_text, position_to_draw, FONT_HERSHEY_PLAIN, 0.4, CV_RGB(128,128,0)); } // Draw lines to adjacent vertices (if the edge is active) for (tie(ei, eiend) = out_edges(*vi, graph); ei!=eiend; ++ei){ if (!graph[*ei].active) continue; // Get where this out_edge is pointing to other_v = target(*ei, graph); // Convert position to image coordinate position_in_world = (graph)[other_v].pos; convert_to_image_coordinate(position_in_world, homography_matrix_, &position_in_image2); line(image_, position_in_image, position_in_image2, color); } } }
int pip_play_guess() { /* 猜拳程式 */ int com; int pipkey; struct tm *qtime; time_t now; time(&now); qtime = localtime(&now); d.satisfy += (rand() % 3 + 2); count_tired(2, 2, "Y", 100, 1); d.shit += rand() % 3 + 2; do { if (d.death == 1 || d.death == 2 || d.death == 3) return 0; if (pip_mainmenu(0)) return 0; move(b_lines - 2, 0); clrtoeol(); move(b_lines, 0); clrtoeol(); move(b_lines, 0); prints ("\033[1;44;37m 猜拳选单 \033[46m[1]我出剪刀 [2]我出石头 [3]我出布啦 [4]猜拳记录 [Q]跳出: \033[m"); move(b_lines - 1, 0); clrtoeol(); pipkey = igetkey(); switch (pipkey) { #ifdef MAPLE case Ctrl('R'): if (currutmp->msgs[0].last_pid) { show_last_call_in(); my_write(currutmp->msgs[0].last_pid, "水球丢回去:"); } break; #endif // END MAPLE case '4': situ(); break; } } while ((pipkey != '1') && (pipkey != '2') && (pipkey != '3') && (pipkey != 'q') && (pipkey != 'Q')); com = rand() % 3; move(18, 0); clrtobot(); switch (com) { case 0: outs("小鸡:剪刀\n"); break; case 1: outs("小鸡:石头\n"); break; case 2: outs("小鸡:布\n"); break; } move(17, 0); switch (pipkey) { case '1': outs("你 :剪刀\n"); if (com == 0) tie(); else if (com == 1) lose(); else if (com == 2) win(); break; case '2': outs("你 :石头\n"); if (com == 0) win(); else if (com == 1) tie(); else if (com == 2) lose(); break; case '3': outs("你 :布\n"); if (com == 0) lose(); else if (com == 1) win(); else if (com == 2) tie(); break; case 'q': break; } return 0; }
bool operator==(P p) const { return tie(x,y)==tie(p.x,p.y); }
void TMap::initGraph() { locations.clear(); g.clear(); g = mygraph_t(rooms.size()*10);//FIXME weightmap = get(edge_weight, g); QMapIterator<int, TRoom *> it( rooms ); int roomCount=0; int edgeCount=0; while( it.hasNext() ) { it.next(); int i = it.key(); if( ! rooms.contains( i ) || rooms[i]->isLocked ) { continue; } roomCount++; location l; l.x = rooms[i]->x; l.y = rooms[i]->y; l.z = rooms[i]->z; locations.push_back( l ); if( rooms[i]->north != -1 && rooms.contains( rooms[i]->north ) && !rooms[rooms[i]->north]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_NORTH ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->north, g ); weightmap[e] = rooms[rooms[i]->north]->weight; } } if( rooms[i]->south != -1 && rooms.contains( rooms[i]->south ) && !rooms[rooms[i]->south]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_SOUTH ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->south, g ); weightmap[e] = rooms[rooms[i]->south]->weight; } } if( rooms[i]->northeast != -1 && rooms.contains( rooms[i]->northeast ) && !rooms[rooms[i]->northeast]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_NORTHEAST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->northeast, g ); weightmap[e] = rooms[rooms[i]->northeast]->weight; } } if( rooms[i]->east != -1 && rooms.contains( rooms[i]->east ) && !rooms[rooms[i]->east]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_EAST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->east, g ); weightmap[e] = rooms[rooms[i]->east]->weight; } } if( rooms[i]->west != -1 && rooms.contains( rooms[i]->west ) && !rooms[rooms[i]->west]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_WEST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->west, g ); weightmap[e] = rooms[rooms[i]->west]->weight; } } if( rooms[i]->southwest != -1 && rooms.contains( rooms[i]->southwest ) && !rooms[rooms[i]->southwest]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_SOUTHWEST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->southwest, g ); weightmap[e] = rooms[rooms[i]->southwest]->weight; } } if( rooms[i]->southeast != -1 && rooms.contains( rooms[i]->southeast ) && !rooms[rooms[i]->southeast]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_SOUTHEAST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->southeast, g ); weightmap[e] = rooms[rooms[i]->southeast]->weight; } } if( rooms[i]->northwest != -1 && rooms.contains( rooms[i]->northwest ) && !rooms[rooms[i]->northwest]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_NORTHWEST ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->northwest, g ); weightmap[e] = rooms[rooms[i]->northwest]->weight; } } if( rooms[i]->up != -1 && rooms.contains( rooms[i]->up ) && !rooms[rooms[i]->up]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_UP ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->up, g ); weightmap[e] = rooms[rooms[i]->up]->weight; } } if( rooms[i]->down != -1 && rooms.contains( rooms[i]->down ) && !rooms[rooms[i]->down]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_DOWN ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->down, g ); weightmap[e] = rooms[rooms[i]->down]->weight; } } if( rooms[i]->in != -1 && rooms.contains( rooms[i]->in ) && !rooms[rooms[i]->in]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_IN ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->in, g ); weightmap[e] = rooms[rooms[i]->in]->weight; } } if( rooms[i]->out != -1 && rooms.contains( rooms[i]->out ) && !rooms[rooms[i]->out]->isLocked ) { if( ! rooms[i]->hasExitLock( DIR_OUT ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, rooms[i]->out, g ); weightmap[e] = rooms[rooms[i]->out]->weight; } } if( rooms[i]->other.size() > 0 ) { QMapIterator<int, QString> it( rooms[i]->other ); while( it.hasNext() ) { it.next(); int _id = it.key(); if( ! rooms[i]->hasSpecialExitLock( _id, it.value() ) ) { edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( i, _id, g ); weightmap[e] = rooms[_id]->weight; } } } } mMapGraphNeedsUpdate = false; }
u32 commonPrefixLength(const NGHolder &ga, const ue2::unordered_map<NFAVertex, u32> &a_state_ids, const NGHolder &gb, const ue2::unordered_map<NFAVertex, u32> &b_state_ids) { vector<NFAVertex> a = getSortedVA(ga, a_state_ids); vector<NFAVertex> b = getSortedVA(gb, b_state_ids); /* upper bound on the common region based on local properties */ u32 max = cplCommonReachAndSimple(ga, a, gb, b); DEBUG_PRINTF("cpl upper bound %u\n", max); while (max > 0) { bool ok = true; /* shrink max region based on in-edges from outside the region */ for (size_t j = max; j > 0; j--) { for (auto u : inv_adjacent_vertices_range(a[j - 1], ga)) { u32 state_id = a_state_ids.at(u); if (state_id != NO_STATE && state_id >= max) { max = j - 1; DEBUG_PRINTF("lowering max to %u\n", max); goto next_vertex; } } for (auto u : inv_adjacent_vertices_range(b[j - 1], gb)) { u32 state_id = b_state_ids.at(u); if (state_id != NO_STATE && state_id >= max) { max = j - 1; DEBUG_PRINTF("lowering max to %u\n", max); goto next_vertex; } } next_vertex:; } /* Ensure that every pair of vertices has same out-edges to vertices in the region. */ for (size_t i = 0; ok && i < max; i++) { size_t a_count = 0; size_t b_count = 0; NFAGraph::out_edge_iterator ei, ee; for (tie(ei, ee) = out_edges(a[i], ga); ok && ei != ee; ++ei) { u32 sid = a_state_ids.at(target(*ei, ga)); if (sid == NO_STATE || sid >= max) { continue; } a_count++; NFAEdge b_edge; bool has_b_edge; tie(b_edge, has_b_edge) = edge(b[i], b[sid], gb); if (!has_b_edge) { max = i; ok = false; DEBUG_PRINTF("lowering max to %u due to edge %zu->%u\n", max, i, sid); break; } if (ga[*ei].top != gb[b_edge].top) { max = i; ok = false; DEBUG_PRINTF("tops don't match on edge %zu->%u\n", i, sid); } } NFAGraph::adjacency_iterator ai, ae; for (tie(ai, ae) = adjacent_vertices(b[i], gb); ok && ai != ae; ++ai) { u32 sid = b_state_ids.at(*ai); if (sid == NO_STATE || sid >= max) { continue; } b_count++; } if (a_count != b_count) { max = i; DEBUG_PRINTF("lowering max to %u due to a,b count " "(a_count=%zu, b_count=%zu)\n", max, a_count, b_count); ok = false; } } if (ok) { DEBUG_PRINTF("survived checks, returning cpl %u\n", max); return max; } } DEBUG_PRINTF("failed to find any common region\n"); return 0; }
friend bool operator == ( const permission_level_weight& lhs, const permission_level_weight& rhs ) { return tie( lhs.permission, lhs.weight ) == tie( rhs.permission, rhs.weight ); }
inline void InpaintingAlgorithmWithVerification(TVertexListGraph& g, TInpaintingVisitor vis, TBoundaryStatusMap* boundaryStatusMap, TPriorityQueue* boundaryNodeQueue, TKNNFinder knnFinder, TBestNeighborFinder& bestNeighborFinder, TManualNeighborFinder& manualNeighborFinder, TPatchInpainter inpaint_patch) { BOOST_CONCEPT_ASSERT((InpaintingVisitorConcept<TInpaintingVisitor, TVertexListGraph>)); typedef typename boost::graph_traits<TVertexListGraph>::vertex_descriptor VertexDescriptorType; unsigned int numberOfManualVerifications = 0; while(true) { // Find the next target to in-paint. Some of the nodes in the priority queue // can be already filled (they get "covered up" when a patch is filled around // a target node). So we do not just process the node at the front of the queue, // we also check that it has not been filled by looking at its value in the boundaryStatusMap VertexDescriptorType targetNode; do { if( (*boundaryNodeQueue).empty() ) { std::cout << "Inpainting complete. There were " << numberOfManualVerifications << " manual verifications required." << std::endl; vis.InpaintingComplete(); return; //terminate if the queue is empty. } targetNode = (*boundaryNodeQueue).top(); (*boundaryNodeQueue).pop(); } while( get(*boundaryStatusMap, targetNode) == false); //} while( get(boundaryStatusMap, targetNode) == false && get(fillStatusMap, targetNode)); // Notify the visitor that we have a hole target center. vis.DiscoverVertex(targetNode); // Find the source node that matches best to the target node typename boost::graph_traits<TVertexListGraph>::vertex_iterator vi,vi_end; tie(vi,vi_end) = vertices(g); std::vector<VertexDescriptorType> outputContainer(knnFinder.GetK()); knnFinder(vi, vi_end, targetNode, outputContainer.begin()); VertexDescriptorType sourceNode = bestNeighborFinder(outputContainer.begin(), outputContainer.end(), targetNode); vis.PotentialMatchMade(targetNode, sourceNode); if(!vis.AcceptMatch(targetNode, sourceNode)) { numberOfManualVerifications++; std::cout << "So far there have been " << numberOfManualVerifications << " manual verifications." << std::endl; std::cout << "Automatic match not accepted!" << std::endl; sourceNode = manualNeighborFinder(outputContainer.begin(), outputContainer.end(), targetNode); } // Do the in-painting of the target patch from the source patch. // the inpaint_patch functor should take care of calling // "vis.paint_vertex(target, source)" on the individual vertices in the patch. inpaint_patch(targetNode, sourceNode, vis); vis.FinishVertex(targetNode, sourceNode); } // end main iteration loop }
friend bool operator == ( const key_weight& lhs, const key_weight& rhs ) { return tie( lhs.key, lhs.weight ) == tie( rhs.key, rhs.weight ); }
void TMap::initGraph() { QTime _time; _time.start(); locations.clear(); roomidToIndex.clear(); g.clear(); g = mygraph_t(); weightmap = get(edge_weight, g); QList<TRoom*> roomList = mpRoomDB->getRoomPtrList(); int roomCount=0; int edgeCount=0; for( int _k=0; _k<roomList.size(); _k++ ) { TRoom * pR = roomList[_k]; int i = pR->getId(); if( pR->isLocked || i < 1 ) { continue; } roomCount++; // int roomExits = edgeCount; location l; l.x = pR->x; l.y = pR->y; l.z = pR->z; l.id = pR->getId(); l.area = pR->getAreaId(); locations.push_back( l ); } for(unsigned int i=0;i<locations.size();i++){ roomidToIndex[locations[i].id] = i; indexToRoomid[i] = locations[i].id; } for( int _k=0; _k<roomList.size(); _k++ ){ TRoom * pR = roomList[_k]; if( pR->isLocked || !roomidToIndex.contains(pR->getId()) ) { continue; } int roomIndex = roomidToIndex[pR->getId()]; TRoom * pN = mpRoomDB->getRoom( pR->getNorth() ); TRoom * pNW = mpRoomDB->getRoom( pR->getNorthwest() ); TRoom * pNE = mpRoomDB->getRoom( pR->getNortheast() ); TRoom * pS = mpRoomDB->getRoom( pR->getSouth() ); TRoom * pSW = mpRoomDB->getRoom( pR->getSouthwest() ); TRoom * pSE = mpRoomDB->getRoom( pR->getSoutheast() ); TRoom * pW = mpRoomDB->getRoom( pR->getWest() ); TRoom * pE = mpRoomDB->getRoom( pR->getEast() ); TRoom * pUP = mpRoomDB->getRoom( pR->getUp() ); TRoom * pDOWN = mpRoomDB->getRoom( pR->getDown() ); TRoom * pIN = mpRoomDB->getRoom( pR->getIn() ); TRoom * pOUT = mpRoomDB->getRoom( pR->getOut() ); QMap<QString, int> exitWeights = pR->getExitWeights(); if( pN && !pN->isLocked ) { if( !pR->hasExitLock( DIR_NORTH ) ) { //edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getNorth()], g ); if( exitWeights.contains("n")) weightmap[e] = pR->getExitWeight("n"); else weightmap[e] = pN->getWeight(); } } if( pS && !pS->isLocked ) { if( !pR->hasExitLock( DIR_SOUTH ) ) { //edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getSouth()], g ); if( exitWeights.contains("s")) weightmap[e] = pR->getExitWeight("s"); else weightmap[e] = pS->getWeight(); } } if( pNE && !pNE->isLocked ) { if( !pR->hasExitLock( DIR_NORTHEAST ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getNortheast()], g ); if( exitWeights.contains("ne")) weightmap[e] = pR->getExitWeight("ne"); else weightmap[e] = pNE->getWeight(); } } if( pE && !pE->isLocked ) { if( !pR->hasExitLock( DIR_EAST ) ) { //edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getEast()], g ); if( exitWeights.contains("e")) weightmap[e] = pR->getExitWeight("e"); else weightmap[e] = pE->getWeight(); } } if( pW && !pW->isLocked ) { if( !pR->hasExitLock( DIR_WEST ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getWest()], g ); if( exitWeights.contains("w")) weightmap[e] = pR->getExitWeight("w"); else weightmap[e] = pW->getWeight(); } } if( pSW && !pSW->isLocked ) { if( !pR->hasExitLock( DIR_SOUTHWEST ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getSouthwest()], g ); if( exitWeights.contains("sw")) weightmap[e] = pR->getExitWeight("sw"); else weightmap[e] = pSW->getWeight(); } } if( pSE && !pSE->isLocked ) { if( !pR->hasExitLock( DIR_SOUTHEAST ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getSoutheast()], g ); if( exitWeights.contains("se")) weightmap[e] = pR->getExitWeight("se"); else weightmap[e] = pSE->getWeight(); } } if( pNW && !pNW->isLocked ) { if( !pR->hasExitLock( DIR_NORTHWEST ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getNorthwest()], g ); if( exitWeights.contains("nw")) weightmap[e] = pR->getExitWeight("nw"); else weightmap[e] = pNW->getWeight(); } } if( pUP && !pUP->isLocked ) { if( !pR->hasExitLock( DIR_UP ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getUp()], g ); if( exitWeights.contains("up")) weightmap[e] = pR->getExitWeight("up"); else weightmap[e] = pUP->getWeight(); } } if( pDOWN && !pDOWN->isLocked ) { if( !pR->hasExitLock( DIR_DOWN ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getDown()], g ); if( exitWeights.contains("down")) weightmap[e] = pR->getExitWeight("down"); else weightmap[e] = pDOWN->getWeight(); } } if( pIN && !pIN->isLocked ) { if( !pR->hasExitLock( DIR_IN ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getIn()], g ); if( exitWeights.contains("in")) weightmap[e] = pR->getExitWeight("in"); else weightmap[e] = pIN->getWeight(); } } if( pOUT && !pOUT->isLocked ) { if( !pR->hasExitLock( DIR_OUT ) ) { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pR->getOut()], g ); if( exitWeights.contains("out")) weightmap[e] = pR->getExitWeight("out"); else weightmap[e] = pOUT->getWeight(); } } if( pR->getOtherMap().size() > 0 ) { QMapIterator<int, QString> it( pR->getOtherMap() ); while( it.hasNext() ) { it.next(); int _id = it.key(); QString _cmd = it.value(); if( _cmd.size()>0 ) _cmd.remove(0,1);//strip special exit lock information TRoom * pSpecial = mpRoomDB->getRoom( _id ); if( !pSpecial || pR->hasSpecialExitLock( _id, _cmd ) || pSpecial->isLocked) continue; else { // edgeCount++; edge_descriptor e; bool inserted; tie(e, inserted) = add_edge( roomIndex, roomidToIndex[pSpecial->getId()], g ); if( exitWeights.contains(_cmd)) { weightmap[e] = pR->getExitWeight(_cmd); } else { weightmap[e] = pSpecial->getWeight(); } } } } // if( roomExits == edgeCount ) locations.pop_back(); } mMapGraphNeedsUpdate = false; qDebug("TMap::initGraph(): nodes/room Counts: %i / %i edges: %i run time: %imSec.", locations.size(), roomCount, edgeCount, _time.elapsed()); }
friend bool operator == ( const wait_weight& lhs, const wait_weight& rhs ) { return tie( lhs.wait_sec, lhs.weight ) == tie( rhs.wait_sec, rhs.weight ); }
ossimRefPtr<ossimProjection> ossimFgdcXmlDoc::getGridCoordSysProjection() { static const char M[] = "ossimFgdcXmlDoc::getGridCoordSysProjection"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( m_projection.valid() == false ) { ossimString s; if ( getGridCoordinateSystem(s) ) { ossimString gridsysn = s.downcase(); if ( getHorizontalDatum(s) ) { ossimString horizdn = s.downcase(); const ossimDatum* datum = createOssimDatum(s); // throws exception if ( gridsysn == "universal transverse mercator" ) { // Get the zone: if ( getUtmZone(s) ) { ossim_int32 zone = s.toInt32(); //--- // Note: Contruct with an origin with our datum. // "proj->setDatum" does not change the origin's datum. // This ensures theossimEpsgProjectionDatabase::findProjectionCode // sets the psc code correctly down the line. //--- ossimRefPtr<ossimUtmProjection> utmProj = new ossimUtmProjection( *(datum->ellipsoid()), ossimGpt(0.0,0.0,0.0,datum) ); utmProj->setDatum(datum); utmProj->setZone(zone); // Hemisphere( North false easting = 0.0, South = 10000000): bool tmpResult = getUtmFalseNorthing(s); if ( tmpResult && ( s != "0.0" ) ) { utmProj->setHemisphere('S'); } else { utmProj->setHemisphere('N'); } utmProj->setPcsCode(0); ossim_float64 xRes = 0.0; ossim_float64 yRes = 0.0; if (getXRes(xRes) && getYRes(yRes)) { ossimDrect rect; getBoundingBox(rect); ossimDpt gsd(std::fabs(xRes), std::fabs(yRes)); ossimUnitType unitType = getUnitType(); if (m_boundInDegree) { ossimGpt tieg(rect.ul().lat, rect.ul().lon); utmProj->setUlTiePoints(tieg); } else { ossimDpt tie(rect.ul().x, rect.ul().y); if ( unitType == OSSIM_US_SURVEY_FEET) { tie = tie * US_METERS_PER_FT; } else if ( unitType == OSSIM_FEET ) { tie = tie * MTRS_PER_FT; } utmProj->setUlTiePoints(tie); } if ( unitType == OSSIM_US_SURVEY_FEET) { gsd = gsd * US_METERS_PER_FT; } else if ( unitType == OSSIM_FEET ) { gsd = gsd * MTRS_PER_FT; } utmProj->setMetersPerPixel(gsd); } m_projection = utmProj.get(); // Capture projection. } else { std::string errMsg = M; errMsg += " ERROR: Could not determine utm zone!"; throw ossimException(errMsg); } } } } } if ( traceDebug() ) { if ( m_projection.valid() ) { m_projection->print(ossimNotify(ossimNotifyLevel_DEBUG)); } ossimNotify(ossimNotifyLevel_DEBUG) << M << " exiting...\n"; } return m_projection; }
friend bool operator != ( const authority& lhs, const authority& rhs ) { return tie( lhs.threshold, lhs.keys, lhs.accounts, lhs.waits ) != tie( rhs.threshold, rhs.keys, rhs.accounts, rhs.waits ); }
void Gaussian::fixIntensity() { std::string formula = std::to_string(intensity() / sqrt(2.0 * M_PI)) + "/Sigma"; tie("Height", formula, true); }
void write_graphviz_subgraph (std::ostream& out, const subgraph<Graph_>& g, RandomAccessIterator vertex_marker, RandomAccessIterator edge_marker) { typedef subgraph<Graph_> Graph; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::directed_category cat_type; typedef graphviz_io_traits<cat_type> Traits; typedef typename graph_property<Graph, graph_name_t>::type NameType; const NameType& g_name = get_property(g, graph_name); if ( g.is_root() ) out << Traits::name() ; else out << "subgraph"; out << " " << g_name << " {" << std::endl; typename Graph::const_children_iterator i_child, j_child; //print graph/node/edge attributes #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename graph_property<Graph, graph_graph_attribute_t>::type GAttrMap; typedef typename graph_property<Graph, graph_vertex_attribute_t>::type NAttrMap; typedef typename graph_property<Graph, graph_edge_attribute_t>::type EAttrMap; GAttrMap gam = get_property(g, graph_graph_attribute); NAttrMap nam = get_property(g, graph_vertex_attribute); EAttrMap eam = get_property(g, graph_edge_attribute); graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap> writer(gam, nam, eam); writer(out); #else make_graph_attributes_writer(g)(out); #endif //print subgraph for ( tie(i_child,j_child) = g.children(); i_child != j_child; ++i_child ) write_graphviz_subgraph(out, *i_child, vertex_marker, edge_marker); // Print out vertices and edges not in the subgraphs. typename graph_traits<Graph>::vertex_iterator i, end; typename graph_traits<Graph>::edge_iterator ei, edge_end; typename property_map<Graph, vertex_index_t>::const_type indexmap = get(vertex_index, g.root()); for(tie(i,end) = vertices(g); i != end; ++i) { Vertex v = g.local_to_global(*i); int pos = get(indexmap, v); if ( vertex_marker[pos] ) { vertex_marker[pos] = false; out << pos; #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename property_map<Graph, vertex_attribute_t>::const_type VertexAttributeMap; attributes_writer<VertexAttributeMap> vawriter(get(vertex_attribute, g.root())); vawriter(out, v); #else make_vertex_attributes_writer(g.root())(out, v); #endif out << ";" << std::endl; } } for (tie(ei, edge_end) = edges(g); ei != edge_end; ++ei) { Vertex u = g.local_to_global(source(*ei,g)), v = g.local_to_global(target(*ei, g)); int pos = get(get(edge_index, g.root()), g.local_to_global(*ei)); if ( edge_marker[pos] ) { edge_marker[pos] = false; out << get(indexmap, u) << " " << Traits::delimiter() << " " << get(indexmap, v); #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename property_map<Graph, edge_attribute_t>::const_type EdgeAttributeMap; attributes_writer<EdgeAttributeMap> eawriter(get(edge_attribute, g)); eawriter(out, *ei); #else make_edge_attributes_writer(g)(out, *ei); //print edge properties #endif out << ";" << std::endl; } } out << "}" << std::endl; }