Exemple #1
0
	const out_edge_range_t getOutEdges( const vertex_descriptor& v ) const { return out_edges( v, _graph ); }
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;
}
//***********************************************************************
void SpecificEntitiesLoader::XMLHandler::
addSpecificEntity(AnalysisContent& analysis,
                  LinguisticAnalysisStructure::AnalysisGraph* anagraph,
                  const std::string& str,
                  const std::string& type, 
                  uint64_t position, 
                  uint64_t length)
{
  LOGINIT("LP::SpecificEntities");
  LDEBUG << "loader: add entity " << str << "," << type << ",[" << position << "," << length << "]";
  // create RecognizerMatch
  Automaton::RecognizerMatch match(anagraph);

  uint64_t posBegin=position;
  uint64_t posEnd=posBegin+length;

  // find vertices corresponding to pos/len : have to go through the graph
  LinguisticGraph* graph=anagraph->getGraph();
  std::queue<LinguisticGraphVertex> toVisit;
  std::set<LinguisticGraphVertex> visited;
  LinguisticGraphOutEdgeIt outItr,outItrEnd;
 
  // output vertices between begin and end,
  toVisit.push(anagraph->firstVertex());

  bool first=true;
  bool inEntity=false;
  while (!toVisit.empty()) {
    LinguisticGraphVertex v=toVisit.front();
    toVisit.pop();
    if (v == anagraph->lastVertex()) {
      break;
    }

    if (first) {
      first=false;
    }
    else if (inEntity) {
      LinguisticAnalysisStructure::Token* t=get(vertex_token,*graph,v);
      if (t->position() >= posEnd) {
        inEntity=false;
        break; // no need to go further
      }
      else {
        // OME?? valeur true?,"SE"?
        match.addBackVertex(v,true,"SE");
      }
    }
    else {
      LinguisticAnalysisStructure::Token* t=get(vertex_token,*graph,v);
      if(t!=0) {
        if (t->position() == posBegin) {
          match.addBackVertex(v,true,"SE");
          inEntity=true;
        }
      }
    }

    // add next vertices
    for (boost::tie(outItr,outItrEnd)=out_edges(v,*graph); outItr!=outItrEnd; outItr++) 
    {
      LinguisticGraphVertex next=target(*outItr,*graph);
      if (visited.find(next)==visited.end())
      {
        visited.insert(next);
        toVisit.push(next);
      }
    }
  }

  if (match.size()==0) {
    LWARN << "Warning: no matching vertices for given position/length";
  }

  // set entity properties
  match.setType(Common::MediaticData::MediaticData::single().getEntityType(Common::Misc::utf8stdstring2limastring(type)));
  // set normalized form similar to string (otherwise, may cause problem when trying to access the created specific entity)
  match.features().addFeature(DEFAULT_ATTRIBUTE,Common::Misc::utf8stdstring2limastring(str));
  
  // create specific entity from RecognizerMatch using default action
  CreateSpecificEntity createEntity(m_language);
  createEntity(match,analysis);
}
Exemple #4
0
//! 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;
}
    /** \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);
            }
        }
    }
void LRACC::LRACC_dual()
{
///*
 	//float stepsize = 0.00025*(1-iter_lagrangian+MAX_LAGRANGIAN_NUM);
  float stepsize = 0.001;
  cout<<"#"<<iter_lagrangian<< "\t LRACC_DUAL parameters"<< endl;
	for(TPLGY_EITER eiter = edges(circuit).first;eiter!=edges(circuit).second;eiter++)
	{
		TPLGY_VDES src = source(*eiter,circuit);
		TPLGY_VDES tgt = target(*eiter,circuit);
		float ai,aj,di;
		if ((circuit[src].info->type == IN1) || (circuit[src].info->type == FFMS&&in_degree(src, circuit) == 0)){
			aj = 0;
		}
		else{
			aj = mu_sigma[circuit[src].info->name].first;
		}
		if ((circuit[tgt].info->type == OUT1) || (circuit[tgt].info->type == FFMS&&out_degree(tgt, circuit) == 0))
		{
			ai = Time_Limit;
			di = 0;
		}
		else
		{
			ai = mu_sigma[circuit[tgt].info->name].first;
			di = gate_sizes[circuit[tgt].info->name][1]*gate_sizes[circuit[tgt].info->name][2];
		}
		circuit[*eiter].lm+=stepsize*(aj+di-ai);
		//cout<<"new lm = "<<circuit[*eiter].lm<<std::endl;
		if(circuit[*eiter].lm<0)
			circuit[*eiter].lm = 0;
	}
	//project to KKT condition space
	for (VDES_CONTAINER::iterator ii = order.begin(); ii != order.end(); ++ii)
  {
		if(circuit[*ii].info->type==OUT1) continue;
		if(circuit[*ii].info->type==FFMS&&out_degree(*ii,circuit)==0) continue;
		float out_lm = 0;
		for(TPLGY_OEITER oeiter = out_edges(*ii,circuit).first;oeiter!=out_edges(*ii,circuit).second;oeiter++)
		{
			out_lm+=circuit[*oeiter].lm;
		}
		circuit[*ii].lm = out_lm;
		float in_lm = 0;
		for(TPLGY_IEITER ieiter = in_edges(*ii,circuit).first;ieiter!=in_edges(*ii,circuit).second;ieiter++)
		{
			in_lm+=circuit[*ieiter].lm;
		}
		if(in_lm==0) continue;
		for(TPLGY_IEITER ieiter = in_edges(*ii,circuit).first;ieiter!=in_edges(*ii,circuit).second;ieiter++)
		{
			circuit[*ieiter].lm*=out_lm/in_lm;
		}
	}
	float tmp = (total_a-Area_Limit)/Area_Limit; 
	//if(tmp>0.01) tmp = (1*tmp);
	//else if(tmp<0.01&&tmp>0) tmp = 0.01*1;
	//lm_a += stepsize*tmp;
  //if (lm_a < 0)
  {
  	lm_a = 0;
  }
	cout<<"Area_lm ="<<lm_a<<endl<<endl;
	//*/
	//float stepsize = 0.002*(1-iter_lagrangian+MAX_LAGRANGIAN_NUM);
 	/*float stepsize = 0.02;
  cout<<"#"<<iter_lagrangian<< "\t LRACC_DUAL parameters"<< endl;
	//update lm based on this hyperplane
	for (VDES_CONTAINER::iterator ii = order.begin(); ii != order.end(); ++ii)
  {
		TPLGY_VDES fgate = *ii;
    if (BIT_TEST(circuit[fgate].info->flag, OUTPUT_LOAD))
    {
    	continue;//skip the OUTPUT gate
    }
   	if (BIT_TEST(circuit[fgate].info->flag, INPUT_DRIVER))
    {
    	circuit[fgate].lm = 0;///???????????? just for simplicity
      continue;
    } 
 		string nm = (circuit[fgate].info)->name;
		//cout<<nm<<": "<<circuit[fgate].lm;
		float tmp = -arrival_time_slack[nm].second/Time_Limit;
		if(tmp>=0.01) tmp = (15*tmp);
		else if(tmp<0.01&&tmp>0) tmp = 15*0.01;
		tmp*=gate_sizes[circuit[fgate].info->name][1]*gate_sizes[circuit[fgate].info->name][2];
		circuit[fgate].lm += stepsize*tmp;
    if (circuit[fgate].lm <= 0)
    {
    	circuit[fgate].lm = 0;
    }
		//cout<<" -> lm="<<circuit[fgate].lm<<endl;//the Lagrangian value after calculate
  }
	float tmp = (total_a-Area_Limit)/Area_Limit; 
	//if(tmp>0.01) tmp = (1*tmp);
	//else if(tmp<0.01&&tmp>0) tmp = 0.01*1;
	//lm_a += stepsize*tmp;
  //if (lm_a < 0)
  {
  	lm_a = 0;
  }
	cout<<"Area_lm ="<<lm_a<<endl<<endl;//*/


	/*
	//update history based on last iteration
	dual_hist_obj.push_back(total_p);
	dual_hist_subg.push_back(make_pair(total_a-Area_Limit,arrival_time_slack));	
	//find the supporting hyperplane(this hyperplane will correspond to a history)
	vector<float> min(dual_hist_obj.size(),0);
	for(int i=0;i<dual_hist_obj.size();i++)
	{
		for (VDES_CONTAINER::iterator ii = order.begin(); ii != order.end(); ++ii)
    {
        fgate = *ii;
        if (BIT_TEST(circuit[fgate].info->flag, OUTPUT_LOAD||INPUT_DRIVER))
        {
            continue;//skip the OUTPUT gate
        }
    	  string nm = (circuit[fgate].info)->name;
        min[i] -= ((dual_hist_subg[i].second)[nm].second)*circuit[fgate].lm;
		}
		min[i] += (dual_hist_obj[i]);
		min[i] += (dual_hist_subg[i].first)*lm_a;
	}
	int idx = distance(min.begin(),min_element(min.begin(),min.end()));
	//update lm based on this hyperplane
	for (VDES_CONTAINER::iterator ii = order.begin(); ii != order.end(); ++ii)
  {
		fgate = *ii;
    if (BIT_TEST(circuit[fgate].info->flag, OUTPUT_LOAD))
    {
    	continue;//skip the OUTPUT gate
    }
   	if (BIT_TEST(circuit[fgate].info->flag, INPUT_DRIVER))
    {
    	circuit[fgate].lm = 0;///???????????? just for simplicity
      continue;
    } 
	
 		string nm = (circuit[fgate].info)->name;
		float tmp = -(dual_hist_subg.back().second)[nm].second*(dual_hist_subg.back().second)[nm].first/Time_Limit;
		if(tmp>=0.01) tmp = (30*tmp);
		else if(tmp<0.01&&tmp>0) tmp = 30*0.01;
		circuit[fgate].lm += stepsize*tmp;
    if (circuit[fgate].lm <= 0)
    {
    	circuit[fgate].lm = 0;
    }
		else cout<<nm<<" -> lm="<<circuit[fgate].lm<<endl;//the Lagrangian value after calculate
  }
	float tmp = (dual_hist_subg.back().first)/Area_Limit; 
	if(tmp>0.01) tmp = (20*tmp);
	else if(tmp<0.01&&tmp>0) tmp = 20*0.05;
	lm_a += stepsize*tmp;
  if (lm_a < 0)
  {
  	lm_a = 0;
  }
	cout<<"Area_lm ="<<lm_a<<endl<<endl;//*/
}
Exemple #7
0
LimaStatusCode EntityTracker::process(AnalysisContent& analysis) const
{
  TimeUtils::updateCurrentTime();
  SELOGINIT;

  LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData"));
  if (metadata == 0)
  {
    LERROR << "no LinguisticMetaData ! abort" << LENDL;
    return MISSING_DATA;
  }

  AnalysisGraph* anagraph=static_cast<AnalysisGraph*>(analysis.getData("AnalysisGraph"));
  if (anagraph==0)
  {
    LERROR << "no graph 'AnaGraph' available !" << LENDL;
    return MISSING_DATA;
  }

  AnnotationData* annotationData = static_cast< AnnotationData* >(analysis.getData("AnnotationData"));
  if (annotationData==0)
  {
    LERROR << "no annotation graph available !" << LENDL;
    return MISSING_DATA;
  }

  // add new data to store co-references
  CoreferenceData* corefData = new CoreferenceData;
  analysis.setData("CoreferenceData",corefData);
  
  CoreferenceEngine ref;
  LinguisticGraph* graph=anagraph->getGraph();
  LinguisticGraphVertex lastVertex=anagraph->lastVertex();
  LinguisticGraphVertex firstVertex=anagraph->firstVertex();

  std::queue<LinguisticGraphVertex> toVisit;
  std::set<LinguisticGraphVertex> visited;

  LinguisticGraphOutEdgeIt outItr,outItrEnd;

  // output vertices between begin and end,
  // but do not include begin (beginning of text or previous end of sentence) and include end (end of sentence)
  toVisit.push(firstVertex);

  bool first=true;
  bool last=false;
  while (!toVisit.empty()) {
    LinguisticGraphVertex v=toVisit.front();
    toVisit.pop();
    if (last || v == lastVertex) {
      continue;
    }
    if (v == lastVertex) {
      last=true;
    }

    for (boost::tie(outItr,outItrEnd)=out_edges(v,*graph); outItr!=outItrEnd; outItr++)
    {
      LinguisticGraphVertex next=target(*outItr,*graph);
      if (visited.find(next)==visited.end())
      {
        visited.insert(next);
        toVisit.push(next);
      }
    }

    if (first) {
      first=false;
    }
    else {
   // first, check if vertex corresponds to a specific entity
    std::set< AnnotationGraphVertex > matches = annotationData->matches("AnalysisGraph",v,"annot");
    for (std::set< AnnotationGraphVertex >::const_iterator it = matches.begin();
         it != matches.end(); it++)
    {
      AnnotationGraphVertex vx=*it;
      Token* t=get(vertex_token,*graph,vx);
      /* sauvegarde de tous les vertex */
      if (t != 0)
      {
        //storeAllToken(t);
        //allToken.push_back(t);
        ref.storeAllToken(*t);
      }
      if (annotationData->hasAnnotation(vx, Common::Misc::utf8stdstring2limastring("SpecificEntity")))
      {
        /*const SpecificEntityAnnotation* se =
          annotationData->annotation(vx, Common::Misc::utf8stdstring2limastring("SpecificEntity")).
          pointerValue<SpecificEntityAnnotation>();*/
        //storeSpecificEntity(se);
        //Token* t=get(vertex_token,*graph,vx);
        //storedAnnotations.push_back(*t);
        ref.storeAnnot(*t);
//             std::cout<< "le vertex de nom "<< t->stringForm()<<std::endl;
      }
      }
    }
  }

  /* recherche des coréferences entre les entitées nommées précédemment détectées */

  vector<Token> vectTok;
  vector<Token>::const_iterator it1=ref.getAnnotations().begin(), it1_end=ref.getAnnotations().end();
  for (;
       it1 != it1_end;
       it1++)
  {
//     checkCoreference (*it1,ref);
    vectTok = ref.searchCoreference(*it1);
    if (vectTok.size() > 0)
    {
      corefData->push_back(vectTok);
    }
    ref.searchCoreference(*it1);
  }

  /* get the text */
//   LimaStringText* text=static_cast<LimaStringText*>(analysis.getData("Text"));
  
  return SUCCESS_ID;
}
Exemple #8
0
BOOST_AUTO_TEST_CASE_TEMPLATE( intint_bgl_mutable_graph_test, Graph, intint_graphtest_types )
{
  typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;
  typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIter;
  typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;
  typedef typename boost::graph_traits<Graph>::edge_iterator EdgeIter;
  typedef typename boost::graph_traits<Graph>::out_edge_iterator OutEdgeIter;
  typedef typename boost::graph_traits<Graph>::in_edge_iterator InEdgeIter;
  
  Graph g;
  
  Vertex v_root = Vertex();
  BOOST_CHECK_NO_THROW( v_root = add_vertex(g) );
  BOOST_CHECK_EQUAL( num_vertices(g), 1);
  BOOST_CHECK_NO_THROW( remove_vertex(v_root,g) );
  BOOST_CHECK_EQUAL( num_vertices(g), 0);
  
  BOOST_CHECK_NO_THROW( v_root = add_vertex(1, g) );
  g[v_root] = 1;
  BOOST_CHECK_EQUAL( g[v_root], 1 );
  
  int vp_rc[] = {2,3,4,5};
  int ep_rc[] = {1002,1003,1004,1005};
  Vertex v_rc[4];
  Edge e_rc[4];
  for(int i = 0; i < 4; ++i) {
    BOOST_CHECK_NO_THROW( v_rc[i] = add_vertex(g) );
    g[ v_rc[i] ] = vp_rc[i];
    BOOST_CHECK_EQUAL( g[ v_rc[i] ], vp_rc[i] );
    bool edge_added_success = false;
    BOOST_CHECK_NO_THROW( boost::tie(e_rc[i],edge_added_success) = add_edge(v_root, v_rc[i], g) );
    BOOST_CHECK( edge_added_success );
    g[ e_rc[i] ] = ep_rc[i];
    BOOST_CHECK_EQUAL( g[ e_rc[i] ], ep_rc[i] );
  };
  BOOST_CHECK_EQUAL( num_vertices(g), 5 );
  
  int vp_rc1c[] = {6,7,8,9};
  int ep_rc1c[] = {2006,2007,2008,2009};
  Vertex v_rc1c[4];
  Edge e_rc1c[4];
  for(std::size_t i = 0; i < 4; ++i) {
    BOOST_CHECK_NO_THROW( v_rc1c[i] = add_vertex(vp_rc1c[i], g) );
    BOOST_CHECK_EQUAL( g[ v_rc1c[i] ], vp_rc1c[i] );
    bool edge_added_success = false;
    BOOST_CHECK_NO_THROW( boost::tie(e_rc1c[i],edge_added_success) = add_edge(v_rc[0], v_rc1c[i], ep_rc1c[i], g) );
    BOOST_CHECK( edge_added_success );
    BOOST_CHECK_EQUAL( g[ e_rc1c[i] ], ep_rc1c[i] );
  };
  BOOST_CHECK_EQUAL( num_vertices(g), 9 );
  
  
  BOOST_CHECK_EQUAL( g[v_root], 1 );
  {
    OutEdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei,ei_end) = out_edges(v_root,g) );
    std::vector<int> e_list;
    for(; ei != ei_end; ++ei) {
      if(is_edge_valid(*ei,g)) {
        BOOST_CHECK_EQUAL( g[*ei], (g[source(*ei,g)] * 1000 + g[target(*ei,g)]) );
        e_list.push_back(g[*ei]);
      };
    };
    std::sort(e_list.begin(), e_list.end());
    BOOST_CHECK_EQUAL( e_list[0], 1002);
    BOOST_CHECK_EQUAL( e_list[1], 1003);
    BOOST_CHECK_EQUAL( e_list[2], 1004);
    BOOST_CHECK_EQUAL( e_list[3], 1005);
    
    
    InEdgeIter iei, iei_end;
    BOOST_CHECK_NO_THROW( boost::tie(iei, iei_end) = in_edges(v_rc[0], g) );
    BOOST_CHECK( iei != iei_end );
    BOOST_CHECK_EQUAL( g[*iei], 1002);
    ++iei;
    BOOST_CHECK( iei == iei_end );
    
    
    BOOST_CHECK_NO_THROW( boost::tie(ei,ei_end) = out_edges(v_rc[0],g) );
    std::vector<int> e_list2;
    for(; ei != ei_end; ++ei) {
      if(is_edge_valid(*ei,g)) {
        BOOST_CHECK_EQUAL( g[*ei], (g[source(*ei,g)] * 1000 + g[target(*ei,g)]) );
        e_list2.push_back(g[*ei]);
      };
    };
    std::sort(e_list2.begin(), e_list2.end());
    BOOST_CHECK_EQUAL( e_list2[0], 2006);
    BOOST_CHECK_EQUAL( e_list2[1], 2007);
    BOOST_CHECK_EQUAL( e_list2[2], 2008);
    BOOST_CHECK_EQUAL( e_list2[3], 2009);

  };
  
  int vp_rc2c[] = {10,11,12,13};
  int ep_rc2c[] = {3010,3011,3012,3013};
  Vertex v_rc2c[4];
  Edge e_rc2c[4];
  for(std::size_t i = 0; i < 4; ++i) {
#ifdef RK_ENABLE_CXX0X_FEATURES
    BOOST_CHECK_NO_THROW( v_rc2c[i] = add_vertex(std::move(vp_rc2c[i]), g) );
#else
    BOOST_CHECK_NO_THROW( v_rc2c[i] = add_vertex(vp_rc2c[i], g) );
#endif
    bool edge_added_success = false;
#ifdef RK_ENABLE_CXX0X_FEATURES
    BOOST_CHECK_NO_THROW( boost::tie(e_rc2c[i],edge_added_success) = add_edge(v_rc[1], v_rc2c[i], ep_rc2c[i], g) );
#else
    BOOST_CHECK_NO_THROW( boost::tie(e_rc2c[i],edge_added_success) = add_edge(v_rc[1], v_rc2c[i], ep_rc2c[i], g) );
#endif
    BOOST_CHECK( edge_added_success );
  };
  BOOST_CHECK_EQUAL( num_vertices(g), 13 );
  
  {
    OutEdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei,ei_end) = out_edges(v_rc[1],g) );
    std::vector<int> e_list;
    std::vector<int> vp_list;
    for(; ei != ei_end; ++ei) {
      if(is_edge_valid(*ei,g)) {
        BOOST_CHECK_EQUAL( g[*ei], (g[source(*ei,g)] * 1000 + g[target(*ei,g)]) );
        e_list.push_back(g[*ei]);
        vp_list.push_back(g[target(*ei,g)]);
      };
    };
    std::sort(e_list.begin(), e_list.end());
    BOOST_CHECK_EQUAL( e_list[0], 3010);
    BOOST_CHECK_EQUAL( e_list[1], 3011);
    BOOST_CHECK_EQUAL( e_list[2], 3012);
    BOOST_CHECK_EQUAL( e_list[3], 3013);
    
    std::sort(vp_list.begin(), vp_list.end());
    BOOST_CHECK_EQUAL( vp_list[0], 10);
    BOOST_CHECK_EQUAL( vp_list[1], 11);
    BOOST_CHECK_EQUAL( vp_list[2], 12);
    BOOST_CHECK_EQUAL( vp_list[3], 13);
  };
  
  BOOST_CHECK_NO_THROW( clear_vertex(v_rc[0],g) );
  
  BOOST_CHECK_EQUAL( out_degree(v_rc[0], g), 0 );
  BOOST_CHECK_EQUAL( in_degree(v_rc[0], g), 0 );
  BOOST_CHECK_EQUAL( out_degree(v_root, g), 3 );
  BOOST_CHECK_EQUAL( in_degree(v_rc1c[0], g), 0 );
  BOOST_CHECK_EQUAL( in_degree(v_rc1c[1], g), 0 );
  BOOST_CHECK_EQUAL( in_degree(v_rc1c[2], g), 0 );
  BOOST_CHECK_EQUAL( in_degree(v_rc1c[3], g), 0 );
  
  BOOST_CHECK_EQUAL( num_vertices(g), 13 );
  {
    VertexIter vi, vi_end;
    BOOST_CHECK_NO_THROW( boost::tie(vi, vi_end) = vertices(g) );
    std::vector<int> vp_list;
    for(; vi != vi_end; ++vi)
      if( is_vertex_valid(*vi, g) )
        vp_list.push_back( g[*vi] );
    std::sort(vp_list.begin(), vp_list.end());
    BOOST_CHECK_EQUAL( vp_list[0], 1 );
    BOOST_CHECK_EQUAL( vp_list[1], 2 );
    BOOST_CHECK_EQUAL( vp_list[2], 3 );
    BOOST_CHECK_EQUAL( vp_list[3], 4 );
    BOOST_CHECK_EQUAL( vp_list[4], 5 );
    BOOST_CHECK_EQUAL( vp_list[5], 6 );
    BOOST_CHECK_EQUAL( vp_list[6], 7 );
    BOOST_CHECK_EQUAL( vp_list[7], 8 );
    BOOST_CHECK_EQUAL( vp_list[8], 9 );
    BOOST_CHECK_EQUAL( vp_list[9], 10 );
    BOOST_CHECK_EQUAL( vp_list[10], 11 );
    BOOST_CHECK_EQUAL( vp_list[11], 12 );
    BOOST_CHECK_EQUAL( vp_list[12], 13 );
  };
  
  BOOST_CHECK_EQUAL( num_edges(g), 7 );
  {
    EdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei, ei_end) = edges(g) );
    std::vector<int> ep_list;
    for(; ei != ei_end; ++ei)
      if( is_edge_valid(*ei, g) )
        ep_list.push_back( g[*ei] );
    std::sort(ep_list.begin(), ep_list.end());
    BOOST_CHECK_EQUAL( ep_list[0], 1003 );
    BOOST_CHECK_EQUAL( ep_list[1], 1004 );
    BOOST_CHECK_EQUAL( ep_list[2], 1005 );
    BOOST_CHECK_EQUAL( ep_list[3], 3010 );
    BOOST_CHECK_EQUAL( ep_list[4], 3011 );
    BOOST_CHECK_EQUAL( ep_list[5], 3012 );
    BOOST_CHECK_EQUAL( ep_list[6], 3013 );
  };
  
  
  
  BOOST_CHECK_NO_THROW( remove_edge(v_rc[1], v_rc2c[2], g) );
  
  BOOST_CHECK_EQUAL( num_vertices(g), 13 );
  {
    VertexIter vi, vi_end;
    BOOST_CHECK_NO_THROW( boost::tie(vi, vi_end) = vertices(g) );
    std::vector<int> vp_list;
    for(; vi != vi_end; ++vi) {
      if( is_vertex_valid(*vi, g) ) {
        vp_list.push_back( g[*vi] );
      };
    };
    std::sort(vp_list.begin(), vp_list.end());
    BOOST_CHECK_EQUAL( vp_list[0], 1 );
    BOOST_CHECK_EQUAL( vp_list[1], 2 );
    BOOST_CHECK_EQUAL( vp_list[2], 3 );
    BOOST_CHECK_EQUAL( vp_list[3], 4 );
    BOOST_CHECK_EQUAL( vp_list[4], 5 );
    BOOST_CHECK_EQUAL( vp_list[5], 6 );
    BOOST_CHECK_EQUAL( vp_list[6], 7 );
    BOOST_CHECK_EQUAL( vp_list[7], 8 );
    BOOST_CHECK_EQUAL( vp_list[8], 9 );
    BOOST_CHECK_EQUAL( vp_list[9], 10 );
    BOOST_CHECK_EQUAL( vp_list[10], 11 );
    BOOST_CHECK_EQUAL( vp_list[11], 12 );
    BOOST_CHECK_EQUAL( vp_list[12], 13 );
  };
  
  BOOST_CHECK_EQUAL( num_edges(g), 6 );
  {
    EdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei, ei_end) = edges(g) );
    std::vector<int> ep_list;
    for(; ei != ei_end; ++ei) {
      if( is_edge_valid(*ei, g) ) {
        ep_list.push_back( g[*ei] );
      };
    };
    std::sort(ep_list.begin(), ep_list.end());
    BOOST_CHECK_EQUAL( ep_list[0], 1003 );
    BOOST_CHECK_EQUAL( ep_list[1], 1004 );
    BOOST_CHECK_EQUAL( ep_list[2], 1005 );
    BOOST_CHECK_EQUAL( ep_list[3], 3010 );
    BOOST_CHECK_EQUAL( ep_list[4], 3011 );
    BOOST_CHECK_EQUAL( ep_list[5], 3013 );
  };
  
  
  
  BOOST_CHECK_NO_THROW( remove_edge(e_rc2c[3], g) );
  
  BOOST_CHECK_EQUAL( num_vertices(g), 13 );
  {
    VertexIter vi, vi_end;
    BOOST_CHECK_NO_THROW( boost::tie(vi, vi_end) = vertices(g) );
    std::vector<int> vp_list;
    for(; vi != vi_end; ++vi) {
      if( is_vertex_valid(*vi, g) ) {
        vp_list.push_back( g[*vi] );
      };
    };
    std::sort(vp_list.begin(), vp_list.end());
    BOOST_CHECK_EQUAL( vp_list[0], 1 );
    BOOST_CHECK_EQUAL( vp_list[1], 2 );
    BOOST_CHECK_EQUAL( vp_list[2], 3 );
    BOOST_CHECK_EQUAL( vp_list[3], 4 );
    BOOST_CHECK_EQUAL( vp_list[4], 5 );
    BOOST_CHECK_EQUAL( vp_list[5], 6 );
    BOOST_CHECK_EQUAL( vp_list[6], 7 );
    BOOST_CHECK_EQUAL( vp_list[7], 8 );
    BOOST_CHECK_EQUAL( vp_list[8], 9 );
    BOOST_CHECK_EQUAL( vp_list[9], 10 );
    BOOST_CHECK_EQUAL( vp_list[10], 11 );
    BOOST_CHECK_EQUAL( vp_list[11], 12 );
    BOOST_CHECK_EQUAL( vp_list[12], 13 );
  };
  
  BOOST_CHECK_EQUAL( num_edges(g), 5 );
  {
    EdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei, ei_end) = edges(g) );
    std::vector<int> ep_list;
    for(; ei != ei_end; ++ei) {
      if( is_edge_valid(*ei, g) ) {
        ep_list.push_back( g[*ei] );
      };
    };
    std::sort(ep_list.begin(), ep_list.end());
    BOOST_CHECK_EQUAL( ep_list[0], 1003 );
    BOOST_CHECK_EQUAL( ep_list[1], 1004 );
    BOOST_CHECK_EQUAL( ep_list[2], 1005 );
    BOOST_CHECK_EQUAL( ep_list[3], 3010 );
    BOOST_CHECK_EQUAL( ep_list[4], 3011 );
  };
  
  
  
  BOOST_CHECK_NO_THROW( clear_vertex(v_rc2c[0], g) );
  BOOST_CHECK_NO_THROW( remove_vertex(v_rc2c[0], g) );
  
  BOOST_CHECK_EQUAL( num_vertices(g), 12 );
  {
    VertexIter vi, vi_end;
    BOOST_CHECK_NO_THROW( boost::tie(vi, vi_end) = vertices(g) );
    std::vector<int> vp_list;
    for(; vi != vi_end; ++vi) {
      if( is_vertex_valid(*vi, g) ) {
        vp_list.push_back( g[*vi] );
      };
    };
    std::sort(vp_list.begin(), vp_list.end());
    BOOST_CHECK_EQUAL( vp_list[0], 1 );
    BOOST_CHECK_EQUAL( vp_list[1], 2 );
    BOOST_CHECK_EQUAL( vp_list[2], 3 );
    BOOST_CHECK_EQUAL( vp_list[3], 4 );
    BOOST_CHECK_EQUAL( vp_list[4], 5 );
    BOOST_CHECK_EQUAL( vp_list[5], 6 );
    BOOST_CHECK_EQUAL( vp_list[6], 7 );
    BOOST_CHECK_EQUAL( vp_list[7], 8 );
    BOOST_CHECK_EQUAL( vp_list[8], 9 );
    BOOST_CHECK_EQUAL( vp_list[9], 11 );
    BOOST_CHECK_EQUAL( vp_list[10], 12 );
    BOOST_CHECK_EQUAL( vp_list[11], 13 );
  };
  
  BOOST_CHECK_EQUAL( num_edges(g), 4 );
  {
    EdgeIter ei, ei_end;
    BOOST_CHECK_NO_THROW( boost::tie(ei, ei_end) = edges(g) );
    std::vector<int> ep_list;
    for(; ei != ei_end; ++ei) {
      if( is_edge_valid(*ei, g) ) {
        ep_list.push_back( g[*ei] );
      };
    };
    std::sort(ep_list.begin(), ep_list.end());
    BOOST_CHECK_EQUAL( ep_list[0], 1003 );
    BOOST_CHECK_EQUAL( ep_list[1], 1004 );
    BOOST_CHECK_EQUAL( ep_list[2], 1005 );
    BOOST_CHECK_EQUAL( ep_list[3], 3011 );
  };
  
  
};
	inline void
	harel_bfs_separation(Graph &g, WeightMap w, int passes, int k = 3)
	{
		typedef typename graph_traits<Graph>::vertex_descriptor vertex;
		typedef typename graph_traits<Graph>::edge_descriptor edge;
		typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
		typedef typename graph_traits<Graph>::out_edge_iterator out_edge_iterator;
		typedef typename graph_traits<Graph>::directed_category directed;
		typedef typename property_traits<WeightMap>::value_type weight;
		typedef typename detail::harel_bfs_traits<Graph, WeightMap>::neighbor_similarity_map NSMap;
		
		BOOST_STATIC_ASSERT((is_same<directed, directed_tag>::value));
		function_requires< WritablePropertyMapConcept<WeightMap, edge> >();
		
		// process:
		//	- iterate through all the edges in this graph (however to save computation time we're going to iterate
		//			through each vertex and its out_edges so we're only computing half the NS map for each edge)
		//	- calculate the NS map to a depth of k for each vertex
		//	- use the NS map to apply our separating algorithm
		//	- ^ do above passes times
		
		// this is our new map, which we'll use to hold our new weights until the iteration is done
		std::map<edge, weight> new_weights;
		
		// this will cache our NSMaps
		std::map<vertex, NSMap> ns_cache;
		
		for(int pass = 0; pass < passes; pass++) {
			std::cout << "starting pass " << pass << std::endl;
			vertex_iterator vi, vend;
			vertex target;
			boost::progress_display dsp(num_vertices(g), std::cout);

			for(tie(vi, vend) = vertices(g); vi != vend; ++vi) {
				// calculate the NS map for the source node
				if (!ns_cache.count(*vi)) detail::harel_bfs_create_ns_map(g, w, *vi, k, ns_cache[*vi], true);
				NSMap &source_map = ns_cache[*vi];
				
				// now go through each of the edges coming out of this vertex
				out_edge_iterator ei, eend;
				for(tie(ei, eend) = out_edges(*vi, g); ei != eend; ++ei) {
					// get the NS map for the target node
					target = boost::target(*ei, g);
					if (!ns_cache.count(target)) detail::harel_bfs_create_ns_map(g, w, target, k, ns_cache[target], true);
					NSMap &target_map = ns_cache[target];
					
					// calculate their difference
					weight difference = detail::ns_difference<Graph, WeightMap>(source_map, target_map);
					// use exp(2k - ||x-y||) - 1  --> where ||x-y|| is difference
					new_weights.insert(std::make_pair<edge, weight>(*ei, exp(2 * k - difference)/* - 1*/)); // no longer subtracting 1 to avoid getting negative numbers when difference > 2*k
				}
				++dsp;
			}
			
			// now transfer the new weights over to our old weight map
			for(typename std::map<edge, weight>::iterator i = new_weights.begin(); i != new_weights.end(); ++i) {
				//put(w, (*i).first, (get(w, (*i).first) > 0)?(*i).second:0);
				put(w, (*i).first, (*i).second); // above line is redundant
			}
			new_weights.clear();
			ns_cache.clear();
			
			std::cout << "pass " << pass << " complete." << std::endl;
		}
	}
Exemple #10
0
    void EngineManager::loadRadio(RadioRepresentation rad)
    {
        //Set the current radio representation
        radioRep_ = rad;

        //Set the controller repositories in the ControllerManager
        controllerManager_.addRepository(reps_.contRepository);

        //Load the controllers
        vector<ControllerDescription> conts = rad.getControllers();
        vector<ControllerDescription>::iterator contIt;
        for(contIt=conts.begin(); contIt!=conts.end(); ++contIt)
        {
            controllerManager_.loadController(contIt->type);
        }

        engineGraph_ = rad.getEngineGraph();

        //Create the engines
        EngVertexIterator i, iend;
        for(b::tie(i,iend) = vertices(engineGraph_); i != iend; ++i)
        {
            //Get the engine description
            EngineDescription current = engineGraph_[*i];

            //Add the engine to our vector
            engines_.push_back(createEngine(current));
        }

        //Do a topological sort of the graph
        deque<unsigned> topoOrder;
        topological_sort(engineGraph_, front_inserter(topoOrder), b::vertex_index_map(b::identity_property_map()));

        //Go through graph in topological order and set buffers
        for(deque<unsigned>::iterator i = topoOrder.begin(); i != topoOrder.end(); ++i)
        {
            //Get input buffers
            vector< b::shared_ptr< DataBufferBase > > inputBuffers, outputBuffers;
            EngInEdgeIterator edgeIt, edgeItEnd;
            for(b::tie(edgeIt, edgeItEnd) = in_edges(*i, engineGraph_); edgeIt != edgeItEnd; ++edgeIt)
            {
                inputBuffers.push_back(engineGraph_[*edgeIt].theBuffer);
            }

            //Load the engine, passing in the input buffers
            outputBuffers = engines_[*i].loadEngine(engineGraph_[*i], inputBuffers);

            //Set the ouput buffers in the graph edges
            EngOutEdgeIterator outEdgeIt, outEdgeItEnd;
            for(b::tie(outEdgeIt, outEdgeItEnd) = out_edges(*i, engineGraph_); outEdgeIt != outEdgeItEnd; ++outEdgeIt)
            {
                for(vector< b::shared_ptr< DataBufferBase > >::iterator it = outputBuffers.begin(); it != outputBuffers.end(); ++it)
                {
                    LinkDescription first = (*it)->getLinkDescription();
                    LinkDescription second = engineGraph_[*outEdgeIt];
                    if(sameLink(first, second))
                    {
                        engineGraph_[*outEdgeIt].theBuffer = *it;
                        engineGraph_[*outEdgeIt].theBuffer->setLinkDescription( second );
                    }
                }
            }
        }
    }
void r_c_shortest_paths_dispatch
( const Graph& g, 
  const VertexIndexMap& vertex_index_map, 
  const EdgeIndexMap& /*edge_index_map*/, 
  typename graph_traits<Graph>::vertex_descriptor s, 
  typename graph_traits<Graph>::vertex_descriptor t, 
  // each inner vector corresponds to a pareto-optimal path
  std::vector
    <std::vector
      <typename graph_traits
        <Graph>::edge_descriptor> >& pareto_optimal_solutions, 
  std::vector
    <Resource_Container>& pareto_optimal_resource_containers, 
  bool b_all_pareto_optimal_solutions, 
  // to initialize the first label/resource container 
  // and to carry the type information
  const Resource_Container& rc, 
  Resource_Extension_Function& ref, 
  Dominance_Function& dominance, 
  // to specify the memory management strategy for the labels
  Label_Allocator /*la*/, 
  Visitor vis )
{
  pareto_optimal_resource_containers.clear();
  pareto_optimal_solutions.clear();

  unsigned long i_label_num = 0;
  typedef 
    typename 
      Label_Allocator::template rebind
        <r_c_shortest_paths_label
          <Graph, Resource_Container> >::other LAlloc;
  LAlloc l_alloc;
  typedef 
    ks_smart_pointer
      <r_c_shortest_paths_label<Graph, Resource_Container> > Splabel;
  std::priority_queue<Splabel, std::vector<Splabel>, std::greater<Splabel> > 
    unprocessed_labels;

  bool b_feasible = true;
  r_c_shortest_paths_label<Graph, Resource_Container>* first_label = 
    l_alloc.allocate( 1 );
  l_alloc.construct
    ( first_label, 
      r_c_shortest_paths_label
        <Graph, Resource_Container>( i_label_num++, 
                                     rc, 
                                     0, 
                                     typename graph_traits<Graph>::
                                       edge_descriptor(), 
                                     s ) );

  Splabel splabel_first_label = Splabel( first_label );
  unprocessed_labels.push( splabel_first_label );
  std::vector<std::list<Splabel> > vec_vertex_labels( num_vertices( g ) );
  vec_vertex_labels[vertex_index_map[s]].push_back( splabel_first_label );
  std::vector<typename std::list<Splabel>::iterator> 
    vec_last_valid_positions_for_dominance( num_vertices( g ) );
  for( int i = 0; i < static_cast<int>( num_vertices( g ) ); ++i )
    vec_last_valid_positions_for_dominance[i] = vec_vertex_labels[i].begin();
  std::vector<int> vec_last_valid_index_for_dominance( num_vertices( g ), 0 );
  std::vector<bool> 
    b_vec_vertex_already_checked_for_dominance( num_vertices( g ), false );
  while( !unprocessed_labels.empty()  && vis.on_enter_loop(unprocessed_labels, g) )
  {
    Splabel cur_label = unprocessed_labels.top();
    unprocessed_labels.pop();
    vis.on_label_popped( *cur_label, g );
    // an Splabel object in unprocessed_labels and the respective Splabel 
    // object in the respective list<Splabel> of vec_vertex_labels share their 
    // embedded r_c_shortest_paths_label object
    // to avoid memory leaks, dominated 
    // r_c_shortest_paths_label objects are marked and deleted when popped 
    // from unprocessed_labels, as they can no longer be deleted at the end of 
    // the function; only the Splabel object in unprocessed_labels still 
    // references the r_c_shortest_paths_label object
    // this is also for efficiency, because the else branch is executed only 
    // if there is a chance that extending the 
    // label leads to new undominated labels, which in turn is possible only 
    // if the label to be extended is undominated
    if( !cur_label->b_is_dominated )
    {
      int i_cur_resident_vertex_num = cur_label->resident_vertex;
      std::list<Splabel>& list_labels_cur_vertex = 
        vec_vertex_labels[i_cur_resident_vertex_num];
      if( static_cast<int>( list_labels_cur_vertex.size() ) >= 2 
          && vec_last_valid_index_for_dominance[i_cur_resident_vertex_num] 
               < static_cast<int>( list_labels_cur_vertex.size() ) )
      {
        typename std::list<Splabel>::iterator outer_iter = 
          list_labels_cur_vertex.begin();
        bool b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = false;
        while( outer_iter != list_labels_cur_vertex.end() )
        {
          Splabel cur_outer_splabel = *outer_iter;
          typename std::list<Splabel>::iterator inner_iter = outer_iter;
          if( !b_outer_iter_at_or_beyond_last_valid_pos_for_dominance 
              && outer_iter == 
                   vec_last_valid_positions_for_dominance
                     [i_cur_resident_vertex_num] )
            b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = true;
          if( !b_vec_vertex_already_checked_for_dominance
                [i_cur_resident_vertex_num] 
              || b_outer_iter_at_or_beyond_last_valid_pos_for_dominance )
          {
            ++inner_iter;
          }
          else
          {
            inner_iter = 
              vec_last_valid_positions_for_dominance
                [i_cur_resident_vertex_num];
            ++inner_iter;
          }
          bool b_outer_iter_erased = false;
          while( inner_iter != list_labels_cur_vertex.end() )
          {
            Splabel cur_inner_splabel = *inner_iter;
            if( dominance( cur_outer_splabel->
                             cumulated_resource_consumption, 
                           cur_inner_splabel->
                             cumulated_resource_consumption ) )
            {
              typename std::list<Splabel>::iterator buf = inner_iter;
              ++inner_iter;
              list_labels_cur_vertex.erase( buf );
              if( cur_inner_splabel->b_is_processed )
              {
                l_alloc.destroy( cur_inner_splabel.get() );
                l_alloc.deallocate( cur_inner_splabel.get(), 1 );
              }
              else
                cur_inner_splabel->b_is_dominated = true;
              continue;
            }
            else
              ++inner_iter;
            if( dominance( cur_inner_splabel->
                             cumulated_resource_consumption, 
                           cur_outer_splabel->
                             cumulated_resource_consumption ) )
            {
              typename std::list<Splabel>::iterator buf = outer_iter;
              ++outer_iter;
              list_labels_cur_vertex.erase( buf );
              b_outer_iter_erased = true;
              if( cur_outer_splabel->b_is_processed )
              {
                l_alloc.destroy( cur_outer_splabel.get() );
                l_alloc.deallocate( cur_outer_splabel.get(), 1 );
              }
              else
                cur_outer_splabel->b_is_dominated = true;
              break;
            }
          }
          if( !b_outer_iter_erased )
            ++outer_iter;
        }
        if( static_cast<int>( list_labels_cur_vertex.size() ) > 1 )
          vec_last_valid_positions_for_dominance[i_cur_resident_vertex_num] = 
            (--(list_labels_cur_vertex.end()));
        else
          vec_last_valid_positions_for_dominance[i_cur_resident_vertex_num] = 
            list_labels_cur_vertex.begin();
        b_vec_vertex_already_checked_for_dominance
          [i_cur_resident_vertex_num] = true;
        vec_last_valid_index_for_dominance[i_cur_resident_vertex_num] = 
          static_cast<int>( list_labels_cur_vertex.size() ) - 1;
      }
    }
    if( !b_all_pareto_optimal_solutions && cur_label->resident_vertex == t )
    {
      // the devil don't sleep
      if( cur_label->b_is_dominated )
      {
        l_alloc.destroy( cur_label.get() );
        l_alloc.deallocate( cur_label.get(), 1 );
      }
      while( unprocessed_labels.size() )
      {
        Splabel l = unprocessed_labels.top();
        unprocessed_labels.pop();
        // delete only dominated labels, because nondominated labels are 
        // deleted at the end of the function
        if( l->b_is_dominated )
        {
          l_alloc.destroy( l.get() );
          l_alloc.deallocate( l.get(), 1 );
        }
      }
      break;
    }
    if( !cur_label->b_is_dominated )
    {
      cur_label->b_is_processed = true;
      vis.on_label_not_dominated( *cur_label, g );
      typename graph_traits<Graph>::vertex_descriptor cur_vertex = 
        cur_label->resident_vertex;
      typename graph_traits<Graph>::out_edge_iterator oei, oei_end;
      for( boost::tie( oei, oei_end ) = out_edges( cur_vertex, g ); 
           oei != oei_end; 
           ++oei )
      {
        b_feasible = true;
        r_c_shortest_paths_label<Graph, Resource_Container>* new_label = 
          l_alloc.allocate( 1 );
        l_alloc.construct( new_label, 
                           r_c_shortest_paths_label
                             <Graph, Resource_Container>
                               ( i_label_num++, 
                                 cur_label->cumulated_resource_consumption, 
                                 cur_label.get(), 
                                 *oei, 
                                 target( *oei, g ) ) );
        b_feasible = 
          ref( g, 
               new_label->cumulated_resource_consumption, 
               new_label->p_pred_label->cumulated_resource_consumption, 
               new_label->pred_edge );

        if( !b_feasible )
        {
          vis.on_label_not_feasible( *new_label, g );
          l_alloc.destroy( new_label );
          l_alloc.deallocate( new_label, 1 );
        }
        else
        {
          const r_c_shortest_paths_label<Graph, Resource_Container>& 
            ref_new_label = *new_label;
          vis.on_label_feasible( ref_new_label, g );
          Splabel new_sp_label( new_label );
          vec_vertex_labels[vertex_index_map[new_sp_label->resident_vertex]].
            push_back( new_sp_label );
          unprocessed_labels.push( new_sp_label );
        }
      }
    }
    else
    {
      vis.on_label_dominated( *cur_label, g );
      l_alloc.destroy( cur_label.get() );
      l_alloc.deallocate( cur_label.get(), 1 );
    }
  }
  std::list<Splabel> dsplabels = vec_vertex_labels[vertex_index_map[t]];
  typename std::list<Splabel>::const_iterator csi = dsplabels.begin();
  typename std::list<Splabel>::const_iterator csi_end = dsplabels.end();
  // if d could be reached from o
  if( !dsplabels.empty() )
  {
    for( ; csi != csi_end; ++csi )
    {
      std::vector<typename graph_traits<Graph>::edge_descriptor> 
        cur_pareto_optimal_path;
      const r_c_shortest_paths_label<Graph, Resource_Container>* p_cur_label = 
        (*csi).get();
      pareto_optimal_resource_containers.
        push_back( p_cur_label->cumulated_resource_consumption );
      while( p_cur_label->num != 0 )
      {
        cur_pareto_optimal_path.push_back( p_cur_label->pred_edge );
        p_cur_label = p_cur_label->p_pred_label;
      }
      pareto_optimal_solutions.push_back( cur_pareto_optimal_path );
      if( !b_all_pareto_optimal_solutions )
        break;
    }
  }

  int i_size = static_cast<int>( vec_vertex_labels.size() );
  for( int i = 0; i < i_size; ++i )
  {
    const std::list<Splabel>& list_labels_cur_vertex = vec_vertex_labels[i];
    csi_end = list_labels_cur_vertex.end();
    for( csi = list_labels_cur_vertex.begin(); csi != csi_end; ++csi )
    {
      l_alloc.destroy( (*csi).get() );
      l_alloc.deallocate( (*csi).get(), 1 );
    }
  }
} // r_c_shortest_paths_dispatch
Exemple #12
0
void program::pretty_print(std::ostream & out) const
{
	for (std::map<std::string, cfg>::const_iterator it = m_cfgs.begin(); it != m_cfgs.end(); ++it)
	{
		out << "def " << it->first << ":\n";

		cfg const & c = it->second;

		std::map<cfg::vertex_descriptor, std::size_t> index_map;
		std::pair<cfg::vertex_iterator, cfg::vertex_iterator> vertices_range = vertices(c);
		for (cfg::vertex_iterator it = vertices_range.first; it != vertices_range.second; ++it)
		{
			std::size_t vidx = index_map.size();
			index_map[*it] = vidx;
		}

		out << "    entry " << index_map[c.entry()] << "\n";

		for (std::size_t i = 0; i < c.params().size(); ++i)
			out << "    param: " << c.params()[i] << "\n";

		for (std::size_t i = 0; i < c.locals().size(); ++i)
			out << "    var: " << c.locals()[i] << "\n";

		vertices_range = vertices(c);
		for (cfg::vertex_iterator it = vertices_range.first; it != vertices_range.second; ++it)
		{
			cfg::node const & node = c[*it];

			out << "    node " << index_map[*it] << " ";

			switch (node.type)
			{
			case cfg::nt_none:
				out << "none";
				break;
			case cfg::nt_exit:
				out << "exit";
				break;
			case cfg::nt_value:
				out << "value";
				break;
			case cfg::nt_call:
				out << "call";
				break;
			case cfg::nt_phi:
				out << "phi";
				break;
			default:
				BOOST_ASSERT(0 && "Unknown node type");
			}

			out << '\n';

			for (std::size_t j = 0; j < node.ops.size(); ++j)
			{
				cfg::operand const & op = node.ops[j];

				static char const * op_names[] = { "none", "func", "oper", "const", "member", "node", "var", "varptr" };

				BOOST_ASSERT(op.type <= cfg::ot_varptr);
				out << "        " << op_names[op.type] << " ";

				if (op.id.which() == 2)
				{
					cfg::vertex_descriptor op_node = boost::get<cfg::vertex_descriptor>(op.id);
					out << index_map[op_node];
				}
				else
				{
					out << op.id;
				}

				out << "\n";
			}

			std::pair<cfg::out_edge_iterator, cfg::out_edge_iterator> out_edges_range = out_edges(*it, c);
			for (cfg::out_edge_iterator edge_it = out_edges_range.first; edge_it != out_edges_range.second; ++edge_it)
			{
				out << "        succ " << index_map[target(*edge_it, c)] << " " << c[*edge_it].id << " " << c[*edge_it].cond << '\n';
			}
		}

		out << std::endl;
	}
}
  typename graph_traits<VertexListGraph>::degree_size_type
  edge_connectivity(VertexListGraph& g, OutputIterator disconnecting_set)
  {
    //-------------------------------------------------------------------------
    // Type Definitions
    typedef graph_traits<VertexListGraph> Traits;
    typedef typename Traits::vertex_iterator vertex_iterator;
    typedef typename Traits::edge_iterator edge_iterator;
    typedef typename Traits::out_edge_iterator out_edge_iterator;
    typedef typename Traits::vertex_descriptor vertex_descriptor;
    typedef typename Traits::degree_size_type degree_size_type;
    typedef color_traits<default_color_type> Color;

    typedef adjacency_list_traits<vecS, vecS, directedS> Tr;
    typedef typename Tr::edge_descriptor Tr_edge_desc;
    typedef adjacency_list<vecS, vecS, directedS, no_property, 
      property<edge_capacity_t, degree_size_type,
	property<edge_residual_capacity_t, degree_size_type,
	  property<edge_reverse_t, Tr_edge_desc> > > > 
      FlowGraph;
    typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor;

    //-------------------------------------------------------------------------
    // Variable Declarations
    vertex_descriptor u, v, p, k;
    edge_descriptor e1, e2;
    bool inserted;
    vertex_iterator vi, vi_end;
    edge_iterator ei, ei_end;
    degree_size_type delta, alpha_star, alpha_S_k;
    std::set<vertex_descriptor> S, neighbor_S;
    std::vector<vertex_descriptor> S_star, non_neighbor_S;
    std::vector<default_color_type> color(num_vertices(g));
    std::vector<edge_descriptor> pred(num_vertices(g));

    //-------------------------------------------------------------------------
    // Create a network flow graph out of the undirected graph
    FlowGraph flow_g(num_vertices(g));

    typename property_map<FlowGraph, edge_capacity_t>::type
      cap = get(edge_capacity, flow_g);
    typename property_map<FlowGraph, edge_residual_capacity_t>::type
      res_cap = get(edge_residual_capacity, flow_g);
    typename property_map<FlowGraph, edge_reverse_t>::type
      rev_edge = get(edge_reverse, flow_g);

    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
      u = source(*ei, g), v = target(*ei, g);
      tie(e1, inserted) = add_edge(u, v, flow_g);
      cap[e1] = 1;
      tie(e2, inserted) = add_edge(v, u, flow_g);
      cap[e2] = 1; // not sure about this
      rev_edge[e1] = e2;
      rev_edge[e2] = e1;
    }

    //-------------------------------------------------------------------------
    // The Algorithm

    tie(p, delta) = detail::min_degree_vertex(g);
    S_star.push_back(p);
    alpha_star = delta;
    S.insert(p);
    neighbor_S.insert(p);
    detail::neighbors(g, S.begin(), S.end(), 
		      std::inserter(neighbor_S, neighbor_S.begin()));

    std::set_difference(vertices(g).first, vertices(g).second,
			neighbor_S.begin(), neighbor_S.end(),
			std::back_inserter(non_neighbor_S));

    while (!non_neighbor_S.empty()) { // at most n - 1 times
      k = non_neighbor_S.front();

      alpha_S_k = edmunds_karp_max_flow
	(flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]);

      if (alpha_S_k < alpha_star) {
	alpha_star = alpha_S_k;
	S_star.clear();
	for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi)
	  if (color[*vi] != Color::white())
	    S_star.push_back(*vi);
      }
      S.insert(k);
      neighbor_S.insert(k);
      detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin()));
      non_neighbor_S.clear();
      std::set_difference(vertices(g).first, vertices(g).second,
			  neighbor_S.begin(), neighbor_S.end(),
			  std::back_inserter(non_neighbor_S));
    }
    //-------------------------------------------------------------------------
    // Compute edges of the cut [S*, ~S*]
    std::vector<bool> in_S_star(num_vertices(g), false);
    typename std::vector<vertex_descriptor>::iterator si;
    for (si = S_star.begin(); si != S_star.end(); ++si)
      in_S_star[*si] = true;

    degree_size_type c = 0;
    for (si = S_star.begin(); si != S_star.end(); ++si) {
      out_edge_iterator ei, ei_end;
      for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei)
	if (!in_S_star[target(*ei, g)]) {
	  *disconnecting_set++ = *ei;
	  ++c;
	}
    }
    return c;
  }
void FSISPOptimizerOLD::calculateFunctionBenefitsWithSCFGProperties(ControlFlowGraph scfg)
{
	// get node property structures
	property_map<ControlFlowGraph, nodetype_t>::type scfg_nodeTypeNProp = get(nodetype_t(), scfg);
	property_map<ControlFlowGraph, startaddr_t>::type scfg_startAddrNProp = get(startaddr_t(), scfg);
//	property_map<ControlFlowGraph, startaddrstring_t>::type scfg_startAddrStringNProp = get(startaddrstring_t(), scfg); // unused
//	property_map<ControlFlowGraph, bbsize_t>::type scfg_bbSizeNProp = get(bbsize_t(), scfg); // unused
//	property_map<ControlFlowGraph, calllabel_t>::type scfg_calllabel_t = get(calllabel_t(), scfg); // unused

	// get edge property structures
	property_map<ControlFlowGraph, cost_t>::type scfg_costEProp = get(cost_t(), scfg);
	property_map<ControlFlowGraph, cost_onchip_t>::type scfg_costOnChipEProp = get(cost_onchip_t(), scfg);
	property_map<ControlFlowGraph, cost_offchip_t>::type scfg_costOffChipEProp = get(cost_offchip_t(), scfg);
	property_map<ControlFlowGraph, mem_penalty_t>::type scfg_memPenaltyEProp = get(mem_penalty_t(), scfg);
	property_map<ControlFlowGraph, activation_t>::type scfg_actEProp = get(activation_t(), scfg);

	cfgVertexIter vp;
	cfgOutEdgeIter epo;
	cfgInEdgeIter epi;
	CFGVertex v;
	CFGEdge e;

	LOG_DEBUG(logger, function_data.size() << " functions found.");
	// cycle through all vertices of the supergraph and set the max flow (activation count) and the costs for each basic block for each function (stored in function_data) 
	for(vp = vertices(scfg); vp.first != vp.second; ++vp.first)
	{
		v = *vp.first;

		if(get(scfg_nodeTypeNProp, v) == BasicBlock)
		{
			uint32_t bb_addr = get(scfg_startAddrNProp, v);
			uint32_t affiliated_function=0;

			bool block_found = false;
			// assign the wcet costs for that block to the function it belongs to
			for(uint32_t i = 0; i < function_data.size(); i++)
			{
				if((bb_addr >= function_data[i].address) && (function_data[i].end_address > bb_addr))
				{

					block_found = true;
					LOG_DEBUG(logger, "Assigning block cost of bb: 0x" << hex << bb_addr << "  for function " <<  function_data[i].name);
					affiliated_function = i;
					break;
				}
			}

			assert(block_found);

			for(epo = out_edges(v, scfg); epo.first != epo.second; ++epo.first) 
			{
				e = *epo.first;
				uint32_t cur_cost = get(scfg_costEProp, e);
				uint32_t off_cost = get(scfg_costOffChipEProp, e);
				uint32_t on_cost = get(scfg_costOnChipEProp, e);
				uint32_t mem_penalty = get(scfg_memPenaltyEProp, e);
				uint32_t activation_count = get(scfg_actEProp,e);

				switch((analysis_metric_t) conf->getUint(CONF_USE_METRIC))
				{
					case WCET_RATIO_FILES:
					case WCET:
						{
							function_data[affiliated_function].cur_cost += activation_count * cur_cost;
							function_data[affiliated_function].offchip_cost += activation_count * off_cost;
							function_data[affiliated_function].onchip_cost += activation_count * on_cost;
							assert(mem_penalty == (off_cost - on_cost));
							function_data[affiliated_function].benefit += activation_count * (off_cost - on_cost);
							break;
						}
					case MDIC:
						{
							function_data[affiliated_function].cur_cost += activation_count * cur_cost;
							function_data[affiliated_function].offchip_cost += activation_count * off_cost;
							function_data[affiliated_function].onchip_cost += activation_count * on_cost;
							function_data[affiliated_function].benefit += function_data[affiliated_function].cur_cost;
							break;
						}
					case MPL:
						{
							function_data[affiliated_function].cur_cost += cur_cost;
							function_data[affiliated_function].offchip_cost += off_cost;
							function_data[affiliated_function].onchip_cost += on_cost;
							function_data[affiliated_function].benefit += function_data[affiliated_function].cur_cost;
							// this method is _not_ to be used, so fall down to assert(false)
//							break; 
						}
					default:
						{
							assert(false);
						}
				}

			}
		}
	}

	LOG_DEBUG(logger, function_data.size() << " functions found.");
	
	for(uint32_t i = 0; i < function_data.size(); i++)
	{
		LOG_DEBUG(logger, "Function id: " << function_data[i].id << " name: " << function_data[i].name << " addr: 0x" << hex << function_data[i].address << " end addr: 0x" << function_data[i].end_address << " size: "  << dec << function_data[i].size << " on/offchip cost: " << function_data[i].onchip_cost << "/" << function_data[i].offchip_cost << " benefit: " << function_data[i].benefit);
	} 
}
void mitk::ConnectomicsStatisticsCalculator::CalculateClusteringCoefficients()
{
  VertexIteratorType vi, vi_end;
  std::vector<double> m_VectorOfClusteringCoefficientsC;
  std::vector<double> m_VectorOfClusteringCoefficientsD;
  std::vector<double> m_VectorOfClusteringCoefficientsE;
  typedef std::set<VertexDescriptorType> NeighborSetType;
  typedef NetworkType::out_edge_iterator OutEdgeIterType;

  for(boost::tie(vi,vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi)
  {
    // Get the list of vertices which are in the neighborhood of vi.
    std::pair<AdjacencyIteratorType, AdjacencyIteratorType> adjacent =
      boost::adjacent_vertices(*vi, *(m_Network->GetBoostGraph()) );

    //Populate a set with the neighbors of vi
    NeighborSetType neighbors;
    for(; adjacent.first!=adjacent.second; ++adjacent.first)
    {
      neighbors.insert(*adjacent.first);
    }

    // Now, count the edges between vertices in the neighborhood.
    unsigned int neighborhood_edge_count = 0;
    if(neighbors.size() > 0)
    {
      NeighborSetType::iterator iter;
      for(iter = neighbors.begin(); iter != neighbors.end(); ++iter)
      {
        std::pair<OutEdgeIterType, OutEdgeIterType> oe = out_edges(*iter, *(m_Network->GetBoostGraph()) );
        for(; oe.first != oe.second; ++oe.first)
        {
          if(neighbors.find(target(*oe.first, *(m_Network->GetBoostGraph()) )) != neighbors.end())
          {
            ++neighborhood_edge_count;
          }
        }
      }
      neighborhood_edge_count /= 2;
    }
    //Clustering Coefficienct C,E
    if(neighbors.size() > 1)
    {
      double num   = neighborhood_edge_count;
      double denum = neighbors.size() * (neighbors.size()-1)/2;
      m_VectorOfClusteringCoefficientsC.push_back( num / denum);
      m_VectorOfClusteringCoefficientsE.push_back( num / denum);
    }
    else
    {
      m_VectorOfClusteringCoefficientsC.push_back(0.0);
    }

    //Clustering Coefficienct D
    if(neighbors.size() > 0)
    {
      double num   = neighbors.size() + neighborhood_edge_count;
      double denum = ( (neighbors.size()+1) * neighbors.size()) / 2;
      m_VectorOfClusteringCoefficientsD.push_back( num / denum);
    }
    else
    {
      m_VectorOfClusteringCoefficientsD.push_back(0.0);
    }
  }

  // Average Clustering coefficienies:
  m_AverageClusteringCoefficientsC = std::accumulate(m_VectorOfClusteringCoefficientsC.begin(),
    m_VectorOfClusteringCoefficientsC.end(),
    0.0) / m_NumberOfVertices;

  m_AverageClusteringCoefficientsD = std::accumulate(m_VectorOfClusteringCoefficientsD.begin(),
    m_VectorOfClusteringCoefficientsD.end(),
    0.0) / m_NumberOfVertices;

  m_AverageClusteringCoefficientsE = std::accumulate(m_VectorOfClusteringCoefficientsE.begin(),
    m_VectorOfClusteringCoefficientsE.end(),
    0.0) / m_VectorOfClusteringCoefficientsE.size();
}
Exemple #16
0
    void PhyEngine::buildEngineGraph(RadioGraph& graph)
    {
        //Create the components
        VertexIterator i, iend;
        for(b::tie(i,iend) = vertices(graph); i != iend; ++i)
        {
            //Load the component and add to vector
            ComponentDescription current = graph[*i];
            b::shared_ptr<PhyComponent> comp = compManager_->loadComponent(current);
            comp->setEngine(this);    //Provide an interface to the component
            components_.push_back(comp);
        }

        //Do a topological sort of the graph
        deque<unsigned> topoOrder;
        topological_sort(graph, front_inserter(topoOrder), b::vertex_index_map(b::identity_property_map()));

        //Set up some containers
        vector< ReadBufferBase* > currentInBufs;
        vector< WriteBufferBase* > currentOutBufs;
        map<string, int> inputTypes, outputTypes;

        //The external input buffers feed the source component of the graph
        for( vector< b::shared_ptr< DataBufferBase > >::iterator i = engInputBuffers_.begin(); i != engInputBuffers_.end(); ++i)
        {
            DataBufferBase* buf = (*i).get();
            LinkDescription desc = buf->getLinkDescription();
            inputTypes[desc.sinkPort] = buf->getTypeIdentifier();
            currentInBufs.push_back(dynamic_cast<ReadBufferBase*>(buf));
        }

        //Set buffers on the components
        for(deque<unsigned>::iterator i = topoOrder.begin(); i != topoOrder.end(); ++i)
        {
            //Get the internal input buffer details
            InEdgeIterator edgeIt, edgeItEnd;
            for(b::tie(edgeIt, edgeItEnd) = in_edges(*i, graph); edgeIt != edgeItEnd; ++edgeIt)
            {
                inputTypes[graph[*edgeIt].sinkPort] =  graph[*edgeIt].theBuffer->getTypeIdentifier();
                currentInBufs.push_back(dynamic_cast<ReadBufferBase*>(graph[*edgeIt].theBuffer.get()));
            }

            //TODO: Check that the input port names from the xml match existing input ports
            //TODO: Check that inputs exist for each of the registered input port names

            //Get output buffer types from component
            components_[*i]->calculateOutputTypes(inputTypes, outputTypes);

            // temporary shell for testing template components
            std::vector<int> inTypes, outTypes;
            for (std::map<std::string, int>::iterator j = inputTypes.begin(); j != inputTypes.end(); ++j)
            {
                inTypes.push_back(j->second);
            }
            for (std::map<std::string, int>::iterator j = outputTypes.begin(); j != outputTypes.end(); ++j)
            {
                outTypes.push_back(j->second);
            }

            PhyComponent* x = components_[*i]->setupIO(inTypes, outTypes);
            if (x != components_[*i].get())
            {
                components_[*i].reset(x);
            }

            //Create internal output buffers and add to graph edges
            OutEdgeIterator outEdgeIt, outEdgeItEnd;
            for(b::tie(outEdgeIt, outEdgeItEnd) = out_edges(*i, graph); outEdgeIt != outEdgeItEnd; ++outEdgeIt)
            {
                //Check that the port name exists
                string srcPort = graph[*outEdgeIt].sourcePort;
                if(outputTypes.find(srcPort) == outputTypes.end())
                {
                    throw ResourceNotFoundException("Output port " + srcPort + \
                        " could not be found on PhyComponent " + components_[*i]->getName());
                }

                //Create a PhyDataBuffer of the correct type
                int currentType = outputTypes[srcPort];
                b::shared_ptr< DataBufferBase > buf = createPhyDataBuffer(currentType);
                graph[*outEdgeIt].theBuffer = buf;
                graph[*outEdgeIt].theBuffer->setLinkDescription(graph[*outEdgeIt]);
                internalBuffers_.push_back( buf );

                currentOutBufs.push_back( dynamic_cast<WriteBufferBase*>( buf.get() ) );

                //Remove from the outputTypes map
                outputTypes.erase( outputTypes.find( srcPort ) );
            }

            //Anything left in the outputTypes map must be an external output buffer
            for( map<string, int>::iterator j = outputTypes.begin(); j != outputTypes.end(); ++j)
            {
                //Create a DataBuffer and add to exOutputBuffers
                b::shared_ptr< DataBufferBase > buf = createDataBuffer( j->second );
                LinkDescription l;
                l.sourceEngine = engineName_;
                l.sourceComponent = components_[*i]->getName();
                l.sourcePort = j->first;
                buf->setLinkDescription(l);
                engOutputBuffers_.push_back(buf);
                currentOutBufs.push_back( dynamic_cast<WriteBufferBase*>( buf.get() ) );
            }

            //Set the buffers in the component
            components_[*i]->setBuffers(currentInBufs, currentOutBufs);

            //Initialize the component
            components_[*i]->initialize();

            currentInBufs.clear();
            currentOutBufs.clear();
        }

    }
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;

}
  typename graph_traits < VertexListGraph >::degree_size_type
  edge_connectivity(VertexListGraph & g, OutputIterator disconnecting_set)
  {
    typedef typename graph_traits <
      VertexListGraph >::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits <
      VertexListGraph >::degree_size_type degree_size_type;
    typedef color_traits < default_color_type > Color;
    typedef typename adjacency_list_traits < vecS, vecS,
      directedS >::edge_descriptor edge_descriptor;
    typedef adjacency_list < vecS, vecS, directedS, no_property,
      property < edge_capacity_t, degree_size_type,
      property < edge_residual_capacity_t, degree_size_type,
      property < edge_reverse_t, edge_descriptor > > > > FlowGraph;

    vertex_descriptor u, v, p, k;
    edge_descriptor e1, e2;
    bool inserted;
    typename graph_traits < VertexListGraph >::vertex_iterator vi, vi_end;
    degree_size_type delta, alpha_star, alpha_S_k;
    std::set < vertex_descriptor > S, neighbor_S;
    std::vector < vertex_descriptor > S_star, nonneighbor_S;
    std::vector < default_color_type > color(num_vertices(g));
    std::vector < edge_descriptor > pred(num_vertices(g));

    FlowGraph flow_g(num_vertices(g));
    typename property_map < FlowGraph, edge_capacity_t >::type
      cap = get(edge_capacity, flow_g);
    typename property_map < FlowGraph, edge_residual_capacity_t >::type
      res_cap = get(edge_residual_capacity, flow_g);
    typename property_map < FlowGraph, edge_reverse_t >::type
      rev_edge = get(edge_reverse, flow_g);

    typename graph_traits < VertexListGraph >::edge_iterator ei, ei_end;
    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
      u = source(*ei, g), v = target(*ei, g);
      boost::tie(e1, inserted) = add_edge(u, v, flow_g);
      cap[e1] = 1;
      boost::tie(e2, inserted) = add_edge(v, u, flow_g);
      cap[e2] = 1;
      rev_edge[e1] = e2;
      rev_edge[e2] = e1;
    }

    boost::tie(p, delta) = min_degree_vertex(g);
    S_star.push_back(p);
    alpha_star = delta;
    S.insert(p);
    neighbor_S.insert(p);
    neighbors(g, S.begin(), S.end(),
              std::inserter(neighbor_S, neighbor_S.begin()));
    std::set_difference(vertices(g).first, vertices(g).second,
                        neighbor_S.begin(), neighbor_S.end(),
                        std::back_inserter(nonneighbor_S));

    while (!nonneighbor_S.empty()) {
      k = nonneighbor_S.front();
      alpha_S_k = edmonds_karp_max_flow
        (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]);
      if (alpha_S_k < alpha_star) {
        alpha_star = alpha_S_k;
        S_star.clear();
        for (boost::tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi)
          if (color[*vi] != Color::white())
            S_star.push_back(*vi);
      }
      S.insert(k);
      neighbor_S.insert(k);
      neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin()));
      nonneighbor_S.clear();
      std::set_difference(vertices(g).first, vertices(g).second,
                          neighbor_S.begin(), neighbor_S.end(),
                          std::back_inserter(nonneighbor_S));
    }

    std::vector < bool > in_S_star(num_vertices(g), false);
    typename std::vector < vertex_descriptor >::iterator si;
    for (si = S_star.begin(); si != S_star.end(); ++si)
      in_S_star[*si] = true;
    degree_size_type c = 0;
    for (si = S_star.begin(); si != S_star.end(); ++si) {
      typename graph_traits < VertexListGraph >::out_edge_iterator ei, ei_end;
      for (boost::tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei)
        if (!in_S_star[target(*ei, g)]) {
          *disconnecting_set++ = *ei;
          ++c;
        }
    }

    return c;
  }
Exemple #19
0
int main() {
    GraphTraits::out_edge_iterator out_i, out_end;
    GraphTraits::edge_descriptor e;
    boost::graph_traits<Graph>::adjacency_iterator ai;
    boost::graph_traits<Graph>::adjacency_iterator ai_end;
    boost::minstd_rand gen;

    std::map<uint64_t, uint32_t> m;
    std::map<int_type, int_type> id_map;

    size_t count = 0;

    uint64_t *v_array = (uint64_t *)malloc(sizeof(uint64_t)*(n_count + n_count*3));
    // Create graph with 100 nodes and edges with probability 0.05
    double prob = n_count*n_count;
    prob = n_count*3/prob;
    Graph g(ERGen(gen, n_count, prob), ERGen(), n_count);

    std::cout << "done generating\n\n";

    IndexMap index = get(boost::vertex_index, g);
    cow_trie_p my_map = cow_trie_alloc(0, 0);
    my_map->ref_count = 1;
    my_map->child_bitmap = 0;
    my_map->value_bitmap = 0;
    uint32_t id = 0;

    std::cout << "beginning vertex iteration\n\n";
    std::pair<vertex_iter, vertex_iter> vp;
    for (vp = vertices(g); vp.first != vp.second; ++vp.first) {
        Vertex v = *vp.first;
        boost::tie(out_i, out_end) = out_edges(v, g);
        uint32_t deg = out_degree(v, g);
        uint32_t *succs = new uint32_t[deg];
        val_t my_val = cow_trie_create_val(0, deg, succs, 0, 0);
        int_type my_id = cow_trie_insert(my_map, my_val, &my_map);
        id_map[id] = my_id;
        ++id;
    }

    std::cout << "vertex iteration done, beginning edge iteration\n\n";
    boost::graph_traits<Graph>::edge_iterator ei, ei_end;
    boost::tie(ei, ei_end) = edges(g);
    std::cout << "id before is" << id << "\n\n"; 
    for (ei; ei != ei_end; ++ei) {
        val_t my_val = cow_trie_create_val(1, 0, 0, id_map[index[source(*ei, g)]], id_map[index[target(*ei, g)]]);
        int_type my_id = cow_trie_insert(my_map, my_val, &my_map);
        m[index[source(*ei, g)] << 32 | index[target(*ei, g)]] = id;
        ++id;
    }
    std::cout << "id is\n\n" << id << "\n\n";
    std::cout << "done edge iterating\n\n";
    std::cout << "putting in successors\n\n";
    int p = 0;
    for (vp = vertices(g); vp.first != vp.second; ++vp.first) {
        Vertex v = *vp.first;
        val_t my_val;
        cow_trie_lookup(my_map, p, &my_val);
        uint32_t *succs = edge_list_values(my_val._.node.succs);
        boost::tie(out_i, out_end) = out_edges(v, g);
        int eindex = 0;
        for (out_i; out_i != out_end; ++out_i) {
            e = *out_i;
            Vertex src = source(e, g), targ = target(e, g);
            uint32_t id = m[index[src] << 32 | index[targ]];
            succs[eindex] = id_map[id];
            ++eindex;
        }
    ++p;
    }
    val_t v;
    cow_trie_lookup(my_map, 0, &v);
    Vertex vtest = *vertices(g).first;
    std::cout << "beginning random traversal\n\n";
    float t1 = random_walk(vtest, index, g);
    printf("time for theirs %f", t1);
    float t2 = random_walk_c(v, my_map);
    printf("time for ours %f", t2);
    std::cout << "end random traversal\n\n";
}
    std::vector<Solution> HeuristicsSolver::solve_fast_forward() const {
        auto sols = std::vector<Solution>();
        auto h1 = g->get_source_vertex().second;
        auto h2 = g->get_sink_vertex().second;
        struct EdgeWithCost {
            Edge e;
            double c;
            double rc;
        };

        for(auto i = 0; i < prob->params.greedy_reruns; i++) {
            auto current = h1;
            auto path = Path();
            auto tot_c = 0.0f, tot_rc = 0.0f;
            auto done = false;

            while(current != h2) {
                std::vector<EdgeWithCost> out_e;

                for(auto ep = out_edges(current, g->graph); ep.first != ep.second; ++ep.first) {
                    if(erased.find(current) != erased.end() &&
                       erased.at(current).find(*ep.first) != erased.at(current).end()) { continue; }

                    auto n_dest = *g->graph[target(*ep.first, g->graph)];

                    auto dual = g->dual_of(n_dest);
                    EdgeWithCost ewc = {*ep.first, g->graph[*ep.first]->cost, g->graph[*ep.first]->cost - dual};

                    auto closes_cycle = false;
                    for(const auto &e : path) {
                        if(n_dest.n_type == NodeType::REGULAR_PORT &&
                           n_dest.port == g->graph[source(e, g->graph)]->port) {
                            closes_cycle = true;
                            break;
                        }
                    }

                    if(!closes_cycle) {
                        out_e.push_back(ewc);
                    }
                }

                if(out_e.size() == 0) {
                    break;
                }

                std::sort(out_e.begin(), out_e.end(),
                          [this](const auto &ewc1, const auto &ewc2) {
                              return (ewc1.rc > ewc2.rc);
                          });

                auto rnd_idx = (int) (rand() % (std::min(prob->params.greedy_max_outarcs, (int) out_e.size())));
                auto chosen = out_e[rnd_idx];

                path.insert(path.begin(), chosen.e);
                tot_c += chosen.c;
                tot_rc += chosen.rc;

                current = target(chosen.e, g->graph);

                if(current == h2) {
                    done = true;
                }
            }

            if(done) {
                sols.push_back(Solution(path, tot_c, tot_rc, g->vessel_class, g));
            }
        }

        return sols;
    }
Exemple #21
0
        typename property_traits<CoreMap>::value_type
        core_numbers_impl(Graph& g, CoreMap c, PositionMap pos, Visitor vis)
        {
            typedef typename graph_traits<Graph>::vertices_size_type size_type;
            typedef typename graph_traits<Graph>::degree_size_type degree_type;
            typedef typename graph_traits<Graph>::vertex_descriptor vertex;
            typename graph_traits<Graph>::vertex_iterator vi,vi_end;

            // store the vertex core numbers
            typename property_traits<CoreMap>::value_type v_cn = 0;

            // compute the maximum degree (degrees are in the coremap)
            typename graph_traits<Graph>::degree_size_type max_deg = 0;
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                max_deg = (std::max<typename graph_traits<Graph>::degree_size_type>)(max_deg, get(c,*vi));
            }

            // store the vertices in bins by their degree
            // allocate two extra locations to ease boundary cases
            std::vector<size_type> bin(max_deg+2);
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                ++bin[get(c,*vi)];
            }

            // this loop sets bin[d] to the starting position of vertices
            // with degree d in the vert array for the bucket sort
            size_type cur_pos = 0;
            for (degree_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg) {
                degree_type tmp = bin[cur_deg];
                bin[cur_deg] = cur_pos;
                cur_pos += tmp;
            }

            // perform the bucket sort with pos and vert so that
            // pos[0] is the vertex of smallest degree
            std::vector<vertex> vert(num_vertices(g));
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                vertex v=*vi;
                size_type p=bin[get(c,v)];
                put(pos,v,p);
                vert[p]=v;
                ++bin[get(c,v)];
            }
            // we ``abused'' bin while placing the vertices, now,
            // we need to restore it
            std::copy(boost::make_reverse_iterator(bin.end()-2),
                boost::make_reverse_iterator(bin.begin()),
                boost::make_reverse_iterator(bin.end()-1));
            // now simulate removing the vertices
            for (size_type i=0; i < num_vertices(g); ++i) {
                vertex v = vert[i];
                vis.examine_vertex(v,g);
                v_cn = get(c,v);
                typename graph_traits<Graph>::out_edge_iterator oi,oi_end;
                for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) {
                    vis.examine_edge(*oi,g);
                    vertex u = target(*oi,g);
                    // if c[u] > c[v], then u is still in the graph,
                    if (get(c,u) > v_cn) {
                        degree_type deg_u = get(c,u);
                        degree_type pos_u = get(pos,u);
                        // w is the first vertex with the same degree as u
                        // (this is the resort operation!)
                        degree_type pos_w = bin[deg_u];
                        vertex w = vert[pos_w];
                        if (u!=v) {
                            // swap u and w
                            put(pos,u,pos_w);
                            put(pos,w,pos_u);
                            vert[pos_w] = u;
                            vert[pos_u] = w;
                        }
                        // now, the vertices array is sorted assuming
                        // we perform the following step
                        // start the set of vertices with degree of u
                        // one into the future (this now points at vertex
                        // w which we swapped with u).
                        ++bin[deg_u];
                        // we are removing v from the graph, so u's degree
                        // decreases
                        put(c,u,get(c,u)-1);
                    }
                }
                vis.finish_vertex(v,g);
            }
            return v_cn;
        }
bool CreateIdiomaticAlternative::operator()(Automaton::RecognizerMatch& result,
                                            AnalysisContent& analysis) const
{
#ifdef DEBUG_LP
    MORPHOLOGINIT;
    LDEBUG << "CreateIdiomaticAlternative, match is " << result;
    LDEBUG << "    expression is " << (result.isContiguous()?"":"non") <<
     " contiguous and" << (result.isContextual()?" non":"") << " absolute";
#endif
  if (result.empty()) return false;
  const LinguisticAnalysisStructure::AnalysisGraph& graph = *(result.getGraph());
  AnnotationData* annotationData = static_cast< AnnotationData* >(analysis.getData("AnnotationData"));
  if (annotationData->dumpFunction("IdiomExpr") == 0)
  {
    annotationData->dumpFunction("IdiomExpr", new DumpIdiomaticExpressionAnnotation());
  }
  
  RecognizerData* recoData=static_cast<RecognizerData*>(analysis.getData("RecognizerData"));
  
  std::set<LinguisticGraphVertex> addedVertices;
  // initialize the vertices to clear

  if (result.isContiguous())
  {
//     MORPHOLOGINIT;
//      LDEBUG << "contiguous idiomatic expression found: "
//          << result.concatString();

    // only one part : terms in expression are adjacent -> easy part

    // check if there is an overlap first
    if (recoData->matchOnRemovedVertices(result))
    {
      // ignore current idiomatic expression, continue
      MORPHOLOGINIT;
      LWARN << "idiomatic expression ignored: " << Common::Misc::limastring2utf8stdstring(result.concatString())
          << ": overlapping with a previous one";
      return false;
    }

    // create the new token
    std::pair<Token*,MorphoSyntacticData*> newToken = createAlternativeToken(result);
    if (newToken.second->empty())
    {
      // ignore current idiomatic expression, continue
      MORPHOLOGINIT;
      LERROR << "CreateIdiomaticAlternative::operator() Got empty morphosyntactic data. Abort";
      delete newToken.first;
      delete newToken.second;
      return false;
    }

    // add the vertex
    LinguisticGraphVertex idiomaticVertex =
        addAlternativeVertex(newToken.first, newToken.second, const_cast<LinguisticGraph*>(graph.getGraph()));
    AnnotationGraphVertex agv =  annotationData->createAnnotationVertex();
    annotationData->addMatching("AnalysisGraph", idiomaticVertex, "annot", agv);
    annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("AnalysisGraph"), idiomaticVertex);
    IdiomaticExpressionAnnotation annot(result);
    GenericAnnotation ga(annot);
    annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("IdiomExpr"), ga);

    addedVertices.insert(idiomaticVertex);

    //create the alternative with this only vertex
    createBeginAlternative(result.front().getVertex(),
                            idiomaticVertex,const_cast<LinguisticGraph&>(*graph.getGraph()));
    attachEndOfAlternative(idiomaticVertex,
                            result.back().getVertex(),const_cast<LinguisticGraph&>(*graph.getGraph()));

    // if expression is not contextual, only keep alternative
    if (! result.isContextual())
    {
      recoData->storeVerticesToRemove(result,const_cast<LinguisticGraph*>(graph.getGraph()));
      removeEdges(const_cast<LinguisticGraph&>(*graph.getGraph()),
                 result, analysis);
      //recoData->setNextVertex(idiomaticVertex);
      // if match was on single token, use next vertices (to avoid loops)
      if (result.size() > 1) 
      {
        recoData->setNextVertex(idiomaticVertex);
      }
      else 
      {
        LinguisticGraphOutEdgeIt outItr,outItrEnd;
        boost::tie(outItr,outItrEnd) = out_edges(idiomaticVertex,*(graph.getGraph()));
        for (;outItr!=outItrEnd;outItr++) 
        {
          recoData->setNextVertex(target(*outItr, *(graph.getGraph())));
        }
      }
    }
  }
  else
  {
    // several parts : tough case
//     MORPHOLOGINIT;
//      LDEBUG << "non contiguous idiomatic expression found: "
//          << result.concatString();

    // check if there is an overlap first
    if (recoData->matchOnRemovedVertices(result))
    {
      // ignore current idiomatic expression, continue
      MORPHOLOGINIT;
      LWARN << "idiomatic expression ignored: " << Common::Misc::limastring2utf8stdstring(result.concatString())
          << ": overlapping with a previous one";
      return false;
    }

    // create the new token
    pair<Token*,MorphoSyntacticData*> newToken = createAlternativeToken(result);
    if (newToken.second->empty())
    {
      // ignore current idiomatic expression, continue
      MORPHOLOGINIT;
      LERROR << "CreateIdiomaticAlternative::operator() Got empty morphosyntactic data. Abort";
      delete newToken.first;
      delete newToken.second;
      return false;
    }

    // add the vertex
    LinguisticGraphVertex idiomaticVertex =
        addAlternativeVertex(newToken.first,newToken.second,const_cast<LinguisticGraph*>(graph.getGraph()));
    addedVertices.insert(idiomaticVertex);
    AnnotationGraphVertex agv =  annotationData->createAnnotationVertex();
    annotationData->addMatching("AnalysisGraph", idiomaticVertex, "annot", agv);
    annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("AnalysisGraph"), idiomaticVertex);
    IdiomaticExpressionAnnotation annot(result);
    GenericAnnotation ga(annot);
    annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("IdiomExpr"), ga);

    //create the alternative with this vertex and duplicate of other vertices
    deque<LinguisticGraphVertex> idiomAlternative;
    LinguisticGraphVertex headVertex=result.getHead();
#ifdef DEBUG_LP
   LDEBUG << "headVertex = " << headVertex;
    if (headVertex!=0) 
    {
      LDEBUG << "=> " << Common::Misc::limastring2utf8stdstring(get(vertex_token,*graph.getGraph(),headVertex)->stringForm());
    }
#endif
    bool foundHead=false;
    bool keeping = false;
    std::pair< LinguisticGraphVertex, LinguisticGraphVertex > idiomPartBounds;
    std::set< std::pair< LinguisticGraphVertex, LinguisticGraphVertex > > edgesToRemove;
    RecognizerMatch::const_iterator matchItr=result.begin();
    for (; matchItr!=result.end(); matchItr++)
    {
      if (!matchItr->isKept())
      {
        if (keeping)
        {
          RecognizerMatch::const_iterator prevItr = matchItr - 1;
          idiomPartBounds.second = prevItr->getVertex();
          keeping = false;
#ifdef DEBUG_LP
          LDEBUG << "adding " << idiomPartBounds.first << " -> " << idiomPartBounds.second << " in edgesToRemove";
#endif
          edgesToRemove.insert(idiomPartBounds);
        }
        // duplicate this vertex
#ifdef DEBUG_LP
        LDEBUG << "duplication of vertex " << matchItr->getVertex();;
#endif
        Token* token=get(vertex_token,*graph.getGraph(),matchItr->getVertex());
        MorphoSyntacticData* data = 
          new MorphoSyntacticData(*get(vertex_data,*graph.getGraph(),matchItr->getVertex()));
        LinguisticGraphVertex dupVx = add_vertex(const_cast<LinguisticGraph&>(*graph.getGraph()));
        put(vertex_token,const_cast<LinguisticGraph&>(*graph.getGraph()),dupVx,token);
        put(vertex_data,const_cast<LinguisticGraph&>(*graph.getGraph()),dupVx,data);
        idiomAlternative.push_back(dupVx);
        AnnotationGraphVertex agv =  annotationData->createAnnotationVertex();
        annotationData->addMatching("AnalysisGraph", dupVx, "annot", agv);
        annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("AnalysisGraph"), dupVx);
        std::set< LinguisticGraphVertex > annotMatches = 
          annotationData->matches("AnalysisGraph",matchItr->getVertex(),"annot");
        for (std::set< LinguisticGraphVertex >::const_iterator annotIt(annotMatches.begin());
              annotIt != annotMatches.end(); annotIt++)
        {
          std::set< std::string > excepted;
          excepted.insert("AnalysisGraph");
          annotationData->cloneAnnotations(*annotIt, agv, excepted);
        }
        addedVertices.insert(dupVx);
//         verticesToRemove.insert(matchItr->getVertex());
      }
      else
      {
        if (!keeping)
        {
          idiomPartBounds.first = matchItr->getVertex();
          keeping = true;
        }
#ifdef DEBUG_LP
         LDEBUG << "kept vertex " << matchItr->getVertex();
#endif
        if (matchItr->getVertex()==headVertex)
        {
          foundHead=true;
#ifdef DEBUG_LP
           LDEBUG << "add head vertex " << idiomaticVertex;
#endif
          idiomAlternative.push_back(idiomaticVertex);
        }
      }
    }
    if (!foundHead) 
    {
      MORPHOLOGINIT;
      LWARN << "head token has not been found in non contiguous expression. "
          << "Idiomatic token is placed first";
      idiomAlternative.push_front(idiomaticVertex);
    }
    if (keeping)
    {
      RecognizerMatch::const_iterator prevItr = matchItr - 1;
      idiomPartBounds.second = prevItr->getVertex();
      keeping = false;
#ifdef DEBUG_LP
      LDEBUG << "adding " << idiomPartBounds.first << " -> " << idiomPartBounds.second << " in edgesToRemove";
#endif
      edgesToRemove.insert(idiomPartBounds);
    }

    // link alternatives
#ifdef DEBUG_LP
     LDEBUG << "idiomAlternative has " << idiomAlternative.size() << " vertex";
#endif
    createBeginAlternative(result.front().getVertex(),
                            idiomAlternative.front(),const_cast<LinguisticGraph&>(*graph.getGraph()));
    {
      deque<LinguisticGraphVertex>::const_iterator idItr=idiomAlternative.begin();
      LinguisticGraphVertex lastIdiomVx=*idItr;
      idItr++;
      while (idItr!=idiomAlternative.end())
      {
        LinguisticGraphEdge newEdge;
        bool ok;
        boost::tie(newEdge, ok) = add_edge(lastIdiomVx,*idItr,const_cast<LinguisticGraph&>(*graph.getGraph()));
#ifdef DEBUG_LP
         LDEBUG << "added new edge in alternatives linking: " << newEdge.m_source << " -> " << newEdge.m_target;
#endif
        lastIdiomVx=*idItr;
        idItr++;
      }
    }
    attachEndOfAlternative(idiomAlternative.back(),
                            result.back().getVertex(),const_cast<LinguisticGraph&>(*graph.getGraph()));

    // if expression is not contextual, only keep alternative
    if (! result.isContextual())
    {
#ifdef DEBUG_LP
      LDEBUG << "expression is not contextual, only keep alternative";
#endif
      std::set< std::pair< LinguisticGraphVertex, LinguisticGraphVertex > >::const_iterator edgesToRemoveIt, edgesToRemoveIt_end;
      edgesToRemoveIt = edgesToRemove.begin(); edgesToRemoveIt_end = edgesToRemove.end();
      for (; edgesToRemoveIt != edgesToRemoveIt_end; edgesToRemoveIt++)
      {
#ifdef DEBUG_LP
         LDEBUG << "Removing edge " << (*edgesToRemoveIt).first << " -> " << (*edgesToRemoveIt).second;
#endif
        removeEdges(const_cast<LinguisticGraph&>(*graph.getGraph()),
                   result, analysis);
      }

//       recoData->storeVerticesToRemove(result,*graph);
      // no need to check size: if several parts, more than one vertex
      recoData->setNextVertex(idiomaticVertex);
      
    }
  }
  RecognizerMatch::const_iterator matchItr=result.begin();
  for (; matchItr!=result.end(); matchItr++)
  {
    recoData->clearUnreachableVertices( analysis, (*matchItr).getVertex());
  }
//   recoData->clearUnreachableVertices( analysis, result.front().getVertex(), result.back().getVertex(), storedEdges);
  return true;
}
	friend std::pair<out_edge_iterator, out_edge_iterator> out_edges(vertex_descriptor v, const Self &g) {
		return out_edges(v, g.g);
	}
Exemple #24
0
LimaStatusCode GreedyPosTagger::process(
  AnalysisContent& analysis) const
{

  // start postagging here !
  TimeUtils::updateCurrentTime();
  PTLOGINIT;
  LINFO << "start greedy posTagging";

  AnalysisGraph* anagraph=static_cast<AnalysisGraph*>(analysis.getData("AnalysisGraph"));
  
  AnalysisGraph* posgraph=new AnalysisGraph("PosGraph",m_language,false,true,*anagraph);

  // walk on the vertex but don't process a vertex if one
  // of its predecessor hasn't been processed.
  LinguisticGraph* graph=posgraph->getGraph();
  LinguisticGraphVertex endVx=posgraph->lastVertex();

  map<LinguisticGraphVertex,uint64_t> processed;
  set<LinguisticGraphVertex> toProcess;
  toProcess.insert(anagraph->firstVertex());
  set<LinguisticGraphVertex> nextToProcess;
  set<LinguisticGraphVertex>::iterator toProcessItr;
  map<LinguisticGraphVertex,uint64_t>::iterator processedItr;
  LinguisticGraphInEdgeIt inItr,inItrEnd;
  LinguisticGraphOutEdgeIt outItr,outItrEnd;

  while (toProcess.size()!=0)
  {

    //cout << "toProcess is ";
    //        copy(toProcess.begin(),toProcess.end(),ostream_iterator<LinguisticGraphVertex>(cout,","));
    //        cout << endl;

    for (toProcessItr=toProcess.begin();
         toProcessItr!=toProcess.end();
         toProcessItr++)
    {

      // process vertex
      processVertex(*toProcessItr,anagraph);
      processed.insert(make_pair(*toProcessItr,out_degree(*toProcessItr,*graph)));
      //cerr << "processed : insert " << *toProcessItr << " with " << out_degree(*toProcessItr,*graph) << endl;

      // remove processed if necessary
      boost::tie(inItr,inItrEnd)=in_edges(*toProcessItr,*graph);
      for (;inItr!=inItrEnd;inItr++)
      {
        processedItr=processed.find(source(*inItr,*graph));
        processedItr->second--;
        //cerr << "processed : vertex " << processedItr->first << " decremented to " << processedItr->second << endl;
        if (processedItr->second==0)
        {
          //cerr << "processed : remove " << processedItr->first << endl;
          processed.erase(processedItr);
        }
      }

      // check and add nex vertex to process
      boost::tie(outItr,outItrEnd)=out_edges(*toProcessItr,*graph);
      for (;outItr!=outItrEnd;outItr++)
      {
        LinguisticGraphVertex next=target(*outItr,*graph);
        if (next==endVx)
        {
          continue;
        }
        // check if all in vertices have been processed
        boost::tie(inItr,inItrEnd)=in_edges(next,*graph);
        bool ok=true;
        for (;inItr!=inItrEnd;inItr++)
        {
          if (processed.find(source(*inItr,*graph))==processed.end())
          {
            ok=false;
            break;
          }
        }
        if (ok)
        {
          nextToProcess.insert(next);
        }
      }

    }

    toProcess.clear();
    toProcess.swap(nextToProcess);

  }

  TimeUtils::logElapsedTime("GreedyPosTagger");
  return SUCCESS_ID;
}
LimaStatusCode ParagraphBoundariesFinder::process(
  AnalysisContent& analysis) const
{
  TimeUtils::updateCurrentTime();
  SENTBOUNDLOGINIT;
  LINFO << "start finding paragraph founds";
  
  // find paragraphs in text (positions of double carriage returns),
  // then find corresponding vertices in graph

  AnalysisGraph* graph=static_cast<AnalysisGraph*>(analysis.getData(m_graph));
  if (graph==0) {
    LERROR << "no graph '" << m_graph << "' available !";
    return MISSING_DATA;
  }
  SegmentationData* boundaries=new SegmentationData(m_graph);
  analysis.setData("ParagraphBoundaries",boundaries);

  LimaStringText* text=static_cast<LimaStringText*>(analysis.getData("Text"));
  
  std::vector<uint64_t> paragraphPositions;
  int currentPos=0;
  int i=text->indexOf(m_paragraphSeparator,currentPos);
  while (i!=-1) {
    paragraphPositions.push_back((uint64_t)i);
    // goto next char that is not a carriage return
    currentPos=text->indexOf(QRegExp(QString("[^")+ m_paragraphSeparator+"]"),i+1);
    i=text->indexOf(m_paragraphSeparator,currentPos);
  }

  if (paragraphPositions.empty()) {
    LWARN << "no paragraph found";
    return SUCCESS_ID;
  }

  // find vertices related to positions in graph
  uint64_t parNum=0;
  std::deque<LinguisticGraphVertex> toVisit;
  std::set<LinguisticGraphVertex> visited;

  LinguisticGraphVertex beginParagraph=graph->firstVertex();

  toVisit.push_back(graph->firstVertex());
  visited.insert(graph->firstVertex());

  while (!toVisit.empty())
  {
    LinguisticGraphVertex currentVertex=toVisit.front();
    toVisit.pop_front();

    if (currentVertex == graph->lastVertex()) { // end of the graph
      continue;  // may be other nodes to test in queue
    }

    if (currentVertex != graph->firstVertex()) {
      Token* t = get(vertex_token,*(graph->getGraph()),currentVertex);
      uint64_t position=t->position();
      if (position >= (paragraphPositions[parNum]+1)) {
        boundaries->add(Segment("paragraph",beginParagraph,currentVertex,graph));
        beginParagraph=currentVertex;
        parNum++;
        if (parNum >= paragraphPositions.size()) {
          break;
        }
      }
    }

    // store following nodes to test
    LinguisticGraphOutEdgeIt outEdge,outEdge_end;
    boost::tie(outEdge,outEdge_end)=out_edges(currentVertex,*(graph->getGraph()));

    for (; outEdge!=outEdge_end; outEdge++) {
      LinguisticGraphVertex next=target(*outEdge,*(graph->getGraph()));
      if (visited.find(next)==visited.end()) {
        toVisit.push_back(next);
        visited.insert(next);
      }
    }
  }
  
  TimeUtils::logElapsedTime("ParagraphBoundariesFinder");
  return SUCCESS_ID;
}
Exemple #26
0
  OutputIterator
  sloan_ordering(Graph& g,
                 typename graph_traits<Graph>::vertex_descriptor s,
                 typename graph_traits<Graph>::vertex_descriptor e,
                 OutputIterator permutation, 
                 ColorMap color, 
                 DegreeMap degree, 
                 PriorityMap priority, 
                 Weight W1, 
                 Weight W2)
  {
    //typedef typename property_traits<DegreeMap>::value_type Degree;
    typedef typename property_traits<PriorityMap>::value_type Degree;
    typedef typename property_traits<ColorMap>::value_type ColorValue;
    typedef color_traits<ColorValue> Color;
    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
    typedef typename std::vector<typename graph_traits<Graph>::vertices_size_type>::iterator vec_iter;
    typedef typename graph_traits<Graph>::vertices_size_type size_type;

    typedef typename property_map<Graph, vertex_index_t>::const_type VertexID;

    
    //Creating a std-vector for storing the distance from the end vertex in it
    typename std::vector<typename graph_traits<Graph>::vertices_size_type> dist(num_vertices(g), 0);
    
    //Wrap a property_map_iterator around the std::iterator
    boost::iterator_property_map<vec_iter, VertexID, size_type, size_type&> dist_pmap(dist.begin(), get(vertex_index, g)); 
    
    breadth_first_search
      (g, e, visitor
       (
           make_bfs_visitor(record_distances(dist_pmap, on_tree_edge() ) )
        )
       );
    
    //Creating a property_map for the indices of a vertex
    typename property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, g);
    
    //Sets the color and priority to their initial status
    unsigned cdeg;    
    typename graph_traits<Graph>::vertex_iterator ui, ui_end;
    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
    {
        put(color, *ui, Color::white());
        cdeg=get(degree, *ui)+1;
        put(priority, *ui, W1*dist[index_map[*ui]]-W2*cdeg );  
    }
    
    //Priority list
    typedef indirect_cmp<PriorityMap, std::greater<Degree> > Compare;
    Compare comp(priority);
    std::list<Vertex> priority_list;

    //Some more declarations
    typename graph_traits<Graph>::out_edge_iterator ei, ei_end, ei2, ei2_end;
    Vertex u, v, w;

    put(color, s, Color::green());      //Sets the color of the starting vertex to gray
    priority_list.push_front(s);                 //Puts s into the priority_list
    
    while ( !priority_list.empty() ) 
    {  
      priority_list.sort(comp);         //Orders the elements in the priority list in an ascending manner
      
      u = priority_list.front();           //Accesses the last element in the priority list
      priority_list.pop_front();               //Removes the last element in the priority list
      
      if(get(color, u) == Color::green() )
      {
        //for-loop over all out-edges of vertex u
        for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) 
        {
          v = target(*ei, g);
          
          put( priority, v, get(priority, v) + W2 ); //updates the priority
          
          if (get(color, v) == Color::white() )      //test if the vertex is inactive
          {
            put(color, v, Color::green() );        //giving the vertex a preactive status
            priority_list.push_front(v);                     //writing the vertex in the priority_queue
          }           
        }
      }
      
      //Here starts step 8
      *permutation++ = u;                      //Puts u to the first position in the permutation-vector
      put(color, u, Color::black() );          //Gives u an inactive status
      
      //for loop over all the adjacent vertices of u
      for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {
        
        v = target(*ei, g);     
        
        if (get(color, v) == Color::green() ) {      //tests if the vertex is inactive
          
          put(color, v, Color::red() );        //giving the vertex an active status
          put(priority, v, get(priority, v)+W2);  //updates the priority        
          
          //for loop over alll adjacent vertices of v
          for (tie(ei2, ei2_end) = out_edges(v, g); ei2 != ei2_end; ++ei2) {
            w = target(*ei2, g);
            
            if(get(color, w) != Color::black() ) {     //tests if vertex is postactive
              
              put(priority, w, get(priority, w)+W2);  //updates the priority
              
              if(get(color, w) == Color::white() ){
                
                put(color, w, Color::green() );   // gives the vertex a preactive status
                priority_list.push_front(w);           // puts the vertex into the priority queue
                
              } //end if
              
            } //end if
            
          } //end for
          
        } //end if
        
      } //end for
      
    } //end while
    
    
    return permutation;
  }  
Exemple #27
0
    void depth_first_visit_impl
      (const IncidenceGraph& g,
       typename graph_traits<IncidenceGraph>::vertex_descriptor u,
       DFSVisitor& vis,
       ColorMap color, TerminatorFunc func = TerminatorFunc())
    {
      BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<IncidenceGraph> ));
      BOOST_CONCEPT_ASSERT(( DFSVisitorConcept<DFSVisitor, IncidenceGraph> ));
      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;
      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ColorMap, Vertex> ));
      typedef typename property_traits<ColorMap>::value_type ColorValue;
      BOOST_CONCEPT_ASSERT(( ColorValueConcept<ColorValue> ));
      typedef color_traits<ColorValue> Color;
      typedef typename graph_traits<IncidenceGraph>::out_edge_iterator Iter;
      typedef std::pair<Vertex, std::pair<Iter, Iter> > VertexInfo;

      Iter ei, ei_end;
      std::vector<VertexInfo> stack;

      // Possible optimization for vector
      //stack.reserve(num_vertices(g));

      typedef typename unwrap_reference<TerminatorFunc>::type TF;

      put(color, u, Color::gray());
      vis.discover_vertex(u, g);
      boost::tie(ei, ei_end) = out_edges(u, g);
      // Variable is needed to workaround a borland bug.
      TF& fn = static_cast<TF&>(func);
      if (fn(u, g)) {
          // If this vertex terminates the search, we push empty range
          stack.push_back(std::make_pair(u, std::make_pair(ei_end, ei_end)));
      } else {
          stack.push_back(std::make_pair(u, std::make_pair(ei, ei_end)));
      }
      while (!stack.empty()) {
        VertexInfo& back = stack.back();
        u = back.first;
        boost::tie(ei, ei_end) = back.second;
        stack.pop_back();
        while (ei != ei_end) {
          Vertex v = target(*ei, g);
          vis.examine_edge(*ei, g);
          ColorValue v_color = get(color, v);
          if (v_color == Color::white()) {
            vis.tree_edge(*ei, g);
            stack.push_back(std::make_pair(u, std::make_pair(++ei, ei_end)));
            u = v;
            put(color, u, Color::gray());
            vis.discover_vertex(u, g);
            boost::tie(ei, ei_end) = out_edges(u, g);
            if (fn(u, g)) {
                ei = ei_end;
            }
          } else if (v_color == Color::gray()) {
            vis.back_edge(*ei, g);
            ++ei;
          } else {
            vis.forward_or_cross_edge(*ei, g);
            ++ei;
          }
        }
        put(color, u, Color::black());
        vis.finish_vertex(u, g);
      }
    }
 bool has_no_out_edges(const typename boost::graph_traits<Graph>::vertex_descriptor& v, const Graph& g) {
   typedef typename boost::graph_traits<Graph>::out_edge_iterator ei;
   std::pair<ei, ei> p = out_edges(v, g);
   return (p.first == p.second);
 }
    void depth_first_visit_impl
      (const IncidenceGraph& g,
       typename graph_traits<IncidenceGraph>::vertex_descriptor u,
       DFSVisitor& vis,
       ColorMap color, TerminatorFunc func = TerminatorFunc())
    {
      BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<IncidenceGraph> ));
      BOOST_CONCEPT_ASSERT(( DFSVisitorConcept<DFSVisitor, IncidenceGraph> ));
      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;
      typedef typename graph_traits<IncidenceGraph>::edge_descriptor Edge;
      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ColorMap, Vertex> ));
      typedef typename property_traits<ColorMap>::value_type ColorValue;
      BOOST_CONCEPT_ASSERT(( ColorValueConcept<ColorValue> ));
      typedef color_traits<ColorValue> Color;
      typedef typename graph_traits<IncidenceGraph>::out_edge_iterator Iter;
      typedef std::pair<Vertex, std::pair<boost::optional<Edge>, std::pair<Iter, Iter> > > VertexInfo;

      boost::optional<Edge> src_e;
      Iter ei, ei_end;
      std::vector<VertexInfo> stack;

      // Possible optimization for vector
      //stack.reserve(num_vertices(g));

      put(color, u, Color::gray());
      vis.discover_vertex(u, g);
      boost::tie(ei, ei_end) = out_edges(u, g);
      if (func(u, g)) {
          // If this vertex terminates the search, we push empty range
          stack.push_back(std::make_pair(u, std::make_pair(boost::optional<Edge>(), std::make_pair(ei_end, ei_end))));
      } else {
          stack.push_back(std::make_pair(u, std::make_pair(boost::optional<Edge>(), std::make_pair(ei, ei_end))));
      }
      while (!stack.empty()) {
        VertexInfo& back = stack.back();
        u = back.first;
        src_e = back.second.first;
        boost::tie(ei, ei_end) = back.second.second;
        stack.pop_back();
        while (ei != ei_end) {
          Vertex v = target(*ei, g);
          vis.examine_edge(*ei, g);
          ColorValue v_color = get(color, v);
          if (v_color == Color::white()) {
            vis.tree_edge(*ei, g);
            src_e = *ei;
            stack.push_back(std::make_pair(u, std::make_pair(src_e, std::make_pair(++ei, ei_end))));
            u = v;
            put(color, u, Color::gray());
            vis.discover_vertex(u, g);
            boost::tie(ei, ei_end) = out_edges(u, g);
            if (func(u, g)) {
                ei = ei_end;
            }
          } else {
            if (v_color == Color::gray()) {
              vis.back_edge(*ei, g);
            } else {
              vis.forward_or_cross_edge(*ei, g);
            }
            call_finish_edge(vis, *ei, g);
            ++ei;
          }
        }
        put(color, u, Color::black());
        vis.finish_vertex(u, g);
        if (src_e) call_finish_edge(vis, src_e.get(), g);
      }
    }
Exemple #30
0
int main() {

    Transport::GraphFactory gf("/vagrant/ubimob/graph.txt-dump", false);
    gf.setAll2();
    const Transport::Graph * gr = gf.get();

    string path="/vagrant/ubimob/analysis/output/projection/matching.csv";
    
    Users users=carpooling::SampleGraph::load(path);

    std::cout << "------------------ After ------------"<<std::endl;
    std::cout << "length drivers: " <<  users.drivers.size() <<std::endl;
    std::cout << "length pedestrians: " <<  users.passengers.size() <<std::endl;
    
    carpooling::vertex_descriptor s_heuristik,t_heuristik;
    carpooling::Graph g_heuristik;

    carpooling::vertex_descriptor s_ideal,t_ideal;
    carpooling::Graph g_ideal;

    //------------heuristic method

    std::cout<<"----------------- Geo distance heuristic ------------------"<<std::endl;

    carpooling::SampleGraph::heuristik_Graph(users,g_heuristik, s_heuristik, t_heuristik);
    boost::edmonds_karp_max_flow(g_heuristik, s_heuristik, t_heuristik);
    boost::cycle_canceling(g_heuristik);

    int cost_heuristik = boost::find_flow_cost(g_heuristik);
    std::cout<<"cost: "<< cost_heuristik <<std::endl;

    boost::graph_traits<carpooling::Graph>::vertex_iterator vi_heuristik, vend_heuristik;

    carpooling::Capacity capacity_heuristik = get(boost::edge_capacity, g_heuristik);
    carpooling::Weight weight_heuristik = get(boost::edge_weight, g_heuristik);
    carpooling::ResidualCapacity residual_capacity_heuristik = get(boost::edge_residual_capacity, g_heuristik);

    boost::graph_traits <  carpooling::Graph  >::vertex_iterator u_iter_heuristik, u_end_heuristik;
    boost::graph_traits <  carpooling::Graph  >::out_edge_iterator ei_heuristik, e_end_heuristik;

    int compt_heuristik=0;

    for (boost::tie(u_iter_heuristik, u_end_heuristik) = vertices(g_heuristik); u_iter_heuristik != u_end_heuristik; ++u_iter_heuristik){
        for (boost::tie(ei_heuristik, e_end_heuristik) = out_edges(*u_iter_heuristik, g_heuristik); ei_heuristik != e_end_heuristik; ++ei_heuristik){
            if ( (capacity_heuristik[*ei_heuristik]-residual_capacity_heuristik[*ei_heuristik] ) > 0 && weight_heuristik[*ei_heuristik] > 0 ){

                User _driver=carpooling::SampleGraph::findByPk_driver(*u_iter_heuristik-1,users);
                Privacy::Driver *d1=new Privacy::Driver(_driver.origin, _driver.destination);
                User _pedestrian= carpooling::SampleGraph::findByPk_passenger(target(*ei_heuristik, g_heuristik)-users.drivers.size()-1,users);
                Privacy::Pedestrian *p1=new Privacy::Pedestrian(_pedestrian.origin, _pedestrian.destination);
                int cost1;
                Privacy::cc_output cc;
                Privacy::Toolbox *tb=new Privacy::Toolbox();
                cc=tb->cc_carpooling_test(*d1,*p1,gr);
                cost1=cc.cc_costs.total_cost;

                std::cout << "node " << *u_iter_heuristik << " with node " << target(*ei_heuristik, g_heuristik) << " with cost: " << cost1 << std::endl;

                compt_heuristik ++;

                delete d1;
                delete p1;
                delete tb;
            }
        }
    }

    std::cout<<"----------------- Number of matching ------------------ : " << compt_heuristik <<std::endl;         

//-----------------ideal algorithm------------------

    std::cout<<"----------------- ideal algorithm ------------------"<<std::endl;
    

    carpooling::SampleGraph::ideal_Graph(users,g_ideal, s_ideal, t_ideal,gr);
    boost::edmonds_karp_max_flow(g_ideal, s_ideal, t_ideal);
    boost::cycle_canceling(g_ideal);

    int cost_ideal = boost::find_flow_cost(g_ideal);
    std::cout<<"cost: "<< cost_ideal <<std::endl;

    boost::graph_traits<carpooling::Graph>::vertex_iterator vi_ideal, vend_ideal;
    carpooling::Capacity capacity_ideal = get(boost::edge_capacity, g_ideal);
    carpooling::Weight weight_ideal = get(boost::edge_weight, g_ideal);
    carpooling::ResidualCapacity residual_capacity_ideal = get(boost::edge_residual_capacity, g_ideal);

    boost::graph_traits <  carpooling::Graph  >::vertex_iterator u_iter_ideal, u_end_ideal;
    boost::graph_traits <  carpooling::Graph  >::out_edge_iterator ei_ideal, e_end_ideal;

    int compt_ideal=0;

    for (boost::tie(u_iter_ideal, u_end_ideal) = vertices(g_ideal); u_iter_ideal != u_end_ideal; ++u_iter_ideal){
        for (boost::tie(ei_ideal, e_end_ideal) = out_edges(*u_iter_ideal, g_ideal); ei_ideal != e_end_ideal; ++ei_ideal){
            if ( (capacity_ideal[*ei_ideal]-residual_capacity_ideal[*ei_ideal] ) > 0 && weight_ideal[*ei_ideal] > 0 ){

                User _driver1=carpooling::SampleGraph::findByPk_driver(*u_iter_ideal-1,users);
                Privacy::Driver *d2=new Privacy::Driver(_driver1.origin, _driver1.destination);
                User _pedestrian1= carpooling::SampleGraph::findByPk_passenger(target(*ei_ideal, g_ideal)-users.drivers.size()-1,users);
                Privacy::Pedestrian *p2=new Privacy::Pedestrian(_pedestrian1.origin, _pedestrian1.destination);
                int cost2;
                Privacy::cc_output cc2;
                Privacy::Toolbox *tbb=new Privacy::Toolbox();
                cc2=tbb->cc_carpooling_test(*d2,*p2,gr);
                cost2=cc2.cc_costs.total_cost;
                std::cout << "node " << *u_iter_ideal << " with node " << target(*ei_ideal, g_ideal) << " with cost: " << cost2 << std::endl;

                compt_ideal ++;

                delete d2;
                delete p2;
                delete tbb;
            }
        }
    }
    std::cout<<"----------------- Number of matching ------------------ : " << compt_ideal <<std::endl; 





    return 0;
}