Пример #1
0
void FilterOutputOpticalFlowPlugin::getNeighbors( CFaceO *f,
                                                  NeighbSet &neighb ) const
{
    getNeighbors( f->V(0), neighb );
    getNeighbors( f->V(1), neighb );
    getNeighbors( f->V(2), neighb );
}
Пример #2
0
	void expandClusterOrder(int obj, float eps, int minPts ) {
		std::vector<int> neighbors(minPts);
		getNeighbors( obj, eps, neighbors );
		setProcessed(obj);

		unsetReachDist(obj);

		setCoreDistance( obj, neighbors, eps, minPts );
		m_orderedSet[m_osNext] = obj;
		m_osNext++;

		if( hasCoreDist(obj) ) {
			orderSeedsUpdate( neighbors, obj );

			while( !m_orderSeeds.empty() ) {
				OsMember cosm = m_orderSeeds.top();
				m_orderSeeds.pop();

				int currentObj = cosm.m_obj;

				getNeighbors(currentObj, eps, neighbors);
				setProcessed(currentObj);
				setCoreDistance(currentObj, neighbors, eps, minPts);

				m_orderedSet[m_osNext] = currentObj;
				m_osNext++;

				if( hasCoreDist(currentObj)) {
					orderSeedsUpdate(neighbors, currentObj);
				}

			}
		}
	}
Пример #3
0
//////////////////////////////////////////////////////////////////////////////
// Name:                         processCells
// Purpose:
//    Process cell state into next states.
// Parameters: None
// Returns:    None
void processCells()
{
    int w, h, n;

    for (h = 0; h < HEIGHT; h++)
        for (w = 0; w < WIDTH; w++)
        {
            n = getNeighbors(w, h);

            if (Cells[w][h].state == STATE_ALIVE)
            {
                if (CELL_SURVIVAL_CONDITION)
                    Cells[w][h].state = STATE_ALIVE;

                else if (CELL_OVERCROWDING_CONDITION)
                    Cells[w][h].state = STATE_DEAD;

                else if (CELL_ISOLATION_CONDITION)
                    Cells[w][h].state = STATE_DEAD;
            }
            else if (EMPTY_CELL_GENERATION_CONDITION)
                Cells[w][h].state = STATE_ALIVE;

            if (n == 8)
                Cells[w][h].state = STATE_ALIVE;
        }

    return;
}
Пример #4
0
SingleParticle2dx::DataStructures::Particle::value_type SingleParticle2dx::DataStructures::Particle::calculateDensity()
{
	SingleParticle2dx::ConfigContainer* config = SingleParticle2dx::ConfigContainer::Instance();
	std::vector<Particle*> neighbors = getNeighbors();
	
	if(neighbors.size() < 0.5)
	{
		return -1;
	}
	
	SingleParticle2dx::DataStructures::GlobalParticleInformation part_info;
	
	value_type current_radius;
	value_type x = getGlobalParticleInformation().getPositionX();
	value_type y = getGlobalParticleInformation().getPositionY();
	
	boost::accumulators::accumulator_set<value_type, boost::accumulators::stats<boost::accumulators::tag::max> > acc;
	
	for(int i=0; i< static_cast<int>(neighbors.size()); i++)
	{
		part_info = neighbors[i]->getGlobalParticleInformation();
		current_radius = sqrt((x - part_info.getPositionX()) * (x - part_info.getPositionX()) + (y - part_info.getPositionY()) * (y - part_info.getPositionY()));
		acc(current_radius);
	}
	
	value_type max_r = boost::accumulators::extract_result<boost::accumulators::tag::max>(acc);
	
	return static_cast<value_type>(neighbors.size()) / (config->getPI() * max_r * max_r * 0.0001 * 0.0001); 
}
Пример #5
0
    void gameOfLife(std::vector<std::vector<int>>& board) { // 0 ms
        /*
         * 0 --> 1 represented as 2
         * 1 --> 0 represented as 3
         */
        // mark 2 & 3
        if (board.empty() || board[0].empty()) { return; }
        int M = board.size(), N = board[0].size();

        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                auto neighbors = getNeighbors(board, i, j);
                if (board[i][j] == 0) {
                    if (neighbors == 3) { board[i][j] = 2; } // dead to live, reproduction
                } else {
                    if (neighbors < 2) { board[i][j] = 3; } // live to dead, under population
                    if (neighbors > 3) { board[i][j] = 3; } // live to dead, over population
                }
            }
        }

        for (auto& row : board) {
            for (auto& val : row) {
                if (val == 2) { val = 1; }
                if (val == 3) { val = 0; }
            }
        }
    }
Пример #6
0
int main(int argc, char const *argv[]) {
	int n, i, *array, value, n1, n2, peaks;
	scanf("%d", &n);
	while(n != 0) {
		array = malloc(n * sizeof(int));
		peaks = 0;
		for(i = 0; i < n; i++)
			scanf("%d", array + i);
		if(n == 2) {
			peaks = 2;
			goto REPORT_ANS;
		}
		for(i = 0; i < n; i++) {
			getNeighbors(n, i, &n1, &n2);
			value = *(array + i);
			n1 = *(array + n1);
			n2 = *(array + n2);
			if(isPeak(value, n1, n2))
				peaks++;
		}
		REPORT_ANS:
			printf("%d\n", peaks);
		scanf("%d", &n);
	}
	return 0;
}
Пример #7
0
int aura_get_next(wmpFrame * p, aura_t * type){
	char nb[32];
	int n_nb = getNeighbors(lqm_get_ptr(),status.id,nb);
	int i, best_val = 1000, best_id = -1;
	for (i = 0; i< n_nb ;i++){
		int elem = aura_vec[(int)nb[i]];
		if (elem < best_val){
			best_val = elem;
			best_id = nb[i];
		}
	}
	if (best_val == 0){
		*type = aura_msg;
		return best_id;
	} else if (best_val == 1){
		*type = aura_msg;
		return best_id;
	} else if (best_val == 2){
		*type = aura_auth;
		return best_id;
	}else{
                //WMP_ERROR(stderr,"Value:%d serial:%u\n",best_val,(int) p->hdr.serial);
		return -1;
	}
}
Пример #8
0
void CascadeClassifier::detectMultiScale( const Mat& image, std::vector<Rect>& objects,
                                          std::vector<int>& numDetections, double scaleFactor,
                                          int minNeighbors, int flags, Size minObjectSize,
                                          Size maxObjectSize )
{
    CV_Assert( scaleFactor > 1 && image.depth() == CV_8U );

    if( empty() )
        return;

    std::vector<int> fakeLevels;
    std::vector<double> fakeWeights;
    if( isOldFormatCascade() )
    {
        std::vector<CvAvgComp> vecAvgComp;
        detectMultiScaleOldFormat( image, oldCascade, objects, fakeLevels, fakeWeights, vecAvgComp, scaleFactor,
                                   minNeighbors, flags, minObjectSize, maxObjectSize );
        numDetections.resize(vecAvgComp.size());
        std::transform(vecAvgComp.begin(), vecAvgComp.end(), numDetections.begin(), getNeighbors());
    }
    else
    {
        detectMultiScaleNoGrouping( image, objects, fakeLevels, fakeWeights, scaleFactor, minObjectSize, maxObjectSize );
        const double GROUP_EPS = 0.2;
        groupRectangles( objects, numDetections, minNeighbors, GROUP_EPS );
    }
}
Пример #9
0
int main(void){	

		//iterate along listings
	for(int i = 0; i < NUMLISTINGS; i++){
			//get k nearest neighbor if the listing is not known
		if(listings[i].type == UNKNOWN){
				//initialize to non-useable number
			int sizeOfArray = -1;

			struct listing *neighbors = getNeighbors(&sizeOfArray);									
			neighbors = getDistance(listings[i].bedrooms, listings[i].squareFeet, sizeOfArray, neighbors);			
			neighbors = bubbleSort(neighbors, sizeOfArray);

			int type = getType(neighbors, 5);
				
				//print which listing we're talking about here
			printf("\t%d:", i);
			if(type == APARTMENT)
				printf("\tThis is an apartment!\n");
			else if(type == HOUSE)
				printf("\tThis is a house!\n");
			free(neighbors);
		}		
	}

}
Пример #10
0
	/**
	 * Find all maximal cliques in an induced subgraph of some chain component
	 *
	 * NOTE: the function does not check whether the provided range of vertices
	 * really is a subset of some chain component!
	 */
	template <typename InputIterator> std::vector<std::set<uint> > getMaxCliques(InputIterator first, InputIterator last)
	{
		std::vector<std::set<uint> > maxCliques;

		// Trivial case: range of vertices contains at most one vertex
		if (std::distance(first, last) <= 1) {
			maxCliques.push_back(std::set<uint>(first, last));
			return maxCliques;
		}

		// For less trivial cases, first generate a LexBFS-ordering on the provided range of vertices
		std::vector<uint> ordering = lexBFS(first, last);

		// Find maximal cliques using the LexBFS-ordering
		std::set<uint> nbhdSubset(first, last);
		std::set<uint> vertices, C;
		std::vector<std::set<uint> >::iterator cliqueIter;
		bool included;
		for (int i = ordering.size() - 1; i >= 0; --i) {
			nbhdSubset.erase(ordering[i]);
			vertices = getNeighbors(ordering[i]);
			C = set_intersection(vertices, nbhdSubset);
			C.insert(ordering[i]);
			included = false;
			for (cliqueIter = maxCliques.begin(); !included && cliqueIter != maxCliques.end(); ++cliqueIter)
				included = std::includes(cliqueIter->begin(), cliqueIter->end(), C.begin(), C.end());
			if (!included)
				maxCliques.push_back(C);
		}

		return maxCliques;
	}
Пример #11
0
// doesn't this always return iteration?
// This does always return iteration. Sorry. I don't know the hint of this commet.
int PathFinder::shortestLength(int iteration=1){
  std::vector<Point> neighbors;
  std::set<Point>::iterator it;
  // Why allocate newClosed on the heap? make it stack allocated, and you get destruction for free
  //yest the swap is  better choice 
  std::set<Point> newClosed;

  for(it=closed->begin(); it != closed->end(); it++){
    neighbors=getNeighbors(*it);
    for(int i=0; i< neighbors.size(); i++){
      Point neighbor = neighbors[i];
	  // magic numbers like -1 aren't good here
      //don't quite get the idea of this comment
      if(validPoint(neighbor) && (*open)[neighbor] == -1) return iteration;

      if(validPoint(neighbor) && (*open)[neighbor] == 0 && (*pointStatus)[neighbor] !=1){
	(*open)[neighbor]=iteration +1;
	newClosed.insert(neighbor);
      }
    }
  }
  closed->swap(newClosed);

  iteration=shortestLength(iteration+1);
  return iteration;
}
Пример #12
0
void looking (_node** tree, char** grid, char* string, stack* stack, table* allWords)
{
    int f = searchDictionary(tree,string);
    int i;

    if (f != -1)
    {
        if (f) tableAdd(allWords,string);
        stackPrint(stack);
        neighbors* n = getNeighbors (stackTop(stack));

        for (i = 0; i < neighSize(n); ++i)
        {
            position* newPos = neighGet(n,i);
            if (!stackFind(stack,newPos))
            {
                stackPush(stack,newPos);
                char newString[strlen(string)+1];
                strcpy(newString,string);
                strcat(newString,&(grid[newPos->x][newPos->y]));

                looking(tree,grid,newString,stack,allWords);
            }
        }
    }
}
Пример #13
0
//Initialize an sor struct
sor* init_sor(int rank, int num_proc, int m_width, int m_height, float p_h,
                float p_w, float p_threshold, int q)
{
    sor* block = malloc(sizeof(sor));
    MPI_Cart_coords(CARTESIAN_COMM, rank, 2, block->coords);
    block->generation = 1;
    block->h = pow(p_h, 2);
    block->w = p_w;
    block->threshold = p_threshold;
    block->proc_num = num_proc;
    block->rank_id = rank;
    //block->matrix_width = m_width;
    //block->matrix_height = m_height;
    block->grid_size = sqrt(num_proc);
    block->block_width = (m_width*q)/num_proc + 2;
    block->block_height = m_height/q + 2;
    block->data = malloc(block->block_width * block->block_height * sizeof(float));
    block->next_data = malloc(block->block_width * block->block_height * sizeof(float));

    createDatatypes(block->block_width, block->block_height);

    //initial values assigment
    int i;
    for ( i = 0; i < block->block_width * block->block_height; i++ )
        block->data[i] = 1;
    // set top row to zero
    if ( block->coords[0] != 0 )
    {
        for ( i = 0; i < block->block_width; i++ )
            block->data[i] = 0;
    }
    // set bottom row to zero
    if ( block->coords[0] != block->grid_size - 1)
    {
        for ( i = (block->block_width - 1) * block->block_height - 1; i < block->block_width * block->block_height; i++ )
            block->data[i] = 0;
    }
    // set first column to zero
    if ( block->coords[1] != 0 )
    {
        for ( i = 0; i < (block->block_width - 1) * block->block_height; i+=block->block_width )
            block->data[i] = 0;
    }
    // set last column to zero
    if ( block->coords[1] != block->grid_size - 1 )
    {
        for ( i = block->block_width - 1; i < block->block_width * block->block_height; i+=block->block_width )
            block->data[i] = 1;
    }
    getNeighbors(block);
    //allocate swap-buffers for send/receive
    block->top_row = malloc(block->block_width * sizeof(float));
    block->bottom_row = malloc(block->block_width * sizeof(float));
    block->first_col = malloc(block->block_height * sizeof(float));
    block->last_col = malloc(block->block_height * sizeof(float));

    return block;
}
Пример #14
0
void UnwalkableArea::fillAreaAround(const TilePosition& tile) {
	if (Broodwar->isWalkable(WalkPosition(tile)) || this->contains(tile)) return;

	tiles.insert(tile);
	const auto& neighbors = getNeighbors(tile);
	for (auto n : neighbors) {
		fillAreaAround(n);
	}
}
Пример #15
0
std::vector<pTileNode> MapAnalyzer::getNeighborNodes(const TilePosition& tile, pred p) {
	std::vector<pTileNode> result;
	auto neighbors = getNeighbors(tile);
	//auto neighbors = get4Neighbours(node->pos);
	for (auto n : neighbors) {
		auto node = getNode(n);
		if (p(node))
			result.push_back(node);
	}
	return result;
}
Пример #16
0
/// Returns the list of neighbors within dist of the point x/y. This
/// can be the position of an agent, but it is not limited to this.
/// \date    2012-01-29
/// \return  The list of neighbors
/// \param   x the x coordinate
/// \param   y the y coordinate
/// \param   dist the distance around x/y that will be searched for agents (search field is a square in the current implementation)
set<const Ped::Tagent*> Ped::Model::getNeighbors(int x, int y, int dist) const {
  // if there is no tree, return all agents
  if(tree == NULL)
    return set<const Ped::Tagent*>(agents.begin(), agents.end());

  // create the output list
  list<const Ped::Tagent*> neighborList;
  getNeighbors(neighborList, x, y, dist);

  // copy the neighbors to a set
  return set<const Ped::Tagent*>(neighborList.begin(), neighborList.end());
}
Пример #17
0
/**
 * \brief Given a node, this method expands the nearest node in a list, where the new expanded neighbor is the closest neighbor with respect to the given node.
 * \param[in] randomNode The reference node based on which the list should be expanded.
 * \param[in] closestNodeIndex The index of the closest node in the list to the randomNode.
 * \param[in,out] list The list of nodes that should be expanded for the closest node.
 * \param[in] map The grid map of the environment.
 * \return The connection node if both trees are connected, or NULL otherwise.
 */
AbstractNode * RRT::extendClosestNode(GridNode * const randomNode, GridNode * const closestNode,
		std::vector<AbstractNode *> & list, const GridMap& map,
		const std::vector<AbstractNode *> & otherList) const {

	// Nothing to do in this method - we've already implemented it for you :-)

	const std::vector<AbstractNode *> neighbors = getNeighbors(closestNode, list, map);
	AbstractNode * connectionNode = tryToConnect(closestNode, neighbors, otherList);
	if (connectionNode == NULL && !neighbors.empty()) {
		addNearestNeighbor(closestNode, neighbors, randomNode, list);
	}
	return connectionNode;
}
Пример #18
0
////////////
/// Everything below here relevant for Assignment 3.
/// Don't use this for Assignment 1!
///////////////////////////////////////////////
void Ped::Model::move( Ped::Tagent *agent)
{
  // Search for neighboring agents
  set<const Ped::Tagent *> neighbors = getNeighbors(agent->getX(), agent->getY(), 2);

  // Retrieve their positions
  std::vector<std::pair<int, int> > takenPositions;
  for (std::set<const Ped::Tagent*>::iterator neighborIt = neighbors.begin(); neighborIt != neighbors.end(); ++neighborIt) {
    std::pair<int,int> position((*neighborIt)->getX(), (*neighborIt)->getY());
    takenPositions.push_back(position);
  }

  // Compute the three alternative positions that would bring the agent
  // closer to his desiredPosition, starting with the desiredPosition itself
  std::vector<std::pair<int, int> > prioritizedAlternatives;
  std::pair<int, int> pDesired(agent->getDesiredX(), agent->getDesiredY());
  prioritizedAlternatives.push_back(pDesired);

  int diffX = pDesired.first - agent->getX();
  int diffY = pDesired.second - agent->getY();
  std::pair<int, int> p1, p2;
  if (diffX == 0 || diffY == 0)
  {
    // Agent wants to walk straight to North, South, West or East
    p1 = std::make_pair(pDesired.first + diffY, pDesired.second + diffX);
    p2 = std::make_pair(pDesired.first - diffY, pDesired.second - diffX);
  }
  else {
    // Agent wants to walk diagonally
    p1 = std::make_pair(pDesired.first, agent->getY());
    p2 = std::make_pair(agent->getX(), pDesired.second);
  }
  prioritizedAlternatives.push_back(p1);
  prioritizedAlternatives.push_back(p2);

  // Find the first empty alternative position
  for (std::vector<pair<int, int> >::iterator it = prioritizedAlternatives.begin(); it != prioritizedAlternatives.end(); ++it) {

    // If the current position is not yet taken by any neighbor
    if (std::find(takenPositions.begin(), takenPositions.end(), *it) == takenPositions.end()) {

      // Set the agent's position
      agent->setX((*it).first);
      agent->setY((*it).second);

      // Update the quadtree
      (*treehash)[agent]->moveAgent(agent);
      break;
    }
  }
}
Пример #19
0
 int main(int argc, char** argv){
   grid[1]="@----^---0";
   grid[2]="abcdefghi0";
   grid[3]="jklmnopqr0";//TODO Change to read of txt*/
   std::string* neighbors;
   for(int i=0;grid[1].length()>i;i++){
     neighbors=getNeighbors(2,1);
     if(neighbors[3]=="-" | neighbors[3]=="^"){
       std::string r=get(1,i);
       (r!="0") ? std::cout<<r:(bool)0;//Dangerous. TODO Unknown symbol handling
       std::cout<<neighbors[3];
     }
   }
 }
Пример #20
0
void Astar::run(){
 std::vector<Astar::node> openList;
 std::set<Astar::node> closedList;
 bool found = false;
 openList.push_back(*head);
 Astar::node temp;
 while( openList.size() > 0 ){//while openlist is not empty
    //temp = removeItemWithLowestCost(OpenList)
    //std::sort(openList.front(), openList.back(), comp);
    boost::sort(openList);
    temp = openList.back();
    openList.pop_back();

    //find goal condition
    if(temp == *target){
        target->previousNode = temp.previousNode;
        target->cost = temp.cost;
        found = true;
        break;
    }
    //iteration:
    else{
    //if temp not in closedList, add it
    if(closedList.count(temp) == 0){
        closedList.insert(temp);
    }
    //for each neighbor of temp
   std::vector<Astar::node> neighbors = getNeighbors(temp);
   for(auto & neighbor : neighbors){
        //add as child of temp
        temp.nextNodes.push_back(neighbor);
        //add to openlist
        openList.push_back(neighbor);
        }
    }
 }
if(found){
    //Goes up the tree from the target until it finds the starting position.
    Astar::node * temp = target;
    while (temp != nullptr) {
        path.push_back(*temp->currentPoint);
        temp = temp->previousNode;
    }
}
else{
    std::cout<< "No Path was Found" << std::endl;
}
}
Пример #21
0
void MolpherMol::MolpherMolImpl::lockAtom(int idx, int mask) {
    std::shared_ptr<MolpherAtom> atom = getAtom(idx);
    atom->setLockingMask(mask);
    mask = atom->getLockingMask();

    if (mask & (MolpherAtom::KEEP_NEIGHBORS | MolpherAtom::KEEP_BONDS)) {
        for (auto ngh : getNeighbors(idx)) {
            if (mask & MolpherAtom::KEEP_NEIGHBORS) {
                ngh->setLockingMask(ngh->getLockingMask() | MolpherAtom::NO_MUTATION | MolpherAtom::NO_REMOVAL);
            }
            if (mask & MolpherAtom::KEEP_BONDS) {
                ngh->setLockingMask(ngh->getLockingMask() | MolpherAtom::NO_REMOVAL);
            }
        }
    }
}
Пример #22
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);
        }
    }
}
Пример #23
0
vector<SuperpixelEdge> SuperpixelEdgeTable::getAllEdges()
{
  const bool debug = false;
  
  // Walk over all superpixels and get each neighbor, then create an edge only when the UID
  // of a superpixel is smaller than the UID of the edge. This basically does a dedup of
  // all the edges without creating and checking for dups.
  
  vector<SuperpixelEdge> allEdges;
  
  vector<int32_t> allSuperpixles = getAllTagsInNeighborsTable();
  
  for (vector<int32_t>::iterator it = allSuperpixles.begin(); it != allSuperpixles.end(); ++it ) {
    int32_t tag = *it;
    
    vector<int32_t> neighbors = getNeighbors(tag);
    
    if (debug) {
      cout << "for superpixel " << tag << " neighbors:" << endl;
    }
    
    for (vector<int32_t>::iterator neighborIter = neighbors.begin(); neighborIter != neighbors.end(); ++neighborIter ) {
      int32_t neighborTag = *neighborIter;

      if (debug) {
        cout << neighborTag << endl;
      }
      
      if (tag <= neighborTag) {
        SuperpixelEdge edge(tag, neighborTag);
        allEdges.push_back(edge);
        
        if (debug) {
          cout << "added edge (" << edge.A << "," << edge.B << ")" << endl;
        }
      } else {
        if (debug) {
          SuperpixelEdge edge(tag, neighborTag);
          
          cout << "ignored dup edge (" << edge.A << "," << edge.B << ")" << endl;
        }
      }
    }
  }
  
  return allEdges;
}
Пример #24
0
Handler::Handler(int wid, int hei) {
	
	width = wid;
	height = hei;
	
	for(int y = 0; y < hei; y++) {
		for(int x = 0; x < wid; x++) {
			Tile tile(x, y);
			tileMap.push_back(tile);
			//std::cout << x << ", " << y << '\n';
		}
	}
	
	for(auto i = tileMap.begin(); i != tileMap.end(); ++i) {
		getNeighbors(&*i);
	}	
}
Пример #25
0
void MapAnalyzer::CalcChokePoints() {
	for (int i = 0; i < mw; ++i) {
		for (int j = 0; j < mh; ++j) {
			auto nodeData = nodeMap[i][j];
			const auto &neighbors = getNeighbors(nodeData->pos);
			if (nodeData->value == maxDistance || nodeData->value >2 || nodeData->value == 0) continue;

			nodeData->inChokepoint = true;
			for (auto n : neighbors) {
				auto posData = getNode(n);
				if (posData->value > nodeData->value) {
					nodeData->inChokepoint = false;
					break;
				}
			}
		}
	}
}
Пример #26
0
KernelFunctions* HistogramOnGrid::getKernelAndNeighbors( std::vector<double>& point, unsigned& num_neigh, std::vector<unsigned>& neighbors ) const {
    if( discrete ) {
        plumed_assert( getType()=="flat" );
        num_neigh=1;
        for(unsigned i=0; i<dimension; ++i) point[i] += 0.5*dx[i];
        neighbors[0] = getIndex( point );
        return NULL;
    } else if( getType()=="flat" ) {
        KernelFunctions* kernel = new KernelFunctions( point, bandwidths, kerneltype, false, 1.0, true );
        getNeighbors( kernel->getCenter(), nneigh, num_neigh, neighbors );
        return kernel;
    } else {
        num_neigh = getNumberOfPoints();
        if( neighbors.size()!=getNumberOfPoints() ) neighbors.resize( getNumberOfPoints() );
        for(unsigned i=0; i<getNumberOfPoints(); ++i) neighbors[i]=i;
    }
    return NULL;
}
Пример #27
0
/** Calculate the the number of holes in the object o of the image i 
 * The function attempts to reverse the idea of sequential labeling 
 * in order to find black spots on objects
 * It still needs work.
 * TODO Make this work properly
 * */
void euler(Image *im, Object *o)
{
	int i, j, k, c, neighbors[NNEIGHB], 
		 newObj, left, right;

	LabelMap lm=makeLabelMap(im);

	/* this sets up a dummy class for background darkness */
	addLabel(&lm);
	for (i=0; i < getNRows(im); ++i)
		for (j=0; j < getNCols(im); ++j)
			if (!getPixel(im, i, j)) setLabel(&lm, i, j, 1);

	for (i=o->top; i <= o->bottom; ++i) {
		left=-1;
		for (j=o->left; j <= o->right; ++j) {
			if (getPixel(im, i, j) == o->label) {
				if (left < 0) left=j; /* left edge for this row */
				right=j; /* right-most so far */
			} 
		}
		for (j=left; j <= right; ++j) {
			if (!getPixel(im, i, j)) {
				newObj=getNeighbors(&lm, i, o->top, j, left, neighbors);
				if (newObj) {
					addLabel(&lm);
					c=getNLabels(&lm);
				} else {
					for (k=0; k < NNEIGHB; ++k)
						if (neighbors[k] > 0) {
							c=evalNeighbor(k, &lm, neighbors);
							break; /* break since finding one means checking the rest */
						}
				}
				setLabel(&lm, i, j, c);
			}
		}
	}

	o->holes=getNClasses(&lm)-1; /* number is off by one because of dummy class */
	freeLabelMap(&lm);
}
Пример #28
0
/**************************************************************************************************
 ** Function:       GameOfLife::createNextIteration()
 ** Description:    Takes the current iteration v and uses it and the 4 rules of the game to
 **                 create the next iteration of the cycle in vector nv.
 *************************************************************************************************/
void GameOfLife::createNextIteration(){
    for (int row = 0 ; row < rows ; row++){
        for (int column = 0 ; column < columns ; column++){
            int neighbors = getNeighbors(column,row);   //get number of neighbors
            char position = v.at(column).at(row);

            if (position == live){                      //rules 1-3
                if (neighbors < 2){                         //rule 1
                    nv.at(column).at(row) = dead; }
                else if (neighbors > 1 && neighbors < 4){   //rule 2
                    nv.at(column).at(row) = live; }
                else if (neighbors > 3){                    //rule 3
                    nv.at(column).at(row) = dead; }
            }   //end if
            else if (position == dead && neighbors == 3){   //rule 4
                nv.at(column).at(row) = live;
            }   //end else if | conditional
        }   //end for loop column
    }   //end for loop row
}
Пример #29
0
void graphSearch::BFS(int x)
{
  S.add(x,1);
  visited[x]=true;

  while(S.size())
    {
      x=S.get(S.size());
      S.remove(S.size());


      List p=getNeighbors(x);
      for(int i=1;i<p.size()+1;i++)
	if(!visited[p.get(i)])
	  {
	    S.add(p.get(i),1);
	    visited[p.get(i)]=true;
	  }
    }
}
void HillClimbingTransformOptimization::optimizeTransform(
		CalibrationState& calibrationState) {
	LtoState currentState, bestState;
	currentState.setCameraToHead(this->getInitialCameraToHead());
	currentState.error = calculateError(currentState);
	bestState.error = INFINITY;
	bool canImprove = true;
	int numOfIterations = 0;

	while (canImprove) {

		if (numOfIterations++ % 100 == 0) {
			//std::cout << currentState << std::endl;
		}

		std::vector<LtoState> neighbors = getNeighbors(currentState);
		LtoState bestNeighbor;
		bestNeighbor.error = INFINITY;

		// find the best neighbor
		for (int i = 0; i < neighbors.size(); i++) {
			LtoState currentNeighbor = neighbors[i];
			if (currentNeighbor.isBetterThan(bestNeighbor)) {
				bestNeighbor = currentNeighbor;
			}
		}

		// check whether the current best neighbor improves
		if (bestNeighbor.isBetterThan(currentState)) {
			currentState = bestNeighbor;
			stepwidth = 0.1;
		} else if (!decreaseStepwidth()) {
			canImprove = false;
		}
	}

	calibrationState.setCameraToHead(currentState.getCameraToHead());
	calibrationState.setHeadYawOffset(currentState.getHeadYawOffset());
	calibrationState.setHeadPitchOffset(currentState.getHeadPitchOffset());
}