Пример #1
0
void WGraph::print(FILE* file, const Interface& I) const

/*
  Prints the graph on a file in ascii format.
*/

{
  const OrientedGraph& Y = *d_graph;

  int d = digits(size()-1,10);

  /* count number of edges */

  Ulong count = 0;

  for (Vertex x = 0; x < size(); ++x) {
    const EdgeList& e = Y.edge(x);
    count += e.size();
  }

  // find alignement

  String str(0);
  LFlags f = leqmask[I.rank()-1];
  interface::append(str,f,I);
  Ulong descent_maxwidth = str.length();

  fprintf(file,"%lu vertices, %lu edges\n\n",size(),count);

  for (Vertex x = 0; x < size(); ++x) {
    fprintf(file,"%*lu : ",d,x);
    io::reset(str);
    interface::append(str,descent(x),I);
    pad(str,descent_maxwidth );
    io::print(file,str);
    fprintf(file," ");
    const EdgeList e = Y.edge(x);
    const CoeffList c = coeffList(x);
    for (Ulong j = 0; j < e.size(); ++j) {
      fprintf(file,"%lu(%lu)",e[j],static_cast<Ulong>(c[j]));
      if (j+1 < e.size()) /* there is more to come */
	fprintf(file,",");
    }
    fprintf(file,"\n");
  }
}
Пример #2
0
void Reader::ProcessSymbol( int i, int j, RowType& v, EdgeList& m ) const
{
   if( '*' != mInput[i][j] )
      return;

   auto p = m.insert( EdgeList::value_type( std::make_pair( i+1, j ), m.size() ) );
   v.push_back(p.first->second);
}
Пример #3
0
void OrientedGraph::levelPartition(Partition& pi) const

/*
  Assuming the graph has no oriented cycles, this function writes in pi the 
  partition of the vertices according to their level, where sinks have level
  0, then sinks in the remaining poset have level one, etc.

  NOTE : the implementation is simple-minded : we traverse the graph as many
  times as there are levels.
*/

{
  static BitMap b(0);
  static BitMap b1(0);

  b.setSize(size());
  b.reset();
  b1.setSize(size());
  b1.reset();
  pi.setSize(size());
  Ulong count = 0;
  Ulong current_level = 0;

  while (count < size()) {
    for (SetElt x = 0; x < size(); ++x) {
      if (b.getBit(x))
	continue;
      const EdgeList e = d_edge[x];
      for (Ulong j = 0; j < e.size(); ++j) {
	if (!b.getBit(e[j])) /* next x */
	  goto nextx;
      }
      /* i we get here, x is the next element in the permutation */
      pi[x] = current_level;
      b1.setBit(x);
      ++count;
    nextx:
      continue;
    }
    b.assign(b1);
    current_level++;
  }

  pi.setClassCount(current_level);
  return;
}
Пример #4
0
  bool IsValidEdgeLoop(const EdgeList& edges)noexcept{
    //First, check there is no edge which have same start point.
    assert(4<=edges.size());
    EdgeList tmp(begin(edges), end(edges));
    auto cmp=[](const Edge& lhs, const Edge& rhs)->bool{
      const auto& lhsp = std::get<0>(lhs);
      const auto& rhsp = std::get<0>(rhs);
      if(real(lhsp) == real(rhsp)){
	return imag(lhsp) < imag(rhsp);
      }else{
	return real(lhsp) < real(rhsp);
      }
    };
    tmp.sort(cmp);
    for(auto prev=begin(tmp), it=std::next(prev); it!=end(tmp); ++prev, ++it){
      if(std::get<0>(*prev)==std::get<0>(*it)){
	return false;
      }
    }
    //Then check there is only one edge loop.
    const PentagonalPoint zero{0,0}, longer{1,0}, shorter{{-1,0,2,0},0};
    PentagonalPoint point{zero};
    Uint32 loop=0;
    for(const auto& edge : edges){
      if(std::get<2>(edge)){
	point+=Rotate(longer, std::get<1>(edge));
      }else{
	point+=Rotate(shorter, std::get<1>(edge));
      }
      if(point==zero){
	++loop;
      }
    }
    assert(0<loop);
    return (loop==1);
  }
Пример #5
0
void Graph::addEdges(const EdgeList& edges)
{
  for (size_t i = 0; i < edges.size(); ++i)
    addEdge(edges[i]);
}
Пример #6
0
inline
Polyhedron<ScalarParam>*
Polyhedron<ScalarParam>::clip(
	const typename Polyhedron<ScalarParam>::Plane& plane) const
	{
	typedef Misc::HashTable<Card,void> IndexSet;
	typedef Misc::HashTable<Card,Card> IndexMapper;
	
	/* Find the indices of all half edges that intersect the plane: */
	IndexMapper indexMapper(101);
	Card nextIndex=0;
	Card numIntersectedEdges=0;
	Card intersectedEdgeIndex=0;
	IndexSet ioEdges(17);
	Card numEdges=edges.size();
	for(Card i=0;i<numEdges;++i)
		{
		/* Get the plane distance of start and end points of edge i: */
		Scalar d0=plane.calcDistance(edges[i].start);
		Scalar d1=plane.calcDistance(edges[edges[i].next].start);
		
		/* Classify the edge: */
		if(d0<Scalar(0)&&d1<Scalar(0))
			{
			/* Keep the edge: */
			indexMapper.setEntry(typename IndexMapper::Entry(i,nextIndex));
			++nextIndex;
			}
		else if(d0<Scalar(0)||d1<Scalar(0))
			{
			/* Keep the edge: */
			indexMapper.setEntry(typename IndexMapper::Entry(i,nextIndex));
			++nextIndex;
			
			if(d0<Scalar(0))
				{
				/* Mark the edge as intersected: */
				++numIntersectedEdges;
				intersectedEdgeIndex=i;
				}
			else
				{
				/* Mark the edge as the opposite of an intersected edge: */
				ioEdges.setEntry(typename IndexSet::Entry(i));
				}
			}
		}
	
	/* Remember the number of retained edges: */
	Card newNumEdges=nextIndex;
	
	/* Check for trivial cases: */
	if(newNumEdges==0)
		return new Polyhedron; // Return an empty polyhedron
	else if(numIntersectedEdges==0)
		return new Polyhedron(*this); // Return an identical copy of the polyhedron
	
	/* Sort the list of intersected edges to form a loop: */
	IndexMapper newFaceEdges(17);
	EdgeList newFace;
	while(newFace.size()<numIntersectedEdges)
		{
		Edge newEdge;
		
		/* Calculate the new edge's starting point: */
		const Point& p0=edges[intersectedEdgeIndex].start;
		Scalar d0=plane.calcDistance(p0);
		const Point& p1=edges[edges[intersectedEdgeIndex].next].start;
		Scalar d1=plane.calcDistance(p1);
		newEdge.start=Geometry::affineCombination(p0,p1,(Scalar(0)-d0)/(d1-d0));
		
		/* Find the next intersected edge around the same face as the current last edge: */
		Card edgeIndex;
		for(edgeIndex=edges[intersectedEdgeIndex].next;!ioEdges.isEntry(edgeIndex);edgeIndex=edges[edgeIndex].next)
			;
		newEdge.next=indexMapper.getEntry(edgeIndex).getDest();
		newEdge.opposite=newNumEdges+numIntersectedEdges+newFace.size();
		
		/* Store the index of the new face edge: */
		newFaceEdges.setEntry(IndexMapper::Entry(intersectedEdgeIndex,newFace.size()));
		
		/* Store the new face edge: */
		newFace.push_back(newEdge);
		
		/* Go to the next intersected face: */
		intersectedEdgeIndex=edges[edgeIndex].opposite;
		}
	
	/* Create the result polyhedron: */
	Polyhedron* result=new Polyhedron;
	
	/* Create the edges of the result polyhedron: */
	for(Card i=0;i<numEdges;++i)
		{
		/* Get the plane distance of start and end points of edge i: */
		Scalar d0=plane.calcDistance(edges[i].start);
		Scalar d1=plane.calcDistance(edges[edges[i].next].start);
		
		/* Classify the edge: */
		if(d0<Scalar(0)&&d1<Scalar(0))
			{
			/*****************************************************************
			If an edge is completely inside, its opposite edge must be as
			well, and its next edge must at least be partially inside.
			Therefore, indexMapper will contain the new indices for both
			edges.
			*****************************************************************/
			
			/* Keep the edge: */
			result->edges.push_back(Edge(edges[i].start,indexMapper.getEntry(edges[i].next).getDest(),indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		else if(d0<Scalar(0))
			{
			/*****************************************************************
			If an edge's start point is inside, its opposite edge's index will
			be contained in indexMapper, and its next edge is a new face edge
			whose index can be calculated from newFaceEdges.
			*****************************************************************/
			
			/* Find the index of the next edge from the new face loop: */
			Card next=newNumEdges+newFaceEdges.getEntry(i).getDest();
			
			/* Retain the edge: */
			result->edges.push_back(Edge(edges[i].start,next,indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		else if(d1<Scalar(0))
			{
			/*****************************************************************
			If an edge's end point is inside, its start point must be
			calculated by clipping, and its next edge and opposite edge will
			both be contained in indexMapper.
			*****************************************************************/
			
			/* Calculate the new start point: */
			Point newStart=Geometry::affineCombination(edges[edges[i].next].start,edges[i].start,(Scalar(0)-d1)/(d0-d1));
			
			/* Retain the clipped edge: */
			result->edges.push_back(Edge(newStart,indexMapper.getEntry(edges[i].next).getDest(),indexMapper.getEntry(edges[i].opposite).getDest()));
			}
		}
	
	/* Add the closing edges for all clipped faces to the polyhedron: */
	for(typename EdgeList::const_iterator nfIt=newFace.begin();nfIt!=newFace.end();++nfIt)
		result->edges.push_back(*nfIt);
	
	/* Add the edges of the closing face to the polyhedron: */
	for(Card i=0;i<newFace.size();++i)
		{
		Edge newEdge;
		newEdge.start=newFace[(i+1)%newFace.size()].start;
		newEdge.next=newNumEdges+numIntersectedEdges+(i+newFace.size()-1)%newFace.size();
		newEdge.opposite=newNumEdges+i;
		result->edges.push_back(newEdge);
		}
	
	// DEBUGGING
	// result->check();
	
	return result;
	}
Пример #7
0
visualization_msgs::MarkerArray getVisualMsg (NodeList& pG, EdgeList& edgeList) 
{
	marker_array.markers.clear();
	msg_arrow.points.clear();
	msg_dots.points.clear();
	int id = 0;

	// start vertex_list - Dots for graph nodes
	msg_dots.id = id;
	msg_dots.ns = "nodes";
	msg_dots.scale.x = 1;
	msg_dots.scale.y = 1;
	msg_dots.scale.z = 1;
	msg_dots.color = red;
	for(unsigned int i=0; i < pG.size(); i++) {
		msg_point.x = pG[i].pose.pose.position.x;
		msg_point.y = pG[i].pose.pose.position.y;
		msg_point.z = pG[i].pose.pose.position.z;
		msg_dots.points.push_back(msg_point);
	}
	marker_array.markers.push_back(msg_dots);
	id++;

	// start vertex_list -arrows for graph edges

	for(unsigned int i=0; i < edgeList.size(); i++) {

		//grab the edge 
		Edge pE = edgeList[i];

		msg_arrow.id = id;
		msg_arrow.points.clear();
		msg_arrow.ns = "edges";
		msg_arrow.scale.x = 0.5;
		msg_arrow.scale.y = 1;
		msg_arrow.scale.z = 1;
		if(pE.from == 0)
			msg_arrow.color = white;
		else 
			msg_arrow.color = blue;
			


		//fill in the point
		msg_point.x = pG[pE.from].pose.pose.position.x;
		msg_point.y = pG[pE.from].pose.pose.position.y;
		msg_point.z = pG[pE.from].pose.pose.position.z;
		//ROS_INFO("start adding: %f, %f", msg_point.x,msg_point.y);
		msg_arrow.points.push_back(msg_point);
		msg_point.x = pG[ pE.to].pose.pose.position.x;
		msg_point.y = pG[ pE.to].pose.pose.position.y;
		msg_point.z = pG[ pE.to].pose.pose.position.z;
		//ROS_INFO("end adding: %f, %f", msg_point.x,msg_point.y);
		msg_arrow.points.push_back(msg_point);
		//we have filled in the arrow stuff, push it back to the marker array
		marker_array.markers.push_back(msg_arrow);
		id++;
	}


	return marker_array;

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

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

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

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

	// compute all pairs shortest paths in the spanning tree
//	computeShortestDistance(tree,treedist);
	
	EdgeList el;
	for (int i = 0; i < gsize; i++) {
		el = tree.out_edges(i);
		if (el.size()>0)
			sptree[i] = vector<int>(el.begin(),el.end());
//		sptree.push_back(vector<int>(el.begin(),el.end()));
//		sptree.insert(el.begin(),el.end());
	}
}
Пример #9
0
void TR()
{
#if defined(DEBUG) && defined(_MSC_VER)
    _CrtSetDbgFlag(0);	// too expensive
#endif

    const char *HitFileName = RequiredValueOpt("tr");
    const char *OutFileName = RequiredValueOpt("out");
    const char *CandFileName = ValueOpt("cand");

    const char *strMinTrSpacing = ValueOpt("mintrspacing");
    const char *strMaxTrSpacing = ValueOpt("maxtrspacing");
    const char *strMinTrLength = ValueOpt("mintrlength");
    const char *strMaxTrLength = ValueOpt("minspacingratio");
    const char *strMinFam = ValueOpt("minfam");
    const char *strMinHitRatio = ValueOpt("minhitratio");
    const char *strMinDistPairs = ValueOpt("mindistpairs");

    if (0 != strMinTrSpacing)
        MIN_LENGTH_LINE = atoi(strMinTrSpacing);
    if (0 != strMaxTrSpacing)
        MAX_LENGTH_LINE = atoi(strMaxTrSpacing);
    if (0 != strMinTrLength)
        MIN_LENGTH_LTR = atoi(strMinTrLength);
    if (0 != strMaxTrLength)
        MAX_LENGTH_LTR = atoi(strMaxTrLength);
    if (0 != strMinFam)
        MIN_FAM_SIZE = atoi(strMinFam);
    if (0 != strMinHitRatio)
        MIN_HIT_LENGTH_RATIO = atoi(strMinHitRatio);
    if (0 != strMinDistPairs)
        MIN_DIST_EDGE = atoi(strMinDistPairs);

    FILE *fHit = OpenStdioFile(HitFileName, FILEIO_MODE_ReadOnly);

    ProgressStart("Index hits");
    GLIX HitGlix;
    HitGlix.Init();
    HitGlix.FromGFFFile(fHit);
    HitGlix.MakeGlobalToLocalIndex();
    ProgressDone();

    const int GlobalLength = HitGlix.GetGlobalLength();
    IIX IntervalIndex;
    IntervalIndex.Init(GlobalLength);

    ProgressStart("Find candidate TRs");
    Rewind(fHit);
    GFFRecord Rec;
    while (GetNextGFFRecord(fHit, Rec))
    {
        HitData Hit;
        GFFRecordToHit(HitGlix, Rec, Hit);
        if (IsCandLTR(Hit))
            AddCand(Hit, IntervalIndex);
    }
    ProgressDone();

    Progress("%d candidates", CandCount);

    if (0 != CandFileName)
    {
        ProgressStart("Write candidates");
        FILE *fCand = OpenStdioFile(CandFileName, FILEIO_MODE_WriteOnly);
        WriteCands(fCand, HitGlix);
        ProgressDone();
    }

    ProgressStart("Make graph");
    Rewind(fHit);
    while (GetNextGFFRecord(fHit, Rec))
    {
        HitData Hit;
        GFFRecordToHit(HitGlix, Rec, Hit);
        FindEdges(Hit, HitGlix, IntervalIndex);
    }
    fclose(fHit);
    fHit = 0;

    ProgressDone();

    Progress("%d edges", (int) Edges.size());

    ProgressStart("Find families");
    FamList Fams;
    FindConnectedComponents(Edges, Fams, MIN_FAM_SIZE);
    ProgressDone();

    Progress("%d families", (int) Fams.size());

    FILE *fOut = OpenStdioFile(OutFileName, FILEIO_MODE_WriteOnly);
    WriteOutputFile(fOut, HitGlix, Fams);
}
Пример #10
0
void TRS()
	{
	const char *InputFileName = RequiredValueOpt("trs");

	const char *OutputFileName = ValueOpt("out");
	const char *PilesFileName = ValueOpt("piles");
	const char *ImagesFileName = ValueOpt("images");

	const char *strMinFamSize = ValueOpt("famsize");
	const char *strMaxLengthDiffPct = ValueOpt("maxlengthdiffpct");
	g_paramSingleHitCoverage = !FlagOpt("multihit");

	if (0 == OutputFileName && 0 == PilesFileName && 0 == ImagesFileName)
		Quit("No output file specified, must be at least one of -out, -piles, -images");

	if (0 != strMinFamSize)
		g_paramMinFamSize = atoi(strMinFamSize);
	if (0 != strMaxLengthDiffPct)
		g_paramMaxLengthDiffPct = atoi(strMaxLengthDiffPct);

	Log("singlehit=%s famsize=%d maxlengthdiffpct=%d\n",
	  g_paramSingleHitCoverage ? "True" : "False",
	  g_paramMinFamSize,
	  g_paramMaxLengthDiffPct);

	ProgressStart("Read hit file");
	int HitCount;
	int SeqLength;
	HitData *Hits = ReadHits(InputFileName, &HitCount, &SeqLength);
	ProgressDone();

	Progress("%d hits", HitCount);

	SeqLengthChunks = (SeqLength + CHUNK_LENGTH - 1)/CHUNK_LENGTH;

	const int BitVectorLength = (SeqLengthChunks + BITS_PER_INT - 1)/BITS_PER_INT;
	int *CopyCount = all(int, BitVectorLength);
	zero(CopyCount, int, BitVectorLength);

	ProgressStart("Compute copy counts");
	for (int i = 0; i < HitCount; ++i)
		IncCopyCount(CopyCount, Hits[i]);
	ProgressDone();

	ProgressStart("Identify piles");
	PILE_INDEX_TYPE *PileIndexes = IdentifyPiles(CopyCount);
	ProgressDone();

	Progress("%d stacks", PileCount);

	freemem(CopyCount);
	CopyCount = 0;

	CreatePiles(Hits, HitCount, PileIndexes);

	if (0 != ImagesFileName)
		{
		ProgressStart("Writing images file");
		WriteImages(ImagesFileName, Hits, HitCount, PileIndexes);
		ProgressDone();
		}

	freemem(Hits);
	Hits = 0;

	if (0 != PilesFileName)
		{
		ProgressStart("Writing piles file");
		WritePiles(PilesFileName, Piles, PileCount);
		ProgressDone();
		}

	freemem(PileIndexes);
	PileIndexes = 0;

	if (0 == OutputFileName)
		return;

	ProgressStart("Find edges");
	EdgeList Edges;
	FindGlobalEdges(Edges, MaxImageCount);
	ProgressDone();

	Progress("%d edges", (int) Edges.size());

	ProgressStart("Find families");
	FamList Fams;
	FindConnectedComponents(Edges, Fams, g_paramMinFamSize);
	AssignFamsToPiles(Fams);
	ProgressDone();

	Progress("%d families", (int) Fams.size());

	ProgressStart("Find superfamilies");
	EdgeList SuperEdges;
	FindSuperFamEdges(Fams, SuperEdges);

	FamList SuperFams;
	FindConnectedComponents(SuperEdges, SuperFams, 1);
	FindSingletonSuperFams(Fams, SuperFams);

	AssignSuperFamsToPiles(Fams, SuperFams);
	ProgressDone();

	Progress("%d superfamilies", (int) SuperFams.size());

	ProgressStart("Write TRS output file");
	WriteTRSFile(OutputFileName, Piles, PileCount);
	ProgressDone();
	}
Пример #11
0
int main(int argc, char **argv)
{
  int i, j, k,nodes = 0,prev_nodes = 0;

  srand(time(0));

  const int max_t = atoi(argv[1]);
  
  cout << max_t << endl;

  //const int max_n = 100;
  //  const int max_m = max_n * (max_n - 1) / 2;

  typedef pair<int, int> EdgePair;

  typedef std::list<EdgePair> EdgeList;


  for(int s = 0; s < max_t; ++s)
  {
    EdgeList edges;
    cout << endl;
    nodes = 0;

    const int ranks = MIN_RANKS
      + (rand () % (MAX_RANKS - MIN_RANKS + 1));
    
    //  printf ("digraph {\n");
    for (i = 0; i < ranks; i++)
    {
      /* New nodes of 'higher' rank than all nodes generated till now.  */
      int new_nodes = MIN_PER_RANK
                      + (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));

      /* Edges from old nodes ('nodes') to new ones ('new_nodes').  */
      for (j = prev_nodes; j < nodes; j++)
        for (k = 0; k < new_nodes; k++)
          if ( (rand () % 100) < PERCENT)
          {
            edges.push_back(make_pair(j, k + nodes));
          }
            //cout << j << " " << k + nodes << endl;
      //            printf ("%d %d\n", j, k + nodes); /* An Edge.  */

      prev_nodes = nodes;
      nodes += new_nodes; /* Accumulate into old node set.  */
    }

    cout << nodes << " " << edges.size() << endl;

    cout << 0;

    set<int> generated;

    for(i = 1; i < nodes; ++i)
    {
      int v = rand() % 1000 + 1;
      while(generated.find(v) != generated.end())
        v = rand() % 1000 + 1;

      cout << " " << v;

      generated.insert(v);
    }
    cout << endl;

    EdgeList::const_iterator edge = edges.begin();

    for(i = 0; i < edges.size(); ++i)
    {
      cout << edge->first << " " << edge->second << endl;
      ++edge;
    }
  }
  
  return 0;
}