예제 #1
0
// Return true if the cut edge at loop[index] is preceded by cuts through
// the edge end points.
bool Foam::geomCellLooper::edgeEndsCut
(
    const labelList& loop,
    const label index
) const
{
    label edgeI = getEdge(loop[index]);

    const edge& e = mesh().edges()[edgeI];

    const label prevCut = loop[loop.rcIndex(index)];
    const label nextCut = loop[loop.fcIndex(index)];

    if (!isEdge(prevCut) && !isEdge(nextCut))
    {
        // Cuts before and after are both vertices. Check if both
        // the edge endpoints
        label v0 = getVertex(prevCut);
        label v1 = getVertex(nextCut);

        if
        (
            (v0 == e[0] && v1 == e[1])
         || (v0 == e[1] && v1 == e[0])
        )
        {
            return true;
        }
    }
    return false;
}
예제 #2
0
/**
 * Returns the inner segment configuration.
 * @return inner segment configuration
 */
unsigned int BOP_Segment::getConfig() 
{
	if (isUndefined(m_cfg1)) return m_cfg2;
	else if (isUndefined(m_cfg2)) return m_cfg1;
	else if (isVertex(m_cfg1)) {
		// v1 is vertex
		if (isVertex(m_cfg2)) {
			// v2 is vertex
			return createEdgeCfg(getEdgeBetween(getVertex(m_cfg1),getVertex(m_cfg2)));
		}
		else if (isEdge(m_cfg2)) {
			// v2 is edge
			if (isOnEdge(m_cfg1,getEdge(m_cfg2))) return m_cfg2;
			else return createInCfg(); //IN
		} 
		else return createInCfg(); //IN
	}
	else if (isEdge(m_cfg1)) {
		// v1 is edge
		if (isVertex(m_cfg2)) {
			// v2 is vertex
			if (isOnEdge(m_cfg2,getEdge(m_cfg1))) return m_cfg1;
			else return createInCfg(); //IN
		}
		else if (isEdge(m_cfg2)) {
			// v2 is edge
			if (m_cfg1 == m_cfg2) return m_cfg1;
			else return createInCfg(); // IN
		}
		else return createInCfg(); // IN
	}
	else return createInCfg(); // IN
}
void
EdgeStrategy::onDataDenied
( const ndn::Data& data,
  const ndn::Interest& interest,
  ns3::Time& delay,
  const std::string& why )
{
    // if the denied data isn't leaving the network
    // then we just do the normal router stuff
    auto in_face = getFaceTable().get( data.getIncomingFaceId() );
    auto out_face = getFaceTable().get( interest.getIncomingFaceId() );
    bool coming_from_network = !in_face->isEdge();
    bool going_to_network = !out_face->isEdge();
    
    if( coming_from_network == going_to_network )
    {
        RouterStrategy::onDataDenied( data, interest, delay, why );
        return;
    }
    
    if( going_to_network )
    {
        BOOST_ASSERT( data.getCurrentNetwork()
                    == ndn::RouteTracker::INTERNET_NETWORK );
        RouterStrategy::onDataDenied( data, interest, delay, why );
        return;
    }
    
    // if the data is denied then we add the
    // tag used to retrieve it to the negative
    // cache; however we only want to do this
    // when the data is leaving the internet
    // and going into the client network
    // and the data's access level > 0
    BOOST_ASSERT( data.getCurrentNetwork()
                == ndn::RouteTracker::ENTRY_NETWORK );
    if( data.getAccessLevel() > 0 )
    {
        BOOST_ASSERT( interest.hasAuthTag() );
        tracers::edge->bloom_insert
        ( interest.getAuthTag(), s_edge_bloom_delay );
        delay += s_edge_bloom_delay;
        m_negative_cache.insert( interest.getAuthTag() );
    }

    // do whatever a normal router would do
    RouterStrategy::onDataDenied( data, interest, delay, why );
}
예제 #4
0
void Graph::BFS(Vertex *w)
{
    for(int i = 0; i < numVertices; i++)
    {
        marked[vertices[i]->num] = false;
    }
    
    marked[w->num] = true;
    queue<int> q;
    q.push(w->num);
    
    cout << "Breadth firts search starting from vertex ";
    cout << w->num << " : " << endl;
    
    while(!q.empty())
    {
        int v = q.front();
        q.pop();
        cout << v << "   ";
        
        for(int i = 0; i < numVertices; i++)
        {
            if(isEdge(vertices[v-1], vertices[i]) && !isMarked(vertices[i]))
            {
                q.push(vertices[i]->num);
                marked[vertices[i]->num] = true;
            }
        }
    }
    
    cout << endl;
}
예제 #5
0
inline HexPoint HexPointUtil::rightEdge(HexPoint edge)
{
    BenzeneAssert(isEdge(edge));
    if (edge == NORTH) return WEST;
    if (edge == SOUTH) return EAST;
    if (edge == EAST)  return NORTH;
    BenzeneAssert(edge == WEST);
    return SOUTH;
}
예제 #6
0
 void delEdge(int i, int j) 
 { 
     // Delete edge (i, j)
     if (isEdge(i,j)) 
     {
         vertex[i]->remove();
         numEdge--;
     }
 }
void
EdgeStrategy::onDataSatisfied
( const ndn::Data& data,
  const ndn::Interest& interest,
  ns3::Time& delay )
{
    // if the satisfied data isn't leaving the network
    // then we just do the normal router stuff
    auto in_face = getFaceTable().get( data.getIncomingFaceId() );
    auto out_face = getFaceTable().get( interest.getIncomingFaceId() );
    bool coming_from_network = !in_face->isEdge();
    bool going_to_network = !out_face->isEdge();
    
    if( coming_from_network == going_to_network )
    {
        RouterStrategy::onDataSatisfied( data, interest, delay );
        return;
    }
    
    if( going_to_network )
    {
        BOOST_ASSERT( data.getCurrentNetwork()
                    == ndn::RouteTracker::INTERNET_NETWORK );
        RouterStrategy::onDataSatisfied( data, interest, delay );
        return;
    }
    
    // if the data is satisfied then we add it to
    // the positive cache if it isn't marked with
    // the no recache flag and if its access level > 0
    BOOST_ASSERT( data.getCurrentNetwork()
                == ndn::RouteTracker::ENTRY_NETWORK );
    if( !data.getNoReCacheFlag()
      && data.getAccessLevel() > 0 )
    {
        BOOST_ASSERT( interest.hasAuthTag() );
        tracers::edge->bloom_insert
        ( interest.getAuthTag(), s_edge_bloom_delay );
        delay += s_edge_bloom_delay;
        m_positive_cache.insert( interest.getAuthTag() );
    }
    
    RouterStrategy::onDataSatisfied( data, interest, delay );
}
예제 #8
0
파일: Graph.cpp 프로젝트: jpsember/mcheck
void Graph::newEdgeAt(int a, int aPos, int b, int bPos, int abData, int baData) 
{
	if (!isEdge(a,b)) {
		Node &na = node(a), &nb = node(b);
		na.addNeighbor(b, abData, aPos);
		if (!halfEdges())
			nb.addNeighbor(a, baData, bPos);
		else ASSERT(baData < 0);
	}
}
예제 #9
0
// when an edge is added/removed update the adjacency lists of the nodes involved
void Graph::updateAdjacencyLists(Edge e) {
    if ( isEdge(e) ) {     // already an edge so remove
        getNode(e.getFrom()).removeNeighbor(getNode(e.getTo()));
        if ( digraph )
            getNode(e.getTo()).removeNeighbor(getNode(e.getFrom()));
    }
    else {                 // not an edge so add
        getNode(e.getFrom()).addNeighbor(getNode(e.getTo()));
    }
}
예제 #10
0
 int weight(int i, int j) 
 { 
     // Return weight of (i, j)
     Edge curr;
     if (isEdge(i, j)) 
     {
         curr = vertex[i]->getValue();
         return curr.weight();
     }
     else return 0;
 }
예제 #11
0
/* ADD [DGraph] */
int DGraph::addEdge(int x, int y) {
	if (x > this->getNoOfVertices() || y > this->getNoOfVertices()) {
		return 0;
	}
	else if (isEdge(x, y)) {
		return -1;
	}
	this->inbounds[y].push_back(x);
	this->outbounds[x].push_back(y);
	return 1;
}
예제 #12
0
 // Get v’s next neighbor after w
 int next(int v, int w) 
 {
     Edge it;
     if (isEdge(v, w)) 
     {
         if ((vertex[v]->currPos()+1) < vertex[v]->length()) 
         {
             vertex[v]->next();
             it = vertex[v]->getValue();
             return it.vertex();
         }
     }
     return n(); // No neighbor
 }
bool
EdgeStrategy::filterOutgoingData
( const nfd::Face& face,
  const ndn::Interest& interest,
  ndn::Data& data,
  ns3::Time& delay )
{
    auto in_face = getFaceTable().get( data.getIncomingFaceId() );
    bool coming_from_network = !in_face->isEdge();
    bool going_to_network = !face.isEdge();
    
    // if the data is coming from and leaving to
    // the same network  then we don't need to do
    // anything special
    if( coming_from_network == going_to_network )
    {
        return RouterStrategy::filterOutgoingData
               ( face, interest, data, delay ); 
    }
    
    // if the data is coming into the network then
    // we just change its current network
    if( going_to_network )
    {
        BOOST_ASSERT( data.getCurrentNetwork()
                    == ndn::RouteTracker::EXIT_NETWORK );
        tracers::edge->data_entered( data );
        data.setCurrentNetwork( ndn::RouteTracker::INTERNET_NETWORK );
        return RouterStrategy::filterOutgoingData
               ( face, interest, data, delay ); 
    }
    
    // if the data is leaving the network then we change
    // its current network
    if( coming_from_network )
    {
        BOOST_ASSERT( data.getCurrentNetwork()
                    == ndn::RouteTracker::INTERNET_NETWORK );
        tracers::edge->data_left( data );
        data.setCurrentNetwork( ndn::RouteTracker::ENTRY_NETWORK );
        return RouterStrategy::filterOutgoingData
               ( face, interest, data, delay );
    }
    
    // this should never happen
    BOOST_ASSERT( false );
    return true;
}
예제 #14
0
void Graph::generateNavGraph() {
    int l = map->getLength();
    int h = map->getHeight();

    int xExcess = l % proximity;
    int yExcess = h % proximity;

    if ( xExcess == 0 )
        xExcess = proximity;
    if ( yExcess == 0 )
        yExcess = proximity;

    cout << "Generating navGraph... xExcess=" << xExcess << ", yExcess=" << yExcess << ", proximity=" << proximity << endl;

    // create nodes
    Node * n;
    int index = 0;
    for( int x = xExcess/2; x < l; x += proximity ) {
        for( int y = yExcess/2; y < h; y += proximity ) {
            n = new Node(index, x, y);
            nodes.push_back(*n);
            index++;
        }
    }

    // this is only for a grid graph where cost of edges can only be sides of a square or diagonal of it.
    // also it assumes the grid base is parallel to x and y axis. in short this is a really specific code
    // not generic!
    double longedge = get_euclidian_distance(0, 0, proximity, proximity);
    double shortedge = get_euclidian_distance(0, 0, proximity, 0 );

    // create edges
    vector<Node>::iterator iter;
    for( iter = nodes.begin(); iter != nodes.end(); iter++ ) {
        vector<Node> nbrs = getNeighbors(*iter);
        vector<Node>::iterator it;
        for( it = nbrs.begin(); it != nbrs.end(); it++ ) {
            Edge * e = new Edge( iter->getID(), it->getID() ) ;
            if ( iter->getX() == it->getX() || iter->getY() == it->getY() )
                e->setCost(shortedge);
            else
                e->setCost(longedge);
            if ( !isEdge(*e) )
                edges.push_back(*e);
        }
    }
}
  void FilterBase::apply(cv::InputArray _src, cv::OutputArray _dst, const int &ddepth){
    int stype = _src.type();
    int dcn = _src.channels();
    int depth = CV_MAT_DEPTH(stype);

    if (0 <= ddepth)
      depth = ddepth;

    Mat src, dst;
    src = _src.getMat();

    Size sz = src.size();

    _dst.create(sz, CV_MAKETYPE(depth, dcn));
    dst = _dst.getMat();

    int imageWidth = src.rows;
    int imageHeight = src.cols;

    Mat srcChannels[3];
    split(src, srcChannels);

    int margineWidth = kernel.cols / 2;
    int margineHeight = kernel.rows / 2;
    double kernelElemCount = (double)(kernel.cols * kernel.rows);

    for(int ch = 0; ch < dcn; ++ch){
      for(int y = 0; y < imageHeight; ++y){
	Vec3d  *ptr = dst.ptr<Vec3d>(y);
	for(int x = 0; x < imageWidth; ++x){
	  if (isEdge(x, y, imageWidth, imageHeight, margineWidth, margineWidth)){
	    ptr[x][ch]
	      = calcKernelOutputAtEdge(srcChannels[ch],
				       kernel, x, y,
				       imageWidth, imageHeight,
				       margineWidth, margineHeight);
	  }else{
	    ptr[x][ch]
	      = calcKernelOutput(srcChannels[ch],
				 kernel, x, y,
				 margineWidth, margineHeight,				 
				 kernelElemCount);
	  }
	}
      }
    }
  }
예제 #16
0
bool Graph::DFS(Vertex *v, Vertex *w)
{
    stack<int> s;
    
    for(int i = 0; i < numVertices; i++)
    {
        marked[vertices[i]->num] = false;
    }
    
    s.push(v->num);
    marked[v->num] = true;
    bool found = false;
    
    if(v->num == w->num)
    {
        cout << "Same starting and Ending Vertex" << endl;
        cout << w->num << endl;
    }
    
    cout << "Depth firts search starting from vertex ";
    cout << v->num << " : " << endl;
    
    
    while(!s.empty())
    {
        int k = s.top();
        s.pop();
        
        if(k == w->num)
        {
            found = true;
            break;
        }
        cout << k << "   ";
        for(int i = numVertices - 1; i >= 0; i--)
        {
            if(isEdge(vertices[k - 1], vertices[i]) && !isMarked(vertices[i]))
            {
                s.push(vertices[i]->num);
                marked[vertices[i]->num] = true;
            }
        }
    }
    cout << endl;
    return found;
}
예제 #17
0
파일: Rbmp.cpp 프로젝트: skybosi/Imaginer
//fix up the point position,if the point is edge point
void fix_PIXPOS(PIXPOS& pixel,int W,int H)
{
	if(isEdge(pixel,W,H))
	{
		pixel.bEdge = true;
		if(pixel.pix_X < 0)
			pixel.pix_X += W;
		if(pixel.pix_Y < 0)
			pixel.pix_Y += H;
		if(pixel.pix_X >= W)
			pixel.pix_X -= W;
		if(pixel.pix_Y >= H)
			pixel.pix_Y -= H;
	}
	else
		pixel.bEdge = false;

}
예제 #18
0
파일: calcer.c 프로젝트: jiecchen/LapSolver
int main(int argc, char* argv[])
{
  if (argc != 4)
    die(1);

  printf("going to get graph\n");
  myGraph* graph = getGraph(argv[1]);
  printf("got graph\n");

  int v1, v2 = -1;
  sscanf(argv[2], "%d", &v1);
  sscanf(argv[3], "%d", &v2);
  
  // check that we were given an actual edge
  if (!isEdge(graph, v1, v2))
    die(1);
  
  checkWts(graph);

  int lastNNZ = -1;
  while(graph->nnz > 2)   // note each edge is counted twice (forwards/backwards)
    {
      printf("graph->nnz: %d\n", graph->nnz);     
      reduceGraph(&graph, v1, v2);
      if (lastNNZ == graph->nnz)
	{
	  fprintf(stderr, "ERROR: reduceGraph failed to do anything!\n");
	  exit(2);
	}
      lastNNZ = graph->nnz;
    }
  
  printf("The effective resistence is: %lf\n", graph->wts[v1][0]); // assume all other edges gone, so it has to be first listing!

  freeGraph(graph);
  
  return 0;
}
예제 #19
0
Bfs <TGraph> ::Bfs(TGraph _graph, bool (*isEdge)(typename TGraph::EdgeType*)) : graph(_graph) {
    int start = graph.s;
    dist.resize(graph.n, -1);
    prev.resize(graph.n, -1);
    dist[start] = 0;
    prev[start] = start;
    std::queue <int> q;
    q.push(start);
    while(!q.empty()) {
        int v = q.front();
        q.pop();
        for (int i = 0; i < graph.graph[v].size(); ++i) {
            if (isEdge(graph.graph[v][i])) {
                int to = graph.graph[v][i]->to;
                if (dist[to] == -1) {
                    dist[to] = dist[v] + 1;
                    prev[to] = v;
                    q.push(to);
                }
            }
        }
    }
}
예제 #20
0
 // Set edge (i, j) to "weight"
 void setEdge(int i, int j, int weight) 
 {
     Assert(weight>0, "May not set weight to 0");
     Edge currEdge(j, weight);
     if (isEdge(i, j)) 
     { 
         // Edge already exists in graph
         vertex[i]->remove();
         vertex[i]->insert(currEdge);
     }
     else 
     { 
         // Keep neighbors sorted by vertex index
         numEdge++;
         for (vertex[i]->moveToStart(); vertex[i]->currPos() < vertex[i]->length();vertex[i]->next()) 
         {                
             Edge temp = vertex[i]->getValue();
             if (temp.vertex() > j) 
                 break;
         }
         vertex[i]->insert(currEdge);
     }
 }
void Foam::hexCellLooper::makeFace
(
    const labelList& loop,
    const scalarField& loopWeights,

    labelList& faceVerts,
    pointField& facePoints
) const
{
    facePoints.setSize(loop.size());
    faceVerts.setSize(loop.size());

    forAll(loop, cutI)
    {
        label cut = loop[cutI];

        if (isEdge(cut))
        {
            label edgeI = getEdge(cut);

            const edge& e = mesh().edges()[edgeI];

            const point& v0 = mesh().points()[e.start()];
            const point& v1 = mesh().points()[e.end()];

            facePoints[cutI] =
                loopWeights[cutI]*v1 + (1.0-loopWeights[cutI])*v0;
        }
        else
        {
            label vertI = getVertex(cut);

            facePoints[cutI] = mesh().points()[vertI];
        }

        faceVerts[cutI] = cutI;
    }
예제 #22
0
Mat img_grad_mask(Mat grad_mag,Mat grad_x,Mat grad_y, Mat img_sym, double TH_G, double TH_P) // edge extraction
{
	if (grad_mag.depth() != CV_64F)
	{
		cout << "the data type of the grad_mag is wrong!" << endl;
		exit(-1);
	}
	Mat mask;
	mask.create(grad_mag.rows, grad_mag.cols, CV_8U); // 
	int i = 0, j = 0;
	bool flag_edge;

	for (i = 0; i < grad_mag.rows; i++)
	{
		for (j = 0; j < grad_mag.cols; j++)
		{
			mask.at<unsigned char>(i, j) = 0;
			if (grad_mag.at<double>(i, j) < TH_G)
			{
				continue;
			}
			flag_edge = isEdge(grad_mag, grad_x, grad_y, i, j);
			if (flag_edge)
			{
				double min_neighbor = min_8_neighbor(img_sym, i, j);
				double max_neighbor = max_8_neighbor(img_sym, i, j);
				double current_pixel = img_sym.at<uchar>(i, j);
				if ( ((current_pixel - max_neighbor) > TH_P) || ((current_pixel - min_neighbor) < -TH_P) )
				{
					continue;
				}
				mask.at<unsigned char>(i, j) = 255;
			}	
		}
	}
	return mask;
}
예제 #23
0
파일: Rbmp.cpp 프로젝트: skybosi/Imaginer
PIXPOT Rbmp::get_pot(PIXPOS pixel)
{
	PIXPOT ppot;
	memset(&ppot,0,sizeof(PIXPOT));
	try
	{
		if(out_range_error(pixel))
			throw 0;
	}
	catch(...)
	{
		printf("In get_pot, You set (x,y) is out Range!\n");
		return ppot;
	}
	ppot.pot.pix_X = pixel.pix_X;
	ppot.pot.pix_Y = pixel.pix_Y;
#ifdef ONLY
	ppot.pot.bEdge = isEdge(pixel,bmpWidth,bmpHeight);
#else
	ppot.pot.bEdge = pixel.isEdge(pixel,bmpWidth,bmpHeight);
#endif

	int lineByte = (bmpWidth * biBitCount + 31)/32*4;
	fseek(fp,bfOffBits + lineByte*(bmpHeight-pixel.pix_Y-1),0); //左上原点
	//	printf("坐标为(%d,%d)的像素\n",pixel.pix_X,pixel.pix_Y);

	BYTE8 *linedata = new BYTE8[lineByte];//一行像素的字节数(一个像素4个字节)
	//	printf("lineByte:%d\n",lineByte);
	fread(linedata,lineByte,1,fp);//读取一行的所有数据
	//fread(linedata,1,lineByte,fp);//读取一行的所有数据
	int rgbsite;
	int tablesite;
	switch(biBitCount)
	{
		case 24://OK
			//			printf("24位图\n");
			rgbsite = pixel.pix_X*3;
			ppot.prgb.rgbBlue  = linedata[rgbsite];
			ppot.prgb.rgbGreen = linedata[rgbsite+1];
			ppot.prgb.rgbRed   = linedata[rgbsite+2];
			break;
		case 8:
			//			printf("8位图\n");
			rgbsite= pixel.pix_X;
			tablesite = linedata[rgbsite];
			//printf("%03d\n",linedata[k]);
			//printf("颜色表位置:%d\n",tablesite);
			ppot.prgb.rgbRed   = pColorTable[tablesite].rgbRed;
			ppot.prgb.rgbGreen = pColorTable[tablesite].rgbGreen;
			ppot.prgb.rgbBlue  = pColorTable[tablesite].rgbBlue;
			break;
		case 4:
			printf("4位图\n");
			break;
		case 1:
			printf("1位图\n");
			break;
		case 32:
			printf("32位图\n");
			break;
		default:
			break;
	}
	//	show_PIXPOT(pixpot);
	delete []linedata;
	return ppot;
}
예제 #24
0
파일: Graph.cpp 프로젝트: daajoe/htd
bool htd::Graph::isEdge(const std::vector<htd::vertex_t> & elements) const
{
    return isEdge(htd::ConstCollection<htd::vertex_t>::getInstance(elements));
}
예제 #25
0
EyeCalibration::SegmentVector EyeCalibration::calculateConvexHull(CalibrationPointVector processingPoints) {
	// Edges
	SegmentVector segments;

	if (processingPoints.size() < 3)
		return segments;

	CalibrationPoint 
		minX = processingPoints.at(0), 
		minY = processingPoints.at(0), 
		maxX = processingPoints.at(0), 
		maxY = processingPoints.at(0);

	for (unsigned int i = 0; i < processingPoints.size(); i++) {
		CalibrationPoint point = processingPoints.at(i);
		osg::Vec3 ray = point.ray();

		if (minX.x() > point.x())
			minX = point;

		if (minY.y() > point.y())
			minY = point;

		if (maxX.x() < point.x())
			maxX = point;

		if (maxY.y() < point.y())
			maxY = point;
	}

	// Get center
	int center_x = (maxX.x() - minX.x())/2;
	int center_y = (maxY.y() - minY.y())/2;

	// Ordered Point
	CalibrationPointVector orderedPoints(processingPoints);

	// Sort Points
	sort(orderedPoints, center_x, center_y);

	// Create segments
	for (unsigned int i = 0; i < orderedPoints.size(); i++) {
		CalibrationPoint from = orderedPoints.at(i);

		for (unsigned int k = 0; k < orderedPoints.size(); k++) {
			if (i == k)
				continue;

			CalibrationPoint to = orderedPoints.at(k);

			Segment segment(from, to);
			segments.push_back(segment);
		}
	}

	unsigned int i = 0;
	unsigned int j = 0;
	while ( i < segments.size() )
	{
		//ProcessingPoints will be the points that are not in  the current segment
		CalibrationPointVector processingPoints(orderedPoints);
		Segment segment = segments.at(i);

		//this loop prepares the ProcessingPoints list for each segment
		while ( j < processingPoints.size() )
		{
			CalibrationPoint point = processingPoints.at(j);
			if((segment.x1() == point.x() && segment.y1() == point.y()) ||
				(segment.x2() == point.x() && segment.y2() == point.y()))
			{
				//eliminating the points that are already in the current segment...
				//we don't need them
				processingPoints.erase(processingPoints.begin()+j);
				j = 0;
			} else {
				j++;
			}
		}

		//checking if the current segment is an edge or notBy calling isEdge function
		if( !isEdge(processingPoints, segments.at(i)) )
		{
			segments.erase(segments.begin()+i);
			i = 0;
		} else {
			i++;
		} 
	}

	return segments;
}
예제 #26
0
bool HamPathVisitor::permutateAndValidate()
{
    _coloredEdges.clear();
    _edgeColors.clear();

    const vector<Node*>& nodes = _graph->getNodes();

    // keep on permutating until we get one without doubles
    do
    {
        _positions[_positions.size()-1]++;

        for ( unsigned i = _positions.size()-1; i > 0; i-- )
        {
            // overflowing, reset last position
            if (_positions[i] >= static_cast<int>(_positions.size()))
            {
                int dif = _positions[i] - (_positions.size() -1);
                _positions[i-1] += dif;
                _positions[i] = 0; // start value
            }
        }

        // reached the end, graph has no hamiltonian path
        if (_positions[0] >= static_cast<int>(_positions.size()))
        {
            _finished = true;
            // reset the color
            vector<Node*> nodes = _graph->getNodes();
            for (unsigned i = 0; i < nodes.size(); ++i)
                nodes[i]->setColor(_nodeColors[i]);
            for (unsigned i = 0; i < _coloredEdges.size(); ++i)
                _coloredEdges[i]->setColor(_edgeColors[i]);
            throw InvalidGraph("The graph does not contain an Hamiltonian path.", 1);
        }

        // set the new permutation and set it's color to orange because it's a candidate path
        for (unsigned i = 0; i < _positions.size(); ++i)
        {
            _permutation[i] = nodes[_positions[i]];
            _permutation[i]->setColor(RGB::colorOrange());
        }
    } while  (doubles(_positions) );


    // passed to isEdge
    Edge* edge;
    unsigned size = nodes.size();
    // check if the permutation is a hamiltonian path
    // verification stage
    for (unsigned i = 0; i < size - 1; ++i)
    {
        // if (_path[i], _path[i+1]) is not an edge
        if ( !isEdge(_permutation[i], _permutation[i+1], &edge) )
            return false;

        // if there is an edge, color it
        else
        {
            _drew = true;
            _edgeColors.push_back(edge->getColor());
            edge->setColor(RGB::colorOrange());
            _coloredEdges.push_back(edge);
        }
    }

    // if we get here, it was a hamiltonian path!
    return true;
}
예제 #27
0
파일: Rbmp.cpp 프로젝트: skybosi/Imaginer
/*函数名称readIline()*/
bool Rbmp::readIline()
{
	if(fp ==  NULL)
		return false;
	int lineByte;
	lineByte = (bmpWidth * biBitCount + 31)/32*4;
	printf("kkkkk:%d\n",lineByte);
	BYTE8 *linedata = new BYTE8[lineByte];
	PIXPOT *lineppot = new PIXPOT[bmpWidth];
	fseek(fp,bfOffBits,0); //左上原点
	int k;
	int x = 0;
	int tablesite;
	for(int y = bmpHeight-1; y >= 0; y--)//左上为原点
//	for(int i = 0; i < bmpHeight; i++)//左下为原点
	{
		fread(linedata,1,lineByte,fp);
		for(k = 0;x < bmpWidth/*k < lineByte*/; k++)
		{
			printf("%03d ",linedata[k]);
			switch(biBitCount)
			{
				case 24://OK
					lineppot[x].prgb.rgbBlue  = linedata[k];
					lineppot[x].prgb.rgbGreen = linedata[++k];
					lineppot[x].prgb.rgbRed   = linedata[++k];
					lineppot[x].pot.pix_X = x;
					lineppot[x].pot.pix_Y = y;
					if(isEdge(lineppot[x].pot,bmpWidth,bmpHeight))
						lineppot[x].pot.bEdge = true;
					else
						lineppot[x].pot.bEdge = false;
					break;
				case 8:
					tablesite = linedata[k];
					//printf("%03d\n",linedata[k]);
					//printf("颜色表位置:%d\n",tablesite);
					lineppot[x].prgb.rgbRed   = pColorTable[tablesite].rgbRed;
					lineppot[x].prgb.rgbGreen = pColorTable[tablesite].rgbGreen;
					lineppot[x].prgb.rgbBlue  = pColorTable[tablesite].rgbBlue;
					lineppot[x].pot.pix_X = x;
					lineppot[x].pot.pix_Y = y;
					if(isEdge(lineppot[x].pot,bmpWidth,bmpHeight))
						lineppot[x].pot.bEdge = true;
					else
						lineppot[x].pot.bEdge = false;
					break;
				default:
					break;
			}
#ifdef ONLY
			show_PIXPOT(lineppot[x]);
#else
			lineppot[x].show_PIXPOT();
#endif
			printf("\n");
			x++;
		}
		x = 0;
		cout << endl;
	}
	delete []linedata;
	delete []lineppot;
	return true;
}
예제 #28
0
//-----------------------------------------------------------------------------
void Myron::ProcessGlobIDs(){
  
  //reset the globID buffer.
  
  for(int i=0;i<this->imageWidth*this->imageHeight;i++){
    this->globIDs[i] = 0;
  }

  //erase the global globbox accum buffer.
  this->globBoxListCount = 0;
  this->globPixelListsCount = 0;
  //reset the working glob counter.
  int curGlobID = 0;


  //loop through all the pixels and call the recursive function on them
  for(int y=0;y<this->imageHeight;y++){

    for(int x=0;x<this->imageWidth;x++){
	  
      int t =y*this->imageWidth+x;
  

	  int r1 = isEdge(x,y);
		int r2 = (this->globIDs[t] == 0);
		int r3 = (this->globPixelList[t] == 255);
	
	  if(r2 && r3 && r1 ){
	curGlobID++;

	//found one. so find all the neighbors too.
	stackFriendlyRecursiveGlobFind(x,y,curGlobID);
	
	//now erase the globs below minDensity
	
	int logicaccum = 0;
	if(this->maxDensity_state>this->minDensity_state){//is max density NOT infinite?
	  logicaccum = (this->thisGlobCount>this->maxDensity_state);//then also check for upper bound
	}
	if(this->thisGlobCount<this->minDensity_state||logicaccum){
	  //kill this glob
	  for(int i=0;i<this->thisGlobCount;i++){
	    //turn that pixel black and erase its ID.
	    this->globPixelList[this->thisGlobYs[i]*this->imageWidth+this->thisGlobXs[i]] = 0;
	    this->globIDs   [this->thisGlobYs[i]*this->imageWidth+this->thisGlobXs[i]] = 0;
	  }//end for
	} else {
	  
	  //store the weirdly ordered pixel list for later use
	  for(int i=0;i<this->thisGlobCount;i++){
	    this->globPixelLists[this->globPixelListsCount*3+0] = this->thisGlobXs[i];
	    this->globPixelLists[this->globPixelListsCount*3+1] = this->thisGlobYs[i];
	    //now record whether this is a head or a tail.
	    if(i==0){
	      this->globPixelLists[this->globPixelListsCount*3+2] = 1;
	    }else if(i==this->thisGlobCount-1){
	      this->globPixelLists[this->globPixelListsCount*3+2] = 2;
	    }else{
	      this->globPixelLists[this->globPixelListsCount*3+2] = 0;
	    }
	    this->globPixelListsCount++;
	  }//end for
	  
	   //do further analysis on it.
	   //1. find the bounding box of it.
	  int topmost = 10000000;
	  int bottommost = -1000000;
	  int leftmost = 10000000;
	  int rightmost = -100000000;
	  int i;
	  for(i=0;i<this->thisGlobCount;i++){
	    if(this->thisGlobXs[i]<leftmost)leftmost=this->thisGlobXs[i];
	    if(this->thisGlobXs[i]>rightmost)rightmost=this->thisGlobXs[i];
	    if(this->thisGlobYs[i]<topmost)topmost=this->thisGlobYs[i];
	    if(this->thisGlobYs[i]>bottommost)bottommost=this->thisGlobYs[i];						
	  }
	  //store this data.
	  this->globBoxList[this->globBoxListCount*4+0] = leftmost;
	  this->globBoxList[this->globBoxListCount*4+1] = topmost;
	  this->globBoxList[this->globBoxListCount*4+2] = rightmost;
	  this->globBoxList[this->globBoxListCount*4+3] = bottommost;
	  this->globBoxListCount++;
	}//end if				
	
      }//end if
    }//end for
  }//end for

  int i;
  //calculate centerpoints
  for(i=0;i<this->globBoxListCount;i++){
    this->globCenterPoints[i*2+0] = (this->globBoxList[i*4+0]+this->globBoxList[i*4+2])/2;
    this->globCenterPoints[i*2+1] = (this->globBoxList[i*4+1]+this->globBoxList[i*4+3])/2;
  }

}
예제 #29
0
//-----------------------------------------------------------------------------
void Myron::stackFriendlyRecursiveGlobFind(int x,int y, int curGlobID){
  // i am proud of myself for writing this without using recursive function calling
  // because that was crashing on Mac OS X - the os having a (defaultly) small stack.
  // i bet linux is the same.
  // -josh
  

  
  this->thisGlobCount = 1;	//clear the current glob data
  int stackCount = 1;	//clear the parsing stack
  this->stackX[0] = x;
  this->stackY[0] = y;
  this->globIDs[y*this->imageWidth+x] = curGlobID;
  this->thisGlobXs[0] = x;
  this->thisGlobYs[0] = y;
  //i just added the stack's first item.
  
  //do all the neighbors of this guy to see if we can start a stack.
  int t;
  int xx;
  int yy;
  



  while(stackCount>0){
    //pop one off.
    xx = this->stackX[stackCount-1];
    yy = this->stackY[stackCount-1];
    stackCount--;
    
    //then check the neighbors if they need to be dealt with later as well.
    
    //left
    if(xx-1>=0){
      t = yy*this->imageWidth+(xx-1);
      if(	this->globIDs[t] == 0 && this->globPixelList[t] == 255 && isEdge(xx,yy) ){
	this->stackX[stackCount] = xx-1;
	this->stackY[stackCount] = yy;
	this->globIDs[t] = curGlobID;
	this->thisGlobXs[this->thisGlobCount] = xx-1;
	this->thisGlobYs[this->thisGlobCount] = yy;
	this->thisGlobCount++;
	stackCount++;
      }
    }
    
    //top
    if(yy-1>=0){
      t = (yy-1)*this->imageWidth+(xx);
      if(	this->globIDs[t] == 0 && this->globPixelList[t] == 255 && isEdge(xx,yy) ){
	this->stackX[stackCount] = xx;
	this->stackY[stackCount] = yy-1;
	this->globIDs[t] = curGlobID;
	this->thisGlobXs[this->thisGlobCount] = xx;
	this->thisGlobYs[this->thisGlobCount] = yy-1;
	this->thisGlobCount++;
	stackCount++;
      }
    }
    
    //bottom
    if(yy+1<this->imageHeight){
      t = (yy+1)*this->imageWidth+(xx);
      if(	this->globIDs[t] == 0 && this->globPixelList[t] == 255 && isEdge(xx,yy) ){
	this->stackX[stackCount] = xx;
	this->stackY[stackCount] = yy+1;
	this->globIDs[t] = curGlobID;
	this->thisGlobXs[this->thisGlobCount] = xx;
	this->thisGlobYs[this->thisGlobCount] = yy+1;
	this->thisGlobCount++;
	stackCount++;
      }
    }
    
    //right
    if(xx+1<this->imageWidth){
      t = (yy)*this->imageWidth+(xx+1);
      if(	this->globIDs[t] == 0 && this->globPixelList[t] == 255 && isEdge(xx,yy) ){
	this->stackX[stackCount] = xx+1;
	this->stackY[stackCount] = yy;
	this->globIDs[t] = curGlobID;
	this->thisGlobXs[this->thisGlobCount] = xx+1;
	this->thisGlobYs[this->thisGlobCount] = yy;
	this->thisGlobCount++;
	stackCount++;
      }
    }
    
  }
}
bool
EdgeStrategy::filterOutgoingInterest
( const nfd::Face& face,
  ndn::Interest& interest,
  ns3::Time& delay )
{
    auto in_face = getFaceTable().get( interest.getIncomingFaceId() );
    bool coming_from_network = !in_face->isEdge();
    bool going_to_network = !face.isEdge();
    
    // if the interest coming from and going to
    // the same network then we don't need to do
    // anything special
    if( coming_from_network == going_to_network )
    {
        return RouterStrategy::filterOutgoingInterest
               ( face, interest, delay );
    }
    
    // if the interest is leaving the network then just change
    // current network
    if( coming_from_network )
    {
        BOOST_ASSERT( interest.getCurrentNetwork()
                    == ndn::RouteTracker::INTERNET_NETWORK );
        tracers::edge->interest_left( interest );
        interest.setCurrentNetwork( ndn::RouteTracker::EXIT_NETWORK );
        return RouterStrategy::filterOutgoingInterest
               ( face, interest, delay );
    }
    
    // if the interest is entering the network then
    // we need to do some extra stuff
    BOOST_ASSERT( interest.getCurrentNetwork()
                == ndn::RouteTracker::ENTRY_NETWORK );
    tracers::edge->interest_entered( interest );
    interest.setCurrentNetwork( ndn::RouteTracker::INTERNET_NETWORK );
    
    // if the interest doesn't have an auth tag, or its auth level
    // is 0 then we don't do any authentication
    if( !interest.hasAuthTag()
      || interest.getAuthTag().getAccessLevel() == 0 )
    {
        return RouterStrategy::filterOutgoingInterest( face,
                                                        interest,
                                                        delay );
    }
    
    const ndn::AuthTag& auth = interest.getAuthTag();

    // if the auth tag provided by the interest is expired
    // then we can drop the interest
    if( auth.isExpired() )
    {
        tracers::edge->blocked_interest
        ( interest, tracers::BlockedExpired );
        onInterestDropped( interest, face, "Expired auth" );
        return false;
    }
    
    // if the interest and auth tag have different prefixes
    // then we drop the interest
    if( !auth.getPrefix().isPrefixOf( interest.getName() ) )
    {
        tracers::edge->blocked_interest
        ( interest, tracers::BlockedBadPrefix );
        onInterestDropped( interest, face, "Mismatched prefix" );
        return false;
    }
    
    // if the interest route hash doesn't match its auth tag
    // then we can drop it
    if( interest.getEntryRoute() != auth.getRouteHash() )
    {
        tracers::edge->blocked_interest
        ( interest, tracers::BlockedBadRoute );
        onInterestDropped( interest, face, "Bad route" );
        return false;
    }
    
    // if the interest auth is in the positive auth cache then
    // we set its auth validity probability
    tracers::edge->bloom_lookup( auth, s_edge_bloom_delay );
    delay += s_edge_bloom_delay;
    if( m_positive_cache.contains( auth ) )
    {
        double fpp = m_positive_cache.getEffectiveFPP();
        double prob = (double)1.0 - fpp;
        uint32_t iprob = prob*0xFFFFFFFF;
        interest.setAuthValidityProb( iprob );
        
    }
    else
    {
        // if it's in the negative cache then we validate
        // its signature manually
        tracers::edge->bloom_lookup( auth, s_edge_bloom_delay );
        delay += s_edge_bloom_delay;
        if( m_negative_cache.contains( auth ) )
        {
            // we simulate verification delay by incrementing
            // the processing delay
            tracers::edge->sigverif( auth, s_edge_signature_delay );
            delay += EdgeStrategy::s_edge_signature_delay;
            if( auth.getSignature().getValue().value_size() > 0
              && auth.getSignature().getValue().value()[0] != 0 )
            {
                // if signature is valid then set auth validity
                // and put auth into positive cache
                interest.setAuthValidityProb( 0xFFFFFFFF );
                tracers::edge->auth_cached
                ( auth, tracers::CachedPositiveMoved );
                m_positive_cache.insert( auth );
            }
            else
            {
                // otherwise we drop the interest
                onInterestDropped( interest, face, "negative cache, manual validation failed" );
                return false;
            }
        }
        else
        {
            // if the auth isn't in either cache then
            // we set validity probability to 0
            interest.setAuthValidityProb( 0 );
        }
    }
    
    return RouterStrategy::filterOutgoingInterest( face, interest,
                                                   delay );
}