Пример #1
0
int GraphUtil::BFSTree(Graph& g, int v, ReducedGraph& tree) {
	int u;
	EdgeList el;
	EdgeList::iterator eit;
	int gsize = g.num_vertices();
	vector<bool> visit = vector<bool>(gsize,false);
	vector<bool> in = vector<bool>(gsize,false);
	deque<int> que;
	que.push_back(v);
	in[v] = true;
	tree.insert(make_pair(v,vector<int>()));
	while (!que.empty()) {
		u = que.front();
		que.pop_front();
		if (!visit[u]) {
			visit[u] = true;
			el = g.out_edges(u);
			for (eit = el.begin(); eit != el.end(); eit++) {
				if (!visit[*eit] && !in[*eit]) {
					que.push_back(*eit);
					in[*eit] = true;
					tree[u].push_back(*eit);
				}
			}
		}
	}
	
	int tcsize = 0;
	ReducedGraph::const_iterator rit;
	for (rit = tree.begin(); rit != tree.end(); rit++)
		tcsize += rit->second.size();
		
	return tcsize;
}
Пример #2
0
int GraphUtil::BFSDist(Graph& g, int sid, int tid) {
	if (sid == tid) return 0;
	
	int u;
	EdgeList el;
	EdgeList::iterator eit;
	int gsize = g.num_vertices();
	vector<bool> visit = vector<bool>(gsize,false);
	vector<bool> in = vector<bool>(gsize,false);
	vector<int> sdist = vector<int>(gsize,0);
	deque<int> que;
	que.push_back(sid);
	in[sid] = true;
	sdist[sid] = 0;
	while (!que.empty()) {
		u = que.front();
		que.pop_front();
		if (!visit[u]) {
			visit[u] = true;
			el = g.out_edges(u);
			for (eit = el.begin(); eit != el.end(); eit++) {
				if (!visit[*eit] && !in[*eit]) {
					sdist[*eit] = sdist[u]+1;
					if (*eit == tid) return sdist[*eit];	
					que.push_back(*eit);
					in[*eit] = true;
				}
			}
		}
	}
	return -1; //unreachable
}
Пример #3
0
bool contains(EdgeList& backedges, const BasicBlock* src, const BasicBlock* tgt) {
  for (EdgeList::iterator E = backedges.begin(), End = backedges.end(); E != End; ++E) {
    if (E->first == src && E->second == tgt)
      return true;
  }
  return false;
}
Пример #4
0
void DrawEdgeList(const EdgeList& e, const Graph& g)
{
  for (EdgeList::const_iterator it = e.begin(); it != e.end(); it++)
  {
    const GraphEdge& edge = *it;
    DrawEdge(edge, g);
  }
}
void DFSCode::fromGraph(Graph& g) {
    clear();
    EdgeList edges;
    for(UINT from=0; from<g.size(); ++from)
    {
        if(!get_forward_root(g,g[from],edges))
            continue;
        for(EdgeList::iterator it = edges.begin(); it!=edges.end(); ++it)
            push(from,(*it)->to,g[(*it)->from].label,(*it)->elabel,g[(*it)->to].label);
    }
}
Пример #6
0
void GraphUtil::computePartialSD(Graph& g, vector<int>& rank, int start_ind, 
				int& end_ind, SparseVec& pdist, long tc_limit) {
	int u;
	deque<int> que;
	EdgeList el;
	EdgeList::iterator eit;
	map<int,int>::iterator mit;

	pdist.clear();
	int gsize = g.num_vertices();
	vector<bool> in = vector<bool>(gsize,false);
	vector<bool> visit = vector<bool>(gsize,false);
	int inc_count = 0;
	int sid = start_ind;
	int i = 0, j = rank[sid];
	while (true) {
		pdist.push_back(map<int,int>());
		pdist[i][j] = 0;
		que.clear();
		que.push_back(j);
		in[j] = true;
		while (!que.empty()) {
			u = que.front();
			que.pop_front();
			if (!visit[u]) {
				visit[u] = true;
				el = g.out_edges(u);
				for (eit = el.begin(); eit != el.end(); eit++) {
					if (!visit[*eit] && !in[*eit]) {
						que.push_back(*eit);
						in[*eit] = true;
						pdist[i][*eit] = pdist[i][u]+1;	
					}
				}
			}
		}
		for (mit = pdist[i].begin(); mit != pdist[i].end(); mit++) {
			in[mit->first] = false;
			visit[mit->first] = false;
		}
		i++;
		sid++;
		if (sid < rank.size()) 
			j = rank[sid];
		inc_count += pdist[i].size();
		
		if (inc_count >= tc_limit)
			break;
	}
	end_ind = sid;
}
void AspEventHandler::dfs(DFSStackElement start_elt) {
	DFSStack stack;
	push(stack, start_elt);
	while(stack.size() > 0) {
		DFSStackElement current_elt = peek(stack);
		Transaction* current_tx = current_elt.tx_;
		if(current_elt.begin_ == current_elt.end_) {
			// no out-going edges; done with current transaction; pop it
			current_tx->set_dfs_state(BLACK);
			pop(stack);

			// add tx to the topologically sorted txlist
			txlist_sorted_.push_front(current_tx);

			if(stack.size() > 0) {
				// iterate the new top to next edge
				current_elt = peek(stack);
				current_elt.begin_++;
				pop_push(stack, current_elt);
			}
			continue;
		}

		Edge e = *(current_elt.begin_);
		assert(current_tx == e.first->tx());
		Transaction* next_tx = e.second->tx();
		assert(current_tx != next_tx);

		dfs_state_t next_state = next_tx->dfs_state();
		if(next_state == WHITE) {
			next_tx->set_dfs_state(GRAY);

			EdgeList* edges = next_tx->conflict_edges();
			push(stack, DFSStackElement(next_tx, edges->begin(), edges->end()));
		} else {
			assert(next_state == BLACK || next_state == GRAY);
			// check cycle
			if(next_state == GRAY) {
				// Cycle; extract it from the current dfs stack and save it
				Cycle* cycle = extract_cycle(stack, next_tx);
				// extract_cycle may skip reporting a cycle, so check if cycle is non-null
				if(cycle != NULL) {
					cycles_.push_back(cycle);
				}
			}
			// iterate top to next edge
			current_elt.begin_++;
			pop_push(stack, current_elt);
		}
	}
}
void AspEventHandler::check_serializability() {
	assert(cycles_.empty());
	assert(txlist_sorted_.empty());

	txset_in_cycle.clear();

	for(TransactionPtrList::iterator itr = txlist_.begin(); itr != txlist_.end(); ++itr) {
		Transaction* tx = (*itr);
		if(tx->dfs_state() == WHITE) {
			EdgeList* edges = tx->conflict_edges();
			dfs(DFSStackElement(tx, edges->begin(), edges->end()));
		}
	}
}
Пример #9
0
// depth first search given a start node
void GraphUtil::dfs(Graph& g, int vid, vector<int>& preorder, vector<int>& postorder, vector<bool>& visited) {
	visited[vid] = true;
	preorder.push_back(vid);
	EdgeList el = g.out_edges(vid);
	EdgeList::iterator eit;
	int nextid = -1;
	// check whether all child nodes are visited
	for (eit = el.begin(); eit != el.end(); eit++) {
		if (!visited[*eit]) {
			nextid = *eit;
			dfs(g, nextid, preorder, postorder, visited);
		}
	}
	postorder.push_back(vid);
}
Пример #10
0
// traverse tree to label node with pre and post order by giving a start node
// using GRIPP's labeling method
void GraphUtil::traverse(Graph& tree, int vid, int& pre_post, vector<bool>& visited) {
	visited[vid] = true;
	EdgeList el = tree.out_edges(vid);
	EdgeList::iterator eit;
	int pre_order;
	for (eit = el.begin(); eit != el.end(); eit++) {
		pre_order = pre_post;
		pre_post++;
		if (!visited[*eit])
			traverse(tree, *eit, pre_post, visited);
		tree[*eit].pre_order = pre_order;
		tree[*eit].post_order = pre_post;
		pre_post++;
	}
}
Пример #11
0
bool EdgeCollector::extractBoundaryEdgeloop(EdgeList & el, Edgeloop & edgeloop)
{
    if (el.empty()) return false;


    osg::ref_ptr<Edge> current = el.back();
    el.pop_back();

    // ** init the Edgeloop
    edgeloop._edgeList.push_back(current.get());



    bool done = false;
    while (!done)
    {
        bool found = false;
        EdgeList::iterator it = el.begin(), end = el.end();
        while (it != end && !found)
        {
            if (current->endConnected(*(it->get())))
            {
                found = true;
            }
            else
            {
                ++it;
            }
        }

        if (!found)
        {
            OSG_WARN << "extractBoundaryEdgeloop : unable to close edge loop" << std::endl;
            return false;
        }
        else
        {
            edgeloop._edgeList.push_back(it->get());
            current = it->get();
            el.erase(it);

            if (edgeloop.isClosed()) done = true;
        }
    }
    return true;
}
Пример #12
0
int GraphUtil::topo_level(Graph& g, int vid){
	if(g[vid].top_level != -1){
		return g[vid].top_level;
	}
	int min = g.num_vertices();	
	int max = -1;
	g[vid].top_level = 0;
	EdgeList el = g.in_edges(vid);
	EdgeList::iterator eit;
	for(eit = el.begin(); eit != el.end(); eit++){
		max = max > topo_level(g,*eit) ? max : g[*eit].top_level;
		min = min < g[*eit].top_level ? min : g[*eit].top_level;
	}
	g[vid].top_level = max + 1;
	g[vid].min_parent_level = (min == g.num_vertices() ? -1 : min );
	return g[vid].top_level;
}
Пример #13
0
// implement tarjan's algorithm to find Strongly Connected Component from a given start node
void GraphUtil::tarjan(Graph& g, int vid, int& index, hash_map< int, pair<int,int> >& order, 
	vector<int>& sn, multimap<int,int>& sccmap, int& scc) {
//	cout << " inside tarjan " << endl;	
	order[vid].first = index;
	order[vid].second = index;
	index++;
//	cout << " before pushing vid = " << vid << endl;
	sn.push_back(vid);
//	cout << " after pushing vid = " << vid << endl;
	g[vid].visited = true;
	EdgeList el = g.out_edges(vid);
	EdgeList::iterator eit;
	for (eit = el.begin(); eit != el.end(); eit++) {
		if (!g[*eit].visited) {
			tarjan(g, *eit, index, order, sn, sccmap, scc);
			order[vid].second = min(order[*eit].second, order[vid].second);
		}
		else if (find(sn.begin(), sn.end(), (*eit)) != sn.end()) {
			order[vid].second = min(order[*eit].first, order[vid].second);
		}
	}

//	cout << " in the middle of tarjan "<< endl;	
	if (order[vid].first == order[vid].second) {
		vector<int>::reverse_iterator rit;
		for (rit = sn.rbegin(); rit != sn.rend(); rit++) {
			if ((*rit) != vid) {
				sccmap.insert(make_pair(scc, *rit));
			//	sccmap[*rit] = scc;
				sn.pop_back();
			}
			else {
				sccmap.insert(make_pair(scc, *rit));
			//	sccmap[*rit] = scc;
				sn.pop_back();
				break;
			}
		}
		scc++;
	}

//	cout << " outside tarjan "<< endl;	
}
LLDependenciesBase::VertexList LLDependenciesBase::topo_sort(int vertices, const EdgeList& edges) const
{
    // Construct a Boost Graph Library graph according to the constraints
    // we've collected. It seems as though we ought to be able to capture
    // the uniqueness of vertex keys using a setS of vertices with a
    // string property -- but I don't yet understand adjacency_list well
    // enough to get there. All the examples I've seen so far use integers
    // for vertices.
    // Define the Graph type. Use a vector for vertices so we can use the
    // default topological_sort vertex lookup by int index. Use a set for
    // edges because the same dependency may be stated twice: Node "a" may
    // specify that it must precede "b", while "b" may also state that it
    // must follow "a".
    typedef boost::adjacency_list<boost::setS, boost::vecS, boost::directedS,
                                  boost::no_property> Graph;
    // Instantiate the graph. Without vertex properties, we need say no
    // more about vertices than the total number.
    Graph g(edges.begin(), edges.end(), vertices);
    // topo sort
    typedef boost::graph_traits<Graph>::vertex_descriptor VertexDesc;
    typedef std::vector<VertexDesc> SortedList;
    SortedList sorted;
    // note that it throws not_a_dag if it finds a cycle
    try
    {
        boost::topological_sort(g, std::back_inserter(sorted));
    }
    catch (const boost::not_a_dag& e)
    {
        // translate to the exception we define
        std::ostringstream out;
        out << "LLDependencies cycle: " << e.what() << '\n';
        // Omit independent nodes: display only those that might contribute to
        // the cycle.
        describe(out, false);
        throw Cycle(out.str());
    }
    // A peculiarity of boost::topological_sort() is that it emits results in
    // REVERSE topological order: to get the result you want, you must
    // traverse the SortedList using reverse iterators.
    return VertexList(sorted.rbegin(), sorted.rend());
}
Пример #15
0
void GraphUtil::computeShortestDistance(Graph& g, SparseVec& dist) {
	int u;
	deque<int> que;
	EdgeList el;
	EdgeList::iterator eit;
	map<int,int>::iterator mit;

	int gsize = g.num_vertices();
	dist = SparseVec(gsize,map<int,int>());
	vector<bool> in = vector<bool>(gsize,false);
	vector<bool> visit = vector<bool>(gsize,false);
	for (int i = 0; i < gsize; i++) {
		dist[i][i] = 0;
		que.clear();
		que.push_back(i);
		in[i] = true;
		while (!que.empty()) {
			u = que.front();
			que.pop_front();
			if (!visit[u]) {
				visit[u] = true;
				el = g.out_edges(u);
				for (eit = el.begin(); eit != el.end(); eit++) {
					if (!visit[*eit] && !in[*eit]) {
						que.push_back(*eit);
						in[*eit] = true;
						dist[i][*eit] = dist[i][u]+1;	
					}
				}
			}
		}
		for (mit = dist[i].begin(); mit != dist[i].end(); mit++) {
			in[mit->first] = false;
			visit[mit->first] = false;
		}
	}
}
Пример #16
0
int GraphUtil::genCandLabels(Graph& g, int vid, ReducedGraph& sptree, 
		map<int,set<int> >& tpairs, vector<int>& left, map<int,set<int> >& right) {
	int u;
	deque<int> que;
	vector<int>::const_iterator sit;
	EdgeList el;
	EdgeList::iterator eit;
	ReducedGraph temp_right;
	ReducedGraph treeedges;
	int gsize = g.num_vertices();
	vector<bool> in = vector<bool>(gsize,false);
	vector<bool> visit = vector<bool>(gsize,false);

//	left.clear();
	vector<int>().swap(left);
	left.push_back(vid);
	que.push_back(vid);
	in[vid] = true;
	while (!que.empty()) {
		u = que.front();
		que.pop_front();
		if (!visit[u]) {
			visit[u] = true;
			// visit tree edges firstly
			if (sptree.find(u) != sptree.end()) {
				for (sit = sptree[u].begin(); sit != sptree[u].end(); sit++) {
					if (!visit[*sit] && !in[*sit]) {
						que.push_back(*sit);
						in[*sit] = true;
						treeedges[u].push_back(*sit);
						temp_right[*sit] = temp_right[u];
					}
				}
			}
			// visit regular edges in original graph
			el = g.out_edges(u);
			for (eit = el.begin(); eit != el.end(); eit++) {
				if (!visit[*eit] && !in[*eit]) {
					que.push_back(*eit);
					in[*eit] = true;
					left.push_back(*eit);
					temp_right[*eit] = temp_right[u];
					temp_right[*eit].push_back(u);
				}
			}
		}
	}	
	
	// for test
/* 	
	cout << "--------------------tree edges --------------------" << endl;
	Util::printReducedGraph(treeedges); */
	
	// compute tree TC
//	tpairs.clear();
	map<int,set<int> >().swap(tpairs);
	treetc(treeedges, tpairs);
//	treeedges.clear();
	ReducedGraph().swap(treeedges);

	// include themselves
	ReducedGraph::iterator rit;
	vector<int>::iterator vit;
	for (rit = temp_right.begin(); rit != temp_right.end(); rit++) {
		for (vit = rit->second.begin(); vit != rit->second.end(); vit++)
			right[*vit].insert(rit->first);
		right[rit->first].insert(rit->first);
	}
	
	// stat size
	int size = 0;
	map<int,set<int> >::const_iterator msit;
	for (msit = right.begin(); msit != right.end(); msit++)
		size += msit->second.size();
	size += left.size();
	
	return size;
}
void gSpan::run_intern()
{
    if(maxpat_min <= 1) {
//        std::cout << "TRANS.size() = " << TRANS.size() << std::endl;


        //Counting the frequency of all single vertex labels
        for(UINT id = 0; id<TRANS.size(); ++id)
        {

            for(UINT nid = 0; nid<TRANS[id].size(); ++nid)
            {

                if(singleVertex[id][TRANS[id][nid].label]==0)
                    singleVertexLabel[TRANS[id][nid].label] += 1;
                singleVertex[id][TRANS[id][nid].label] += 1;
            }

        }

        for(std::map<UINT,UINT>::iterator it = singleVertexLabel.begin(); it!=singleVertexLabel.end(); ++it)
        {
            if((*it).second < minsup)               //checking frequency of vertices with minimum support.
                continue;                           // Ignoring the infrequent vertices
            UINT frequent_label = (*it).first;
            //std::cout << "Frequent Label: " << frequent_label << std::endl;
            Graph g(directed);
            g.resize(1);
            g[0].label = frequent_label;


            // Didn't understand the purpose of this part
            std::vector<UINT> counts(TRANS.size());
            for(std::map<UINT, std::map<UINT, UINT> >::iterator it2 = singleVertex.begin(); it2 != singleVertex.end(); ++it2) {
                // std::cout << "(*it2).first = " << (*it2).first << "(*it2).second[frequent_label] = " << (*it2).second[frequent_label] << std::endl;
                counts[(*it2).first] = (*it2).second[frequent_label];
            }
        }
    }

    EdgeList edges;
    Projected_map3 root;

    for(UINT id=0; id< TRANS.size(); ++id)
    {
        Graph& g = TRANS[id];

        for(UINT from = 0; from < g.size(); ++from)
        {
            if(get_forward_root(g,g[from],edges))
            {
                for(EdgeList::iterator it = edges.begin(); it!= edges.end(); ++it)
                    root[g[from].label][(*it)->elabel][g[(*it)->to].label].push(id,*it,0);
            }
        }
    }

    std::vector<Graph>	List;
    std::vector<Projected> proj_vec;
    std::vector<string> FwEdge;
    char ch[1000];

    for(Projected_iterator3 fromlabel = root.begin(); fromlabel != root.end(); ++fromlabel)
    {
        for(Projected_iterator2 elabel = fromlabel ->second.begin(); elabel != fromlabel -> second.end(); ++elabel)
            for(Projected_iterator1 tolabel = elabel->second.begin(); tolabel != elabel -> second.end(); ++tolabel)
            {
                std::cout << "0,1," << fromlabel->first << "," << elabel->first << "," << tolabel->first << std::endl;
                sprintf(ch,"%d %d %d %d %d",0,1,fromlabel->first,elabel->first,tolabel->first);
                FwEdge.push_back(ch);
                Projected proj = tolabel->second;
                proj_vec.push_back(proj);
            }
    }

    vector<Graph> sorted;
    int x[5];
//    //Initial 1-edge graph to start
    for(UINT i= 0; i< (int)FwEdge.size(); i++)
    {
        std::cout << FwEdge[i] << std::endl;
        sscanf(FwEdge[i].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        //std::cout << FwEdge[i] << std::endl;
        DFS_CODE.push(x[0],x[1],x[2],x[3],x[4]);
        Graph g;
        DFS_CODE.toGraph(g);
//        Calculate_MDL(g,(UINT)NumOfLabels);
//        std::set<int> occurrence = total_occurance(proj_vec[i]);
//
//        g.MDL = EvaluateGraph(TRANS,g,occurrence);
        //g.occurrence = support_counts(proj_vec[i]);
        g.Frequency = support(proj_vec[i]);
        g.SET_COVER = (double)g.Frequency / (double) TRANS.size();
        sorted.push_back(g);
        //ListInsert(BestList,g,5);
//        std::cout << "MDL = "<< g.MDL << "vertex size = " << g.size() << "Support Count = " << support_counts(proj_vec[i])[0] << std::endl;
        project(proj_vec[i]);
        DFS_CODE.pop();
    }


    BestList.insert(BestList.end(),sorted.begin(),sorted.end());
//    for(UINT i=0;i<sorted.size();i++)
//    {
//        ListInsert(BestList,sorted[i],maxBest);
//    }
//

//    Graph g(directed);
//
//    g.resize(2);
//    g[0].label = 2;
//    g[0].used = false;
//    g[1].label = 3;
//    g[1].used = false;
//
//    g[0].push(0,1,1);
//    g[1].push(1,0,1);
//    g.buildEdge();
//    g.write();
//    Calculate_MDL(g,3);
//    std::set<int> ss;
//    ss.insert(0);
//    EvaluateGraph(TRANS,g,ss);
//
//    //std::cout <<"Testing G = " << g.MDL << std::endl;
//    exit(1);
    sorted.clear();
    List.clear();
    FwEdge.clear();
    proj_vec.clear();
}
void gSpan::project(Projected& projected)
{

    UINT sup = support(projected);
    std::cout << "Support: " << sup << std::endl;
    if(sup<minsup)
        return;

    if(!is_min()) {
        //*os << "NOT MIN [";
        //DFS_CODE.write (*os);
        //*os << "]" << std::endl;
        return;
    }

    Graph g(false);
    DFS_CODE.toGraph(g);
    if(g.size() > maxVertices || g.edge_size()> maxEdges)
        return;

    //report(projected,sup);
    ID++;

    //std::cout <<"x = "<< x << std::endl;
    if(maxpat_max>maxpat_min && DFS_CODE.nodeCount() > maxpat_max)
        return;

    const RMPath& rmpath = DFS_CODE.buildRMPath();
    int minlabel = DFS_CODE[0].fromlabel;
    int maxtoc = DFS_CODE[rmpath[0]].to;

    Projected_map3 new_fwd_root;
    Projected_map2 new_bck_root;
    EdgeList edges;

    for(UINT n = 0; n < projected.size(); ++n)
    {
        UINT id = projected[n].id;
        PDFS* cur = & projected[n];
        History history(TRANS[id],cur);

        for(int i = (int) rmpath.size()-1; i>=1 ; --i) {
            Edge* e = get_backward(TRANS[id], history[rmpath[i]],history[rmpath[0]],history);

            if(e)
                new_bck_root[DFS_CODE[rmpath[i]].from][e->elabel].push(id,e,cur);   //inserting the backward edge in DFS COde
        }

        if(get_forward_pure(TRANS[id], history[rmpath[0]], minlabel, history, edges))
            for(EdgeList::iterator it = edges.begin(); it != edges.end(); ++it)
                new_fwd_root[maxtoc][(*it)->elabel][TRANS[id][(*it)->to].label].push(id,*it,cur);

        for(int i=0; i<(int)rmpath.size(); ++i)
            if(get_forward_rmpath(TRANS[id],history[rmpath[i]],minlabel,history,edges))
                for(EdgeList::iterator it = edges.begin(); it!=edges.end(); ++it)
                    new_fwd_root[DFS_CODE[rmpath[i]].from][(*it)->elabel][TRANS[id][(*it)->to].label].push(id,*it,cur);

    }

    std::vector<Graph>	List;
    std::vector<Projected> proj_vec;
    vector<pair<Graph,int> > sorted;
    std::vector<string> FwEdge;
    char ch[1000];
    int index=0;

    // Adding backward edge to subgraph
    for(Projected_iterator2 to = new_bck_root.begin(); to!=new_bck_root.end(); ++to) {
        for(Projected_iterator1 elabel= to->second.begin(); elabel!=to->second.end(); ++elabel) {
            sprintf(ch,"%d %d %d %d %d",maxtoc, to->first,-1,elabel->first,-1);
            FwEdge.push_back(ch);
            Projected proj = elabel->second;
            proj_vec.push_back(proj);
        }
    }

    int x[5];
    sorted.clear();
    for(UINT i=0; i< (int)FwEdge.size(); i++)
    {
        sscanf(FwEdge[i].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        DFS_CODE.push(x[0],x[1],x[2],x[3],x[4]);
        Graph g(directed);
        DFS_CODE.toGraph(g);

        /*Calculate_MDL(g,(UINT)NumOfLabels);
        std::set<int> Gindex = total_occurance(proj_vec[i]);


        g.MDL = EvaluateGraph(TRANS,g,Gindex);
         */
        //g.occurrence = support_counts(proj_vec[i]);
        g.Frequency = support(proj_vec[i]);
        g.SET_COVER = (double)g.Frequency / (double) TRANS.size();
        sorted.push_back(make_pair(g,index++));
        //ListPairInsert(sorted,std::make_pair(g,index++),BeamWidth);
        DFS_CODE.pop();
    }

    sort(sorted.begin(),sorted.end(),SetPairComp);


    for(UINT i= 0; i< std::min((int)FwEdge.size(),BeamWidth); i++) {
        sscanf(FwEdge[sorted[i].second].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        DFS_CODE.push(x[0],x[1],x[2],x[3],x[4]);
        BestList.push_back(sorted[i].first);
//        ListInsert(BestList,sorted[i].first,maxBest);
        //ListInsert(BestList,sorted[i].first,5);
        project(proj_vec[sorted[i].second]);
        DFS_CODE.pop();
    }

    sorted.clear();
    FwEdge.clear();
    List.clear();
    proj_vec.clear();

    index=0;
    //Adding forward Edge

    for(Projected_riterator3 from = new_fwd_root.rbegin(); from!=new_fwd_root.rend(); ++from)
    {
        for(Projected_iterator2 elabel = from->second.begin(); elabel != from->second.end(); ++elabel)
        {
            for(Projected_iterator1 tolabel = elabel->second.begin(); tolabel!=elabel->second.end(); ++tolabel)
            {
                //DFS_CODE.push(from->first,maxtoc+1, -1, elabel->first, tolabel->first);
                Projected proj = tolabel->second;
                proj_vec.push_back(proj);
//                Graph g(directed);
//                DFS_CODE.toGraph(g);
//                Calculate_MDL(g,NumOfLabels);
//                std::set<int> occurrence = total_occurance(proj);
//                g.MDL = EvaluateGraph(TRANS,g,occurrence);
//                sorted.push_back(make_pair(g,index));
//                DFS_CODE.pop();

                sprintf(ch,"%d %d %d %d %d",from->first,maxtoc+1, -1, elabel->first, tolabel->first);
                FwEdge.push_back(ch);

            }
        }
    }

    for(UINT i=0; i< (int)FwEdge.size(); i++)
    {
        sscanf(FwEdge[i].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        DFS_CODE.push(x[0],x[1],x[2],x[3],x[4]);
        Graph g(directed);
        DFS_CODE.toGraph(g);

//        Calculate_MDL(g,NumOfLabels);
//        std::set<int> Gindex = total_occurance(proj_vec[i]);
//
//
//        g.MDL = EvaluateGraph(TRANS,g,Gindex);
        //g.occurrence = support_counts(proj_vec[i]);
        g.Frequency = support(proj_vec[i]);
        g.SET_COVER = (double)g.Frequency / (double) TRANS.size();
        sorted.push_back(make_pair(g,index++));
        //ListPairInsert(sorted,std::make_pair(g,index++),BeamWidth);
        //ListPairInsert(sorted,PGI(g,index++),BeamWidth);
        DFS_CODE.pop();
    }
    sort(sorted.begin(),sorted.end(),SetPairComp);
    //reverse(sorted.begin(),sorted.end());
    //int N = sorted.size();

    //vector<Graph> sorted;

    for(UINT i= 0; i< std::min((int)sorted.size(),BeamWidth); i++) {
        sscanf(FwEdge[sorted[i].second].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        //sscanf(FwEdge[i].c_str(),"%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]);
        DFS_CODE.push(x[0],x[1],x[2],x[3],x[4]);
        //ListInsert(BestList,sorted[i].first,maxBest);
        //ListInsert(BestList,sorted[i].first,5);
        BestList.push_back(sorted[i].first);
        project(proj_vec[sorted[i].second]);
        DFS_CODE.pop();
    }
//
//    for(UINT i= 0; i< std::min(N,BeamWidth);i++) {
//        BestList.push_back(sorted[i].first);
//    }
    //sorted.clear();
//    for(UINT i= 0; i< (int)List.size();i++){
//        DFS_CODE.push(FwEdge[i].from_id,FwEdge[i].to_id,FwEdge[i].from,FwEdge[i].elabel,FwEdge[i].to);
//        project(proj_vec[i]);
//        DFS_CODE.pop();
//    }
//
    sorted.clear();
    FwEdge.clear();
    List.clear();
    proj_vec.clear();
//
    return;
}
Пример #19
0
inline
Polyhedron<ScalarParam>*
Polyhedron<ScalarParam>::clip(
	const typename Polyhedron<ScalarParam>::Plane& plane) const
	{
	typedef Misc::HashTable<Card,void> IndexSet;
	typedef Misc::HashTable<Card,Card> IndexMapper;
	
	/* Find the indices of all half edges that intersect the plane: */
	IndexMapper indexMapper(101);
	Card nextIndex=0;
	Card numIntersectedEdges=0;
	Card intersectedEdgeIndex=0;
	IndexSet ioEdges(17);
	Card numEdges=edges.size();
	for(Card i=0;i<numEdges;++i)
		{
		/* Get the plane distance of start and end points of edge i: */
		Scalar d0=plane.calcDistance(edges[i].start);
		Scalar d1=plane.calcDistance(edges[edges[i].next].start);
		
		/* Classify the edge: */
		if(d0<Scalar(0)&&d1<Scalar(0))
			{
			/* Keep the edge: */
			indexMapper.setEntry(typename IndexMapper::Entry(i,nextIndex));
			++nextIndex;
			}
		else if(d0<Scalar(0)||d1<Scalar(0))
			{
			/* Keep the edge: */
			indexMapper.setEntry(typename IndexMapper::Entry(i,nextIndex));
			++nextIndex;
			
			if(d0<Scalar(0))
				{
				/* Mark the edge as intersected: */
				++numIntersectedEdges;
				intersectedEdgeIndex=i;
				}
			else
				{
				/* Mark the edge as the opposite of an intersected edge: */
				ioEdges.setEntry(typename IndexSet::Entry(i));
				}
			}
		}
	
	/* Remember the number of retained edges: */
	Card newNumEdges=nextIndex;
	
	/* Check for trivial cases: */
	if(newNumEdges==0)
		return new Polyhedron; // Return an empty polyhedron
	else if(numIntersectedEdges==0)
		return new Polyhedron(*this); // Return an identical copy of the polyhedron
	
	/* Sort the list of intersected edges to form a loop: */
	IndexMapper newFaceEdges(17);
	EdgeList newFace;
	while(newFace.size()<numIntersectedEdges)
		{
		Edge newEdge;
		
		/* Calculate the new edge's starting point: */
		const Point& p0=edges[intersectedEdgeIndex].start;
		Scalar d0=plane.calcDistance(p0);
		const Point& p1=edges[edges[intersectedEdgeIndex].next].start;
		Scalar d1=plane.calcDistance(p1);
		newEdge.start=Geometry::affineCombination(p0,p1,(Scalar(0)-d0)/(d1-d0));
		
		/* Find the next intersected edge around the same face as the current last edge: */
		Card edgeIndex;
		for(edgeIndex=edges[intersectedEdgeIndex].next;!ioEdges.isEntry(edgeIndex);edgeIndex=edges[edgeIndex].next)
			;
		newEdge.next=indexMapper.getEntry(edgeIndex).getDest();
		newEdge.opposite=newNumEdges+numIntersectedEdges+newFace.size();
		
		/* Store the index of the new face edge: */
		newFaceEdges.setEntry(IndexMapper::Entry(intersectedEdgeIndex,newFace.size()));
		
		/* Store the new face edge: */
		newFace.push_back(newEdge);
		
		/* Go to the next intersected face: */
		intersectedEdgeIndex=edges[edgeIndex].opposite;
		}
	
	/* Create the result polyhedron: */
	Polyhedron* result=new Polyhedron;
	
	/* Create the edges of the result polyhedron: */
	for(Card i=0;i<numEdges;++i)
		{
		/* Get the plane distance of start and end points of edge i: */
		Scalar d0=plane.calcDistance(edges[i].start);
		Scalar d1=plane.calcDistance(edges[edges[i].next].start);
		
		/* Classify the edge: */
		if(d0<Scalar(0)&&d1<Scalar(0))
			{
			/*****************************************************************
			If an edge is completely inside, its opposite edge must be as
			well, and its next edge must at least be partially inside.
			Therefore, indexMapper will contain the new indices for both
			edges.
			*****************************************************************/
			
			/* Keep the edge: */
			result->edges.push_back(Edge(edges[i].start,indexMapper.getEntry(edges[i].next).getDest(),indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		else if(d0<Scalar(0))
			{
			/*****************************************************************
			If an edge's start point is inside, its opposite edge's index will
			be contained in indexMapper, and its next edge is a new face edge
			whose index can be calculated from newFaceEdges.
			*****************************************************************/
			
			/* Find the index of the next edge from the new face loop: */
			Card next=newNumEdges+newFaceEdges.getEntry(i).getDest();
			
			/* Retain the edge: */
			result->edges.push_back(Edge(edges[i].start,next,indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		else if(d1<Scalar(0))
			{
			/*****************************************************************
			If an edge's end point is inside, its start point must be
			calculated by clipping, and its next edge and opposite edge will
			both be contained in indexMapper.
			*****************************************************************/
			
			/* Calculate the new start point: */
			Point newStart=Geometry::affineCombination(edges[edges[i].next].start,edges[i].start,(Scalar(0)-d1)/(d0-d1));
			
			/* Retain the clipped edge: */
			result->edges.push_back(Edge(newStart,indexMapper.getEntry(edges[i].next).getDest(),indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		}
	
	/* Add the closing edges for all clipped faces to the polyhedron: */
	for(typename EdgeList::const_iterator nfIt=newFace.begin();nfIt!=newFace.end();++nfIt)
		result->edges.push_back(*nfIt);
	
	/* Add the edges of the closing face to the polyhedron: */
	for(Card i=0;i<newFace.size();++i)
		{
		Edge newEdge;
		newEdge.start=newFace[(i+1)%newFace.size()].start;
		newEdge.next=newNumEdges+numIntersectedEdges+(i+newFace.size()-1)%newFace.size();
		newEdge.opposite=newNumEdges+i;
		result->edges.push_back(newEdge);
		}
	
	// DEBUGGING
	// result->check();
	
	return result;
	}
Пример #20
0
std::pair< Point<float>, float > Stippler::calculateCellCentroid( Point<float> &inside, EdgeList &edgeList ) {
	using std::make_pair;
	using std::numeric_limits;
	using std::vector;
	using std::floor;
	using std::ceil;
	using std::abs;
	using std::sqrt;
	using std::pow;

	vector< Line<float> > clipLines;
	Extents<float> extent = getCellExtents(edgeList);

	unsigned int x, y;

	float xDiff = ( extent.maxX - extent.minX );
	float yDiff = ( extent.maxY - extent.minY );

	unsigned int tileWidth = (unsigned int)ceil(xDiff) * parameters.subpixels;
	unsigned int tileHeight = (unsigned int)ceil(yDiff) * parameters.subpixels;

	float xStep = xDiff / (float)tileWidth;
	float yStep = yDiff / (float)tileHeight;

	float spotDensity, areaDensity = 0.0f, maxAreaDensity = 0.0f;
	float xSum = 0.0f;
	float ySum = 0.0f;

	float xCurrent;
	float yCurrent;

	// compute the clip lines
	for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
		Line<float> l = createClipLine( inside.x, inside.y, 
			value_iter->begin.x, value_iter->begin.y,
			value_iter->end.x, value_iter->end.y );
	
		if (l.a < numeric_limits<float>::epsilon() && abs(l.b) < numeric_limits<float>::epsilon()) {
			continue;
		}

		clipLines.push_back(l);
	}

	for ( y = 0, yCurrent = extent.minY; y < tileHeight; ++y, yCurrent += yStep ) {
		for ( x = 0, xCurrent = extent.minX; x < tileWidth; ++x, xCurrent += xStep ) {
			// a point is outside of the polygon if it is outside of all clipping planes
			bool outside = false;
			for ( vector< Line<float> >::iterator iter = clipLines.begin(); iter != clipLines.end(); iter++ ) {
				if ( xCurrent * iter->a + yCurrent * iter->b + iter->c >= 0.0f ) {
					outside = true;
					break;
				}
			}

			if (!outside) {
				spotDensity = image.getIntensity(xCurrent, yCurrent);

				areaDensity += spotDensity;
				maxAreaDensity += 255.0f;
				xSum += spotDensity * xCurrent;
				ySum += spotDensity * yCurrent;
			}
		}
	}

	float area = areaDensity * xStep * yStep / 255.0f;
	float maxArea = maxAreaDensity * xStep * yStep / 255.0f;

	Point<float> pt;
	if (areaDensity > numeric_limits<float>::epsilon()) {
		pt.x = xSum / areaDensity;
		pt.y = ySum / areaDensity;
	} else {
		// if for some reason, the cell is completely white, then the centroid does not move
		pt.x = inside.x;
		pt.y = inside.y;
	}

	float closest = numeric_limits<float>::max(),
		  farthest = numeric_limits<float>::min(),
		  distance;
	float x0 = pt.x, y0 = pt.y,
	      x1, x2, y1, y2;

	for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
		x1 = value_iter->begin.x; x2 = value_iter->end.x;
		y1 = value_iter->begin.y; y2 = value_iter->end.y;

		distance = abs( ( x2 - x1 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y1 ) ) / sqrt( pow( x2 - x1, 2.0f ) + pow( y2 - y1, 2.0f ) );
		if ( closest > distance ) {
			closest = distance;
		}
		if ( farthest < distance ) {
			farthest = distance;
		}
	}

	float radius;
	if ( parameters.noOverlap ) {
		radius = closest;
	} else {
		radius = farthest;
	}
	radius *= area / maxArea;

	return make_pair( pt, radius );
}
Пример #21
0
// build maximal weighted spanning tree and rank the vertices based on tc size of their BFS tree
void GraphUtil::buildMaxWST(Graph& g, ReducedGraph& sptree, vector<int>& rank) {
	ReducedGraph::iterator rit;
	vector<int>::iterator vit;
	map<int,int>::iterator mit;
	SparseVec::iterator svit;
	int gsize = g.num_vertices();
	map<int,pair<int,int> > pred_succ;
	SparseVec weight = SparseVec(gsize,map<int,int>());
	multimap<int,int> mrank;
	int tree_tc = 0;

	for (int i = 0; i < gsize; i++) {
		if(i%100==0)
			printf("buildMaxWST %d\n",i);
		ReducedGraph tree;
		tree_tc = BFSTree(g, i, tree);
		#ifdef ALLPATHS
		treestat(tree, pred_succ, i, gsize);
		#endif
		for (rit = tree.begin(); rit != tree.end(); rit++) {
			for (vit = rit->second.begin(); vit != rit->second.end(); vit++)
				#ifdef ALLPATHS
				weight[rit->first][*vit] += pred_succ[rit->first].first*pred_succ[*vit].second;
				#else
				weight[rit->first][*vit] += 1;
				#endif
		}
		#ifdef ALLPATHS
		map<int,pair<int,int> >().swap(pred_succ);
		#endif
		ReducedGraph().swap(tree);
		mrank.insert(make_pair(tree_tc,i));
	}
	
	// set ranking results
//	rank.clear();
	vector<int>().swap(rank);
	multimap<int,int>::const_reverse_iterator mcit;
	for (mcit = mrank.rbegin(); mcit != mrank.rend(); mcit++)
		rank.push_back(mcit->second);
//	mrank.clear();
	multimap<int,int>().swap(mrank);

	multimap<int,pair<int,int> > wmap;
	multimap<int,pair<int,int> >::reverse_iterator mmit; 
	for (int i = 0; i < weight.size(); i++) {
		for (mit = weight[i].begin(); mit != weight[i].end(); mit++) {
			wmap.insert(make_pair(mit->second,make_pair(i,mit->first)));
		}
	}
//	weight.clear();
	SparseVec().swap(weight);

	// greedy algorithm to extract maximal weight spanning tree
	int numedge = 0;
	Graph tree = Graph(gsize);
	pair<int,int> edge;
	for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) {
		edge = mmit->second;
		if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first))
			continue;
		tree.addEdge(edge.first,edge.second);
		numedge++;
		if (numedge>=(gsize-1)) break;
	}

	// compute all pairs shortest paths in the spanning tree
//	computeShortestDistance(tree,treedist);
	
	EdgeList el;
	for (int i = 0; i < gsize; i++) {
		el = tree.out_edges(i);
		if (el.size()>0)
			sptree[i] = vector<int>(el.begin(),el.end());
//		sptree.push_back(vector<int>(el.begin(),el.end()));
//		sptree.insert(el.begin(),el.end());
	}
}
Пример #22
0
int GraphUtil::buildSpanningTree2(Graph& g, SparseVec& treedist, SparseVec& dist, ReducedGraph& sptree) {
	ReducedGraph::iterator rit;
	vector<int>::iterator vit;
	map<int,int>::iterator mit;
	SparseVec::iterator svit;
	int gsize = g.num_vertices();
	SparseVec weight = SparseVec(gsize,map<int,int>());

	for (int i = 0; i < gsize; i++) {
		ReducedGraph tree;
		BFSTree(g, i, tree);
		for (rit = tree.begin(); rit != tree.end(); rit++) {
			for (vit = rit->second.begin(); vit != rit->second.end(); vit++)
				weight[rit->first][*vit] += 1;
		}
		tree.clear();
	}	
	// for test
	/*
	cout << "weight summary ";
	Util::printSparseVec(weight);
	*/

	multimap<int,pair<int,int> > wmap;
	multimap<int,pair<int,int> >::reverse_iterator mmit; 
	for (int i = 0; i < weight.size(); i++) {
		for (mit = weight[i].begin(); mit != weight[i].end(); mit++) {
			wmap.insert(make_pair(mit->second,make_pair(i,mit->first)));
		}
	}
	weight.clear();

	// greedy algorithm to extract maximal weight spanning tree
	int numedge = 0;
	Graph tree = Graph(gsize);
	pair<int,int> edge;
	for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) {
		// for test
//		cout << "(" << mmit->second.first << "," << mmit->second.second << ")" << mmit->first << endl;	
		edge = mmit->second;
		if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first))
			continue;
		tree.addEdge(edge.first,edge.second);
		numedge++;
		if (numedge>=(gsize-1)) break;
	}
	// for test
//	tree.writeGraph(cout);

	computeShortestDistance(tree,treedist);
	
	int tnum = 0;
	EdgeList el;
	for (int i = 0; i < gsize; i++) {
		treedist[i].erase(i);
		tnum += treedist[i].size();
		for (mit = treedist[i].begin(); mit != treedist[i].end(); ) {
			if (mit->second != dist[i][mit->first]) {
				treedist[i].erase(mit++);
			}
			else
				mit++;
		}
		el = tree.out_edges(i);
		sptree[i] = vector<int>(el.begin(),el.end());
	//	sptree.push_back(vector<int>(el.begin(),el.end()));
	}

	// for test
//	Util::printSparseVec(treedist);

	return tnum;
}