Example #1
0
void turn()
{
	int i = 0;
	int j = 0;

	for (i = 0; i < height; i++)
	{
		for (j = 0; j < width; j++)
		{
			if (neighbors(i, j) == 3)
			{
				field_turn[i][j] = field[i][j] + 1;;
			}
			else if ((field[i][j] != 0) && (neighbors(i, j) == 2))
			{
				field_turn[i][j] = field[i][j] + 1;
			}
			else
			{
				field_turn[i][j] = 0;
			}
		}
	}

	int **field_swap = field;
	field = field_turn;
	field_turn = field_swap;
}
Example #2
0
bool MLNetwork::erase(const NodeSharedPtr& node) {
	// removing the node
	bool res = nodes.erase(node->id);
	sidx_nodes_by_layer[node->layer->id].erase(node->id);
	cidx_node_by_actor_and_layer[node->actor->id].erase(node->layer->id);

	// removing adjacent edges
	sorted_random_map<node_id,NodeSharedPtr> in = neighbors(node,IN);
	vector<EdgeSharedPtr> to_erase_in;
	to_erase_in.reserve(in.size());
	for (NodeSharedPtr node_in : in) {
		to_erase_in.push_back(get_edge(node_in,node));
	}
	for (EdgeSharedPtr edge : to_erase_in) {
		erase(edge);
	}
	sorted_random_map<node_id,NodeSharedPtr> out = neighbors(node,OUT);
	vector<EdgeSharedPtr> to_erase_out;
	to_erase_out.reserve(out.size());
	for (NodeSharedPtr node_out : out) {
		to_erase_out.push_back(get_edge(node,node_out));
	}
	for (EdgeSharedPtr edge : to_erase_out) {
		erase(edge);
	}
	// remove attribute values
	node_features(node->layer)->reset(node->id);
	return res;
}
void ViewSphereRender::initializeGL()
{
	QGLCanvas::initializeGL();

	//在球面上绘制视点移动轨迹时需要,防止轨迹与球面重合出现z-fighting的情况
	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(1, 1);

	// Generate view position
	long npix = nside2npix(m_nside);
	double theta,phi;
	for(int i = 0; i < npix; ++i) {
		pix2ang_ring(m_nside, i, &theta, &phi);
		ViewPoint pos(theta, phi, 0.0);
		ang2vec(theta, phi, pos.coord);
		m_viewSphere.vViewPos.push_back(pos);
	}
	printf("View position count = %d\n", m_viewSphere.vViewPos.size());

	int array[8];
	//生成顶点之间的link
	for(int i = 0; i < npix; i++)
	{
		neighbors(m_nside, i, array, 0);
		for(int j = 0; j < 8; j += 2) {
			if(array[j] > i) 
				m_viewSphere.links.push_back(make_pair(i, array[j]));
		}
	}

	// Generate mesh from vertices
	// 生成球面模型
	vector<ViewPoint>& vp = m_viewSphere.vViewPos;
	m_viewSphere.vTris.push_back(Vector3i(0, 1, 2)); // 北极点的两个三角形
	m_viewSphere.vTris.push_back(Vector3i(0, 2, 3));
	m_viewSphere.vTris.push_back(Vector3i(npix - 1, npix - 2, npix - 3)); // 南极点的两个三角形
	m_viewSphere.vTris.push_back(Vector3i(npix - 1, npix - 3, npix - 4));
	for(int i = 0; i < npix; i++)
	{
		neighbors(m_nside, i, array, 0);

		if (array[4] >= 0 && array[5] >= 0 && array[6] >= 0)
		{
			m_viewSphere.vTris.push_back(Vector3i(i, array[6], array[5]));
			m_viewSphere.vTris.push_back(Vector3i(i, array[5], array[4]));
		} else {
			m_viewSphere.vTris.push_back(Vector3i(i, array[6], array[4]));
		}
 	}

// 	m_currentPos = &(m_viewSphere.vViewPos[0]);
// 
// 	long ipix;
// 	Vector4d p0(1.0, 0.5, 0.0, 1.0);
// 	vec2pix_ring(m_nside, (double*)&p0, &ipix);
// 	moveFromTo(m_currentPos, &(m_viewSphere.vViewPos[ipix]));
}
Example #4
0
ElimGraph::ElimGraph (const vector<Factor*>& factors)
{
  for (size_t i = 0; i < factors.size(); i++) {
    if (factors[i] == 0) { // if contained just one var with evidence
      continue;
    }
    const VarIds& vids = factors[i]->arguments();
    for (size_t j = 0; j < vids.size() - 1; j++) {
      EgNode* n1 = getEgNode (vids[j]);
      if (n1 == 0) {
        n1 = new EgNode (vids[j], factors[i]->range (j));
        addNode (n1);
      }
      for (size_t k = j + 1; k < vids.size(); k++) {
        EgNode* n2 = getEgNode (vids[k]);
        if (n2 == 0) {
          n2 = new EgNode (vids[k], factors[i]->range (k));
          addNode (n2);
        }
        if (neighbors (n1, n2) == false) {
          addEdge (n1, n2);
        } 
      }
    }
    if (vids.size() == 1) {
      if (getEgNode (vids[0]) == 0) {
        addNode (new EgNode (vids[0], factors[i]->range (0)));
      }
    }
  }
}
void ExtractNeighborsWorkflow::run()
{
    const reference::SortedReferenceMetadata::MaskFiles &maskFiles =
        xml_.getMaskFileList(oligo::KmerTraits<KmerT>::KMER_BASES);
    if (maskFiles.empty())
    {
        BOOST_THROW_EXCEPTION(isaac::common::PreConditionException("No mask files in " + sortedReferenceMetadata_.string()));
    }

    const reference::SortedReferenceMetadata::Contigs contigs = xml_.getKaryotypeOrderedContigs();
    const std::vector<unsigned long> contigOffsets = reference::computeContigOffsets(contigs);
    std::vector<bool> neighbors(reference::genomeLength(contigs), false);
    std::vector<bool> highRepeats(highRepeatsFilePath_.empty() ? 0 : reference::genomeLength(contigs), true);

    // there could be mutliple mask widths in the xml. Just pick one.
    const unsigned maskWidth = xml_.getDefaultMaskWidth();

    BOOST_FOREACH(const reference::SortedReferenceMetadata::MaskFile &maskFile, maskFiles)
    {
        //Don't reprocess redundant mask files of different widths
        if (maskWidth == maskFile.maskWidth)
        {
            scanMaskFile<KmerT>(maskFile, contigOffsets, neighbors, highRepeats);
        }
    }

    dumpResults(neighbors, highRepeats);
}
Example #6
0
 bool save_metis_structure(const std::string& filename,
                           const graphlab::local_graph<VertexType, EdgeType>& graph) {
   typedef graphlab::local_graph<VertexType, EdgeType> graph_type;
   typedef typename graph_type::edge_type          edge_type;
   typedef typename graph_type::edge_list_type     edge_list_type;
 
   std::ofstream fout(filename.c_str());
   if(!fout.good()) return false;
   // Count the number of actual edges
   size_t nedges = 0;
   for(vertex_id_type i = 0; i < graph.num_vertices(); ++i)
     nedges += num_neighbors(graph, i);
   fout << graph.num_vertices() << ' ' << (nedges/2) << '\n';
   // Save the adjacency structure
   std::vector<vertex_id_type> neighbor_set;
   for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {
     neighbors(graph, i, neighbor_set);
     for(size_t j = 0; j < neighbor_set.size(); ++j) {
       fout << (neighbor_set[j] + 1);
       if(j + 1 < neighbor_set.size()) fout << ' ';
     }
     fout << '\n';
   }
   fout.close();
   return true;
 } // end of save metis
game* evolve(game* g) {
	
	game* next = clone_game(g); //Clone game for evolution

	int i, j, neighbor_cnt; 
	for (i = 0; i < g->rows; i++) {
		for (j = 0; j < g->cols; j++) {
			neighbor_cnt = neighbors(g, i, j); 			
			if (g->board[i][j] == ALIVE) { //ALIVE case
				if (neighbor_cnt == 2 || neighbor_cnt ==3) {
					; //Do nothing, stays alive
				}
				else {
					next->board[i][j] = DEAD; //Else it dies
				}
			}
			else { //DEAD case
				if (neighbor_cnt == 3) { //If it has 3 living neighbors, it comes back to life
					next->board[i][j] = ALIVE; 
				}
			}
		}
	}

	return next; 
}
Example #8
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);
				}

			}
		}
	}
    void neighbor_mark( MeshT const & mesh, UnvisitedCellMapT & unvisitied_cells )
    {
      bool found = true;
      while (found)
      {
        found = false;

        for (typename UnvisitedCellMapT::iterator ucit = unvisitied_cells.begin(); ucit != unvisitied_cells.end(); )
        {
          typedef typename viennagrid::result_of::cell_tag<MeshT>::type CellTagType;
          typedef typename viennagrid::result_of::facet_tag<MeshT>::type FacetTagType;
          typedef typename viennagrid::result_of::const_neighbor_range<MeshT, CellTagType, FacetTagType>::type NeighborRangeType;
          typedef typename viennagrid::result_of::iterator<NeighborRangeType>::type NeighborIteratorType;

          NeighborRangeType neighbors( mesh, ucit->second );
          NeighborIteratorType ncit = neighbors.begin();
          for (; ncit != neighbors.end(); ++ncit)
          {
            typename UnvisitedCellMapT::iterator ucit2 = unvisitied_cells.find( ncit->id() );
            if (ucit2 == unvisitied_cells.end())
              break;
          }

          if (ncit != neighbors.end())
          {
            found = true;
            unvisitied_cells.erase( ucit++ );
          }
          else
            ++ucit;
        }
      }
    }
Example #10
0
void follow_tail(void)
{
  --snake_length_current;
  //is tail a neighbor of next?
  if (neighbors(corners[tail],corners[get_next_node(tail)]))
  {
    tail = get_next_node(tail);
  }
  
  //find which axis tail and next have in common
  else
  {
    if (corners[tail].x == corners[get_next_node(tail)].x)
    {
      //These points have the same X, so make adjustment to the Y
      if ((corners[tail].y - corners[get_next_node(tail)].y) < 0) corners[tail].y += 1;
      else corners[tail].y -= 1; 
    }
    else
    {
      //These points have the same Y, so make adjustment to the X
      if ((corners[tail].x - corners[get_next_node(tail)].x) < 0) corners[tail].x += 1;
      else corners[tail].x -= 1; 
    }
  }
}
ViewPoint* ViewSphereRender::nextPointNearest( const ViewPoint* fromPoint, const ViewPoint* toPoint )
{
	int array[8];
	long fromIdx, toIdx;
	ang2pix_ring(m_nside, fromPoint->theta, fromPoint->phi, &fromIdx);
	neighbors(m_nside, fromIdx, array, 0);

	ViewPoint* result = NULL;
	ViewPoint* ptr = NULL;
	Vector3d p0(fromPoint->coord[0], fromPoint->coord[1], fromPoint->coord[2]);
	Vector3d p1(toPoint->coord[0], toPoint->coord[1], toPoint->coord[2]);
	Vector3d v0 = (p1 - p0).normalize();
	Vector3d v1;
	double maxCosValue = -1.0;
	double dotProduct;
	
	for (int i = 0; i < 8; ++i)
	{
		if (array[i] >= 0)
		{
			ptr = &(m_viewSphere.vViewPos[array[i]]);
			Vector3d p2(ptr->coord[0], ptr->coord[1], ptr->coord[2]);
			v1 = (p2 - p0).normalize();
			dotProduct = Dot(v0, v1);
// 			//用测地线距离来取最近点
// 			dotProduct2 = Dot(p1, p2); 
			if (dotProduct > maxCosValue)
			{
				maxCosValue = dotProduct;
				result = ptr;
			}
		}
	}
	return result;
}
Example #12
0
 void neighbors(const Graph& g, 
                VertexIterator first, VertexIterator last,
                OutputIterator result)
 {
   for (; first != last; ++first)
     neighbors(g, *first, result);
 }
Example #13
0
void
Graph::display() {
/*  for (unsigned int node=0 ; node<nb_nodes ; node++) {
    pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
    for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
      if (node<=*(p.first+i)) {
	if (weights.size()!=0)
	  cout << node << " " << *(p.first+i) << " " << *(p.second+i) << endl;
	else
	  cout << node << " " << *(p.first+i) << endl;
      }
    }   
  }*/
  for (unsigned int node=0 ; node<nb_nodes ; node++) {
    pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
    cout << node << ":" ;
    for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
      if (true) {
	if (weights.size()!=0)
	  cout << " (" << *(p.first+i) << " " << *(p.second+i) << ")";
	else
	  cout << " " << *(p.first+i);
      }
    }
    cout << endl;
  }
}
Example #14
0
void
Graph::add_selfloops() {
  vector<unsigned long long> aux_deg;
  vector<int> aux_links;

  unsigned long long sum_d = 0ULL;

  for (int u=0 ; u < nb_nodes ; u++) {
    pair<vector<int>::iterator, vector<long double>::iterator> p = neighbors(u);
    int deg = nb_neighbors(u);

    for (int i=0 ; i < deg ; i++) {
      int neigh = *(p.first+i);
      aux_links.push_back(neigh);
    }

    sum_d += (unsigned long long)deg;

    if (nb_selfloops(u) == 0.0L) {
      aux_links.push_back(u); // add a selfloop
      sum_d += 1ULL;
    }

    aux_deg.push_back(sum_d); // add the (new) degree of vertex u
  }

  links = aux_links;
  degrees = aux_deg;
  
  nb_links += (unsigned long long)nb_nodes;
}
inline cv::Mat computeLBPImage_(cv::Mat& src)
{
	cv::Mat dst = cv::Mat::zeros(src.size(), CV_8UC1);
	for (int i = 1; i < src.rows - 1; ++i)
    {
        for (int j = 1; j < src.cols - 1; ++j)
        {
            std::vector<Elem> neighbors(8);
            neighbors[0] = src.at<Elem>(i,     j + 1);
            neighbors[1] = src.at<Elem>(i + 1, j + 1);
            neighbors[2] = src.at<Elem>(i + 1, j);
            neighbors[3] = src.at<Elem>(i + 1, j - 1);
            neighbors[4] = src.at<Elem>(i,     j - 1);
            neighbors[5] = src.at<Elem>(i - 1, j - 1);
            neighbors[6] = src.at<Elem>(i - 1, j);
            neighbors[7] = src.at<Elem>(i - 1, j + 1);
            Elem c = src.at<Elem>(i, j);
            Word word = 0;
            for (size_t k = 0; k < neighbors.size(); ++k)
            {
                if (k > 0)
                    word = word << 1;
                unsigned char bit = neighbors[k] > c;
                word |= bit;
            }
            dst.at<Word>(i, j) = word;
        }
    }
    return dst;
};
Example #16
0
void game_of_life() {
    int x;
    int y;
    for (x = 0; x < SW_VGA_WIDTH; ++x) {
        for (y = 0; y < SW_VGA_HEIGHT; ++y) {
            int n = neighbors(old_img_addr, x, y);
            /* if is alive */
            if (get_pixel(old_img_addr, x, y)) {
                /* underpopulation or overcrowding: die */
                if ((n < 2) || (n > 3)) {
                    set_pixel(new_img_addr, x, y, 0);
                } else {
                    set_pixel(new_img_addr, x, y, 1);
                }
            } else {
                /* perfect conditions: become alive */
                if (n == 3) {
                    set_pixel(new_img_addr, x, y, 1);
                } else {
                    set_pixel(new_img_addr, x, y, 0);
                }
            }
        }
    }
}
Example #17
0
vector<SplitEdge> evenSplit(const vector<SplitEdge> &g, int s, int k, historyIndex &h) 
{
	vector<SplitEdge> G = g;
	vector<vector<int>> X;
	vector<int> ns = neighbors(G, s);
	for (unsigned i = 0; i < ns.size(); i++)
	{
		vector<int> cur;
		cur.push_back(ns[i]);
		X.push_back(cur);
	}
	vector<SplitEdge>B;
	while (X.size() != 0)
	{

		vector<SplitEdge> G1 = eulerCSplit(G, B, s, k, X, h);
		G1 = removeZeroWeighted(G1);
		/*if (cG(s, G) / 2 != magnitude(B))
		{
			cout << "Error: |B| and cG(s)/2 should be the same after C Split" << endl;
			cout << "cG(s, G) /2: " << cG(s, G)/2 << endl;
			cout << "|B|: " << magnitude(B) << endl;
			throw logic_error("");
		}*/
		vector<vector<int>> Y;
		huReturn hookUpOut = hookUp(G1, s, B, k, Y, h);
		vector<SplitEdge> G2 = hookUpOut.G1;
		Y = hookUpOut.Y;
		B = hookUpOut.BP;
		G = G2;
		X = Y;
	}
	return G;
}
void CellGrid::full_neighbors(loc l, vector<loc>& full_n) {
    full_n.clear();
    vector<loc> n;
    neighbors(l, n);
    for (vector<loc>::iterator i = n.begin(); i != n.end(); ++i) {
        if (get(*i) != EM)
            full_n.push_back(*i);
    }
}
Example #19
0
size_t Graph::edgeCount() const
{
  size_t count = 0;

  for (size_t i = 0; i < size(); ++i)
    count += neighbors(i).size();

  return count / 2;
}
Example #20
0
bool Graph::containsEdge(size_t a, size_t b) const
{
  assert(a < size());
  assert(b < size());

  const std::vector<size_t>& neighborsA = neighbors(a);

  return std::find(neighborsA.begin(), neighborsA.end(), b) != neighborsA.end();
}
Example #21
0
shared_ptr<vector<PSchedule>> Schedule :: neighboringSchedules
(NeighborhoodType neighborhoodType,
 function<PVectorJobs(PARAMETERS_OF_SELECTING_FUNCTION)> &functionForSelecting)
{
#warning Is it right? Are we needs to construct correct schedule first?
#warning numberOfGeneratedSchedules needs to be ++ here?
    PSchedule schedule = nullptr;
    switch (neighborhoodType) {
        case NeighborhoodTypeEarly: {
            if (_type == ScheduleTypeEarly) schedule = shared_from_this();
            else schedule = earlySchedule();
            break;
        }
        case NeighborhoodTypeLate: {
            if (_type == ScheduleTypeLate) schedule = shared_from_this();
            else schedule = lateSchedule();
            break;
        }
    }
    
    shared_ptr<vector<PSchedule>> neighbors(new vector<PSchedule>(0));
    neighbors->reserve(schedule->activeList()->size());
    
    for (Job *job : *schedule->activeList()->jobList()) {
        PSchedule neighbor = nullptr;
        switch (schedule->type()) {
            case ScheduleTypeEarly: {
                neighbor = schedule->neighborForEarlySchedule(job, functionForSelecting);
                break;
            }
            case ScheduleTypeLate: {
                neighbor = schedule->neighborForLateSchedule(job, functionForSelecting);
                break;
            }
            default: {
                
                cout << "Error. Incorrect schedule type. See neighboringSchedules(neighborhoodType, &functionForSelecting) function of Schedule"
                << endl;
                
                cout << "neighborhoodType = " << neighborhoodType << endl;
                
                cout << "this = " << *this << endl;
                cout << "this MATLAB string = " << this->stringMATLAB() << endl;
                
                cout << "schedule = " << *schedule << endl;
                cout << "schedule MATLAB string = " << schedule->stringMATLAB() << endl;
                
                abort();
                break;
            }
        }
        if (neighbor) neighbors->push_back(neighbor);
    }
    
    return neighbors;
}
Example #22
0
/* Synthetic Minority Over-sampling Technique */
cv::Mat SMOTE::smote(cv::Mat minority, int amountSmote, int nearestNeighbors) {
  cv::Size s = minority.size();
  int samples, pos, index = 0;
  int minoritySamples = s.height;
  int attributes = s.width;
  std::vector<int> vectorRand;
  cv::Mat newMinority;
  if (amountSmote == 0) return cv::Mat();

  std::cout << "\n---------------------------------------------------------" << std::endl;
  std::cout << "SMOTE generation of samples to rebalance classes" << std::endl;
  std::cout << "---------------------------------------------------------" << std::endl;

  // The first neighbor is the sample itself
  nearestNeighbors =  nearestNeighbors + 1 < minority.rows ? nearestNeighbors + 1 : minority.rows;

  minoritySamples = amountSmote;
  newMinority.create(minoritySamples, attributes, CV_32FC1);
  samples = 0;
  /* If amount to smote is less than 100%, randomize the minority class
  samples as only a random percent of them will be SMOTEd */
  if (amountSmote < s.height) {
    while (samples < minoritySamples) {
      /* Generate a random position for the minority class samples */
      pos = rand() % (s.height);
      if (!count(vectorRand.begin(), vectorRand.end(), pos)) {
        vectorRand.push_back(pos);
        cv::Mat tmp = newMinority.row(samples);
        minority.row(pos).copyTo(tmp);
        samples++;
      }
    }
    minority = newMinority;
  }

  cv::Mat synthetic(amountSmote, attributes, CV_32FC1);
  cv::Mat neighbors(minoritySamples, nearestNeighbors, CV_32FC1);

  /* Compute all the neighbors for the minority class */
  computeNeighbors(minority, nearestNeighbors, &neighbors);

  /* For each sample, generate it(s) synthetic(s) sample(s) */
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(0, minority.rows-1);

  while (amountSmote > 0) {
    // Mat minority, Mat neighbors, Mat *synthetic, int *index, int amountSmote, int i, int nearestNeighbors)

    populate(minority, neighbors, &synthetic, &index, 1, dis(gen), nearestNeighbors);
    amountSmote--;
  }
  return synthetic;
}
Example #23
0
void PrimMaze::moveNeighbors(const QPoint& cell)
{
	QList<QPoint> n = neighbors(cell);
	for (int i = 0; i < n.size(); ++i) {
		const QPoint& current = n.at(i);
		int& ref = m_regions[current.x()][current.y()];
		if (ref == 0) {
			ref = 1;
			m_frontier.append(current);
		}
	}
}
Example #24
0
    int Graph::fuse_vertices(int u, int v, bool contract_edge = false){
        int i;
        if(simple != true){
            fatal_error("%s: called on a non-simple graph!\n", __FUNCTION__);
        }
        if((nodes[u].label == -1) || (nodes[v].label == -1) ){
            fatal_error(
                "%s: Cannot remove edge (%d, %d) as one of its vertices is undefined!\n",
                __FUNCTION__, u, v);
        }
        vector<bool> neighbors(capacity);
        fill(neighbors.begin(), neighbors.end(), false);
        list<int>::iterator it;

        if(v == u){ //maybe don't need this
            return false;
        }

        bool foundv = false;
        for(it = nodes[u].nbrs.begin(); it != nodes[u].nbrs.end(); ++it){
            neighbors[*it] = true;
            if(*it == v){
                foundv = true;
            }
        }

        if(contract_edge){ // for fuse_vertices alone, don't need to be neighbours. for contract_edge you do
            if(foundv == false){
                return false;
            }
        }

        for(it = nodes[v].nbrs.begin(); it != nodes[v].nbrs.end(); ++it){
            neighbors[*it] = true;
        }
        remove_vertex(u);
        remove_vertex(v);
        nodes[u].label = next_label;
        next_label++;
        num_nodes++;
        for(i = 0; i < capacity; i++){
            if((i != u) && (i != v) ){
                if(neighbors[i] == true){
                    nodes[i].nbrs.push_back(u);
                    nodes[u].nbrs.push_back(i);
                    degree[u]++;
                    degree[i]++;
                    num_edges++;
                }
            }
        }
        return u;
    } // fuse_vertices
Example #25
0
void Graph::findNTuples(const edge_callback &tuple_callback,
                        const path_len_2_callback &triple_callback,
                        const path_len_3_callback &quadruple_callback) {
    for (auto &v : _vertices) {
        v.visited = false;
    }

    for (auto it = _vertices.begin(); it != _vertices.end(); ++it) {
        it->visited = true;
        auto v_type = it->particleType();
        auto v_idx = it->particleIndex;
        auto &neighbors = it->neighbors();
        for (auto it_neigh : neighbors) {
            auto vv_type = it_neigh->particleType();
            auto vv_idx = it_neigh->particleIndex;
            if (!it_neigh->visited) {
                log::trace("got type tuple ({}, {}) for particles {}, {}", v_type, vv_type, v_idx, vv_idx);
                // got edge (v, vv), now look for N(v)\{vv} and N(vv)\(N(v) + v)
                tuple_callback(std::tie(it, it_neigh));
                for (auto quad_it_1 : neighbors) {
                    // N(v)\{vv}
                    if (it_neigh != quad_it_1) {
                        auto vvv_type = quad_it_1->particleType();
                        auto vvv_idx = quad_it_1->particleIndex;
                        // got one end of the quadruple
                        for (auto quad_it_2 : it_neigh->neighbors()) {
                            // if this other neighbor is no neighbor of v and not v itself,
                            // we got the other end of the quadruple
                            auto no_circle =
                                    std::find(neighbors.begin(), neighbors.end(), quad_it_2) == neighbors.end();
                            if (quad_it_2 != it && no_circle) {
                                auto vvvv_type = quad_it_2->particleType();
                                auto vvvv_idx = quad_it_2->particleIndex;
                                log::trace("got type quadruple ({}, {}, {}, {}) for particles {}, {}, {}, {}", vvv_type, v_type,
                                           vv_type, vvvv_type, vvv_idx, v_idx, vv_idx, vvvv_idx);
                                quadruple_callback(std::tie(quad_it_1, it, it_neigh, quad_it_2));
                            }
                        }
                    }
                }
            }
            for (auto it_neigh2 : neighbors) {
                if (it_neigh2 != it_neigh && it_neigh->particleIndex < it_neigh2->particleIndex) {
                    auto vvv_type = it_neigh2->particleType();
                    auto vvv_idx = it_neigh2->particleIndex;
                    log::trace("got type triple ({}, {}, {}) for particles {}, {}, {}", vv_type, v_type, vvv_type,
                               vv_idx, v_idx, vvv_idx);
                    triple_callback(std::tie(it_neigh, it, it_neigh2));
                }
            }
        }
    }
}
Example #26
0
// Detect contiguous terrain tiles and store them in the regions list
void HexMap::findRegions()
{
	// new tiles to query
	multimap<int, sf::Vector2i> frontier;
	int i = (int)(mapSize_.x*mapSize_.y);
	HexTile* h = nullptr;
	sf::Vector2i p;
	std::unique_ptr<bool> seen(new bool[i]);
	for (int a = 0; a < i; a++) {
		seen.get()[a] = false;
	}
	std::deque<sf::Vector2i> peaks;
	std::deque<Region> regions;

	Region* currentRegion;
	for (int r = 0; r < mapSize_.y; r++) {
		for (int q = 0, qoff = (int)-floor(r / 2.0); q < mapSize_.x; q++, qoff++) {
			i = q + mapSize_.x * r;
			if (seen.get()[i]) {
				continue;
			}
			regions.emplace_back(1, sf::Vector2i(qoff, r));
			currentRegion = &regions.back();
			h = &getAxial(qoff, r);
			frontier.insert(make_pair(0, sf::Vector2i(qoff, r)));
			VectorSet adj;
			while (!frontier.empty()) {
				for (auto f : frontier) {
					clipToBounds(neighbors(f.second, adj));
				}
				frontier.clear();
				for (auto n : adj) {
					p = axialToOffset(n);
					i = p.x + p.y * mapSize_.x;
					if (seen.get()[i]) {
						continue;
					}
					HexTile& t = getAxial(n.x, n.y);
					if (t.height >= 200) {
						peaks.push_back(n);
					}
					if (t.hts == h->hts) {
						frontier.insert(make_pair(0, n));
						seen.get()[i] = true;
						(*currentRegion).size++;
					}
				}
				adj.clear();
			}
		}
	}
}
Example #27
0
int main( int argc, char** argv ) {

    int numtasks = 0; 
 
    MPI_( MPI_Init( &argc, &argv ) );
    MPI_( MPI_Errhandler_set( MPI_COMM_WORLD, MPI_ERRORS_RETURN ) );
    MPI_( MPI_Comm_size( MPI_COMM_WORLD, &numtasks ) );
    
    const int DIM = int( std::sqrt( double( numtasks ) ) );
    std::vector< int > dims( 2, DIM );
    std::vector< int > periods( 2, 0 ); //periodic - false -> non-periodic
    const int reorder = 0; //false - no reorder
    MPI_Comm cartcomm;
    MPI_( MPI_Cart_create( MPI_COMM_WORLD, 2, &dims[ 0 ], &periods[ 0 ], reorder, &cartcomm ) ); 
    int task = -1;
    MPI_( MPI_Comm_rank( cartcomm, &task ) );
    std::vector< int > coords( 2, -1 );
    MPI_( MPI_Cart_coords( cartcomm, task, 2, &coords[ 0 ] ) );
     
    std::vector< int > neighbors( 4, -1 );
    enum { UP = 0, DOWN, LEFT, RIGHT };
    // compute the shifted source and destination ranks, given a shift direction and amount
    //MPI_Cart_shift is uses to find two "nearby" neighbors of the calling process
    //along a specified direction of an N-dimensional grid
    //The direction and offset are specified as a signed integer
    //If the sign of the displacement is positive the "source" rank is lower
    //than the destination rank; if it's negative the opposite is true 
    MPI_( MPI_Cart_shift( cartcomm, 0, 1, &neighbors[ UP ],   &neighbors[ DOWN ] ) );
    MPI_( MPI_Cart_shift( cartcomm, 1, 1, &neighbors[ LEFT ], &neighbors[ RIGHT ] ) );
    int sendbuf = task;
    const int tag = 0x01;
    std::vector< int > recvbuf( 4, MPI_PROC_NULL ); 
    std::vector< MPI_Request > reqs( 2 * 4 );
    for( int i = 0; i != 4; ++i ) {
        int dest = neighbors[ i ];
        int src  = neighbors[ i ];
        MPI_( MPI_Isend( &sendbuf, 1, MPI_INT, dest, tag, MPI_COMM_WORLD, &reqs[ i ] ) );
        MPI_( MPI_Irecv( &recvbuf[ i ], 1, MPI_INT, src, tag, MPI_COMM_WORLD, &reqs[ i + 4 ] ) );
    }
    std::vector< MPI_Status  > status( 2 * 4 ); 
    MPI_( MPI_Waitall( 8, &reqs[ 0 ], &status[ 0 ] ) );

    std::ostringstream os;
    os << "rank= " << task << " coords= " << coords[ 0 ] << ',' << coords[ 1 ]
       << " neighbors= " << neighbors[ UP ] << ',' << neighbors[ DOWN ] << ','
       << neighbors[ LEFT ] << ',' << neighbors[ RIGHT ] << '\n';
    std::cout << os.str(); os.flush();
 
    MPI_( MPI_Finalize() );
    
    return 0;
}
Example #28
0
bool turfield::step(int steps){

	for(int i=0;i<n_pole;i++){
		for(int j=0;j<n_pole;j++){
			area_t[i][j]=area[i][j];
		}	
	}
	for(int i=0;i<n_pole;i++){
		for(int j=0;j<n_pole;j++){
//			switch(area[i][j]){
//				case 0:{
//					if(neighbors(i,j,1)==2)
//						area[i][j]=1;
//				}break; 
//				
//				case 1:{
//					int neighb=neighbors(i,j,1);
//					if(!(neighb==3||neighb==4||neighb==5))
//						area[i][j]=2;
//				}break;
//				
//				case 2:{
//					int neighb=neighbors(i,j,2);
//					if(!(neighb==3||neighb==4||neighb==5))
//						area[i][j]=3;
//				}break; 
//				
//				case 3:{
//					int neighb=neighbors(i,j,3);
//					if(!(neighb==3||neighb==4||neighb==5))
//						area[i][j]=0;
//				}break;
//			}
			for(int k=0;k<brain.size();k++){
				if(area_t[i][j]==brain[k].color){
					int neighs=neighbors(i,j,brain[k].neigh_color);
					if((find_cifr(brain[k].n_neigh,
					neighs)^brain[k].n_neigh[0]=='!')||
					((brain[k].n_neigh=="-1"&&neighs>0)
					||brain[k].neigh_color==-1)){
						area[i][j]=brain[k].new_color;
						break;
					}
				}else
					continue;
			}
		}
	}

	return 1;
}
std::vector<cv::RotatedRect> RandomFeatureFinder::removeIntersectingEllipses( const std::vector<cv::RotatedRect>& ellipses )
{
    // init stuff
    std::vector<cv::RotatedRect> result;

    // init flann
    cv::Mat_<double> centersCV( static_cast<int>(ellipses.size()), 2 );
    for( size_t i=0; i<ellipses.size(); i++ )
    {
        centersCV( i, 0 ) = ellipses[i].center.x;
        centersCV( i, 1 ) = ellipses[i].center.y;
    }
    cv::flann::GenericIndex< cv::flann::L2_Simple<double> > flann( centersCV, cvflann::KDTreeIndexParams(5) );

    // run over all points and look at the neighbors
    for( size_t i=0; i<ellipses.size(); i++ )
    {
        // get the 5 nearest neighbors of this elipse' center
        cv::Mat_<int> neighbors( 1, 5+1 );
        cv::Mat_<double> dists( 1, 5+1 );
        flann.knnSearch( centersCV.row(i).clone(), neighbors, dists, 5+1, cvflann::SearchParams(128) );
        bool skip = false;

        // have a look at the neighbors
        // if not first point in a "dense cluster", skip
        double rMax = std::max( ellipses[i].size.width, ellipses[i].size.height );
        for( size_t n=1; n<=5; n++ )
            if( dists(n) < rMax && neighbors(n) < i )
                skip = true;

        // if all went well, add the ellipse
        if( !skip )
            result.push_back( ellipses[i] );
    }

    // return
    return result;
}
Example #30
0
void
Graph::display_reverse() {
  for (unsigned int node=0 ; node<nb_nodes ; node++) {
    pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
    for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
      if (node>*(p.first+i)) {
	if (weights.size()!=0)
	  cout << *(p.first+i) << " " << node << " " << *(p.second+i) << endl;
	else
	  cout << *(p.first+i) << " " << node << endl;
      }
    }   
  }
}