Exemplo n.º 1
0
void GameBoard::stepSystem(){
    int x, y;
    int count;
    int value;

    for(x = 0; x < width; x++){
        for(y = 0; y < height; y++){
            count = numNeighbors(x, y);    
            value = getCell(x, y);
            
            if( value == ALIVE ) {
                if( count < 2 || count > 3 ){
                    putCellSwap(x, y, DEAD);
                }else{
		    putCellSwap(x, y, value);
		}
            } 
            else {
                if( count == 3 ){
                    putCellSwap(x, y, ALIVE);
                }else{
		    putCellSwap(x, y, value);
		}
            }
        }
    }

    swap();
}
Exemplo n.º 2
0
// The old version of this was recursing directly and deeply, leading to stack
// overflows in stack restricted environments (e.g. multithreading).  The
// current version is a fairly direct iteratization of the old, directly
// recursive version.
void
Skeletonize::traverse(const GraphVolume::Node& root, Skeleton& skeleton) {
	// DFS of nodes from root.  Data-wise, Nodes are just integer values.
	std::stack<GraphVolume::Node> traversal;
	traversal.push(root);
	while (!traversal.empty()) {
		const GraphVolume::Node n = traversal.top();
		const int nNeighbors = numNeighbors(n);

		// Special nodes that open new segments.
		const bool isOpeningNode = n == _root || nNeighbors != 2;

		// The second time we see a node, we are in back-traversal, popping from
		// traversal stack and potentially closing segments.
		if (_nodeLabels[n] == Visited) {
			if (isOpeningNode) skeleton.closeSegment();
			traversal.pop();
			continue;
		}

		// Otherwise, we're seeing the node for the first time, so opening /
		// extending segment.
		_nodeLabels[n] = Visited;
		const Position pos = _graphVolume.positions()[n];
		const float boundDist = sqrt(boundaryDistance(pos));
		if (isOpeningNode) {
			skeleton.openSegment(pos, 2*boundDist);
		} else {
			skeleton.extendSegment(pos, 2*boundDist);
		}

		// Iterate through neighbors and put unseen ones onto traversal stack.  The
		// loop checks against nNeighbors to allow early termination.
		GraphVolume::IncEdgeIt e(_graphVolume.graph(), n);
		for (int i = 0; i < nNeighbors; ++e /* increment e, not i */) {
			assert(e != lemon::INVALID);  // Should never occur.

			// Only increment i if we are using this edge.
			if (_distanceMap[e] != 0.0) continue;
			++i;

			const GraphVolume::Node neighbor = (_graphVolume.graph().u(e) == n ? _graphVolume.graph().v(e) : _graphVolume.graph().u(e));
			if (_nodeLabels[neighbor] != Visited) traversal.push(neighbor);
		}
	}
}
Exemplo n.º 3
0
void evolve(int x, int y, int rows, int cols, char *newBoard, char *refBoard,
    char *argv[], int numCoords, int iters) {
  /*
   * Purpose: Examines the board and applies the rules of the Game of Life
   * Inputs: Coordinates:            x, y
   *         Rows & Columns:         rows, cols
   *         Game board:             board
   *         Command-line arguments: argv[]
   *         Number of coordinates:  numCoords
   *         Number of iterations:   iters
   * Returns: Nothing
   */ 
  
  //char *newBoard = copyBoard(board, rows, cols);
  
  for(x = 0; x < rows; x++) {
    for(y = 0; y < cols; y++) {
      int neighbors = numNeighbors(x, y, rows, cols, refBoard, numCoords);
      //printf("Point (%d,%d) has %d neighbors\n",x,y,neighbors);
      if (neighbors < 0 || neighbors > 8) {
        printf("Invalid number of neighbors. Should be between 0 and 8");
        exit(1);
      }
      if(neighbors < 2){
        newBoard[x*rows+y]= '-';
      
      } else if(neighbors > 3){
          newBoard[x*rows+y] = '-';

      } else if(neighbors == 3){
          newBoard[x*rows+y] = '@';
      
      } else {
          newBoard[x*rows+y] = refBoard[x*rows+y];
      }
        
    }
  }
    print(newBoard,atoi(argv[2]),rows,cols,iters);
}
Exemplo n.º 4
0
    /**
     *
     * @param parentId
     * @return
     */
    virtual int writeH5Data(hid_t parentId)
    {

      int err = 0;

      // Generate the number of neighbors array and also compute the total number
      // of elements that would be needed to flatten the array
      std::vector<int32_t> numNeighbors(_data.size());

      size_t total = 0;
      for(size_t dIdx = 0; dIdx < _data.size(); ++dIdx)
      {
        numNeighbors[dIdx] = static_cast<int32_t>(_data[dIdx]->size());
        total += _data[dIdx]->size();
      }

      // Check to see if the NumNeighbors is already written to the file
      bool rewrite = false;
      if (H5Lite::datasetExists(parentId, DREAM3D::FieldData::NumNeighbors) == false)
      {
        rewrite = true;
      }
      else
      {
        std::vector<int32_t> fileNumNeigh(_data.size());
        err = H5Lite::readVectorDataset(parentId, DREAM3D::FieldData::NumNeighbors, fileNumNeigh);
        if (err < 0)
        {
          return -602;
        }

        // Compare the 2 vectors to make sure they are exactly the same;
        if (fileNumNeigh.size() != numNeighbors.size())
        {
          rewrite = true;
        }
        // The sizes are the same, now compare each value;
        int32_t* numNeighPtr = &(numNeighbors.front());
        int32_t* fileNumNeiPtr = &(fileNumNeigh.front());
        size_t nBytes = numNeighbors.size() * sizeof(int32_t);
        if (::memcmp(numNeighPtr, fileNumNeiPtr, nBytes) != 0)
        {
          rewrite = true;
        }
      }

      // Write out the NumNeighbors Array
      if(rewrite == true)
      {
        std::vector<hsize_t> dims(1, numNeighbors.size());
        err = H5Lite::writeVectorDataset(parentId, DREAM3D::FieldData::NumNeighbors, dims, numNeighbors);
        if(err < 0)
        {
          return -603;
        }
        err = H5Lite::writeScalarAttribute(parentId, DREAM3D::FieldData::NumNeighbors, std::string(H5_NUMCOMPONENTS), 1);
        if(err < 0)
        {
          return -605;
        }
        err = H5Lite::writeStringAttribute(parentId, DREAM3D::FieldData::NumNeighbors, DREAM3D::HDF5::ObjectType, "DataArray<T>");
        if(err < 0)
        {
          return -604;
        }
      }

      // Allocate an array of the proper size to we can concatenate all the arrays together into a single array that
      // can be written to the HDF5 File. This operation can ballon the memory size temporarily until this operation
      // is complete.
      std::vector<T> flat (total);
      size_t currentStart = 0;
      for(size_t dIdx = 0; dIdx < _data.size(); ++dIdx)
      {
        size_t nEle = _data[dIdx]->size();
        if (nEle == 0) { continue; }
        T* start = &(_data[dIdx]->front()); // Get the pointer to the front of the array
        //    T* end = start + nEle; // Get the pointer to the end of the array
        T* dst = &(flat.front()) + currentStart;
        ::memcpy(dst, start, nEle*sizeof(T));

        currentStart += _data[dIdx]->size();
      }

      int32_t rank = 1;
      hsize_t dims[1] = { total };
      if (total > 0)
      {
        err = H5Lite::writePointerDataset(parentId, GetName(), rank, dims, &(flat.front()));
        if(err < 0)
        {
          return -605;
        }
        err = H5Lite::writeScalarAttribute(parentId, GetName(), std::string(H5_NUMCOMPONENTS), 1);
        if(err < 0)
        {
          return -606;
        }

        err = H5Lite::writeStringAttribute(parentId, GetName(), DREAM3D::HDF5::ObjectType, getNameOfClass());
        if(err < 0)
        {
          return -607;
        }

        err = H5Lite::writeStringAttribute(parentId, GetName(), "Linked NumNeighbors Dataset", DREAM3D::FieldData::NumNeighbors);
        if(err < 0)
        {
          return -608;
        }
      }
      return err;
    }
/** Handles a trapped packet after timeout
 *
 */
dessert_per_result_t handleTrappedPacket(void *data, struct timeval *scheduled, struct timeval *interval) {
    trappedpacket_t* t = (trappedpacket_t*) data;
    uint8_t forwarded = 0;
    switch(gossip) {
        // forward if less than m duplicates received
        case gossip_14:
        case gossip_3:
            if((t->counter)-1 < m) {
                dessert_debug("forwarding msg: src=" MAC ", seq=%d, received %d<%d duplicates",
                              EXPLODE_ARRAY6(t->key.addr), t->msg->u16, t->counter-1, m);
                t->msg->u8 |= DELAYED;
                dessert_meshif_t* iface = NULL;
                logForwarded(t->msg, 0, NULL, iface);
                dessert_meshsend(t->msg, iface);
                forwarded = 1;
            }
            break;
        // send if not all neighbors sent a copy
        case gossip_5:
            if((t->counter) < numNeighbors()) {
                dessert_debug("forwarding msg: src=" MAC ", seq=%d, received %d<%d (=neighbors) duplicates",
                              EXPLODE_ARRAY6(t->key.addr), t->msg->u16, t->counter, numNeighbors());
                t->msg->u8 |= DELAYED;
                dessert_meshif_t* iface = NULL;
                logForwarded(t->msg, 0, NULL, iface);
                dessert_meshsend(t->msg, iface);
                forwarded = 1;
            }
            break;
        // forward if less than m duplicates received with adapted probability
        case gossip_6:
            if((t->counter)-1 < m) {
                float  new_p = (p/(m + 1));
                if(random() < (((long double) new_p)*((long double) RAND_MAX))) {
                    dessert_debug("forwarding msg: src=" MAC ", seq=%d, received %d<%d duplicates and send with probability %f",
                                  EXPLODE_ARRAY6(t->key.addr), t->msg->u16, t->counter-1, m, new_p);
                    t->msg->u8 |= DELAYED;
                    dessert_meshif_t* iface = NULL;
                    logForwarded(t->msg, 0, NULL, iface);
                    dessert_meshsend(t->msg, iface);
                    forwarded = 1;
                }
            }
            break;
        // forward if less than m-1 duplicates received
        case gossip_7:
            if((t->counter-1) <= m) {
                if(random() < (((long double) p)*((long double) RAND_MAX))) {
                    dessert_debug("forwarding msg: src=" MAC ", seq=%d, received %d<=%d duplicates", EXPLODE_ARRAY6(t->key.addr), t->msg->u16, t->counter-1, m);
                    t->msg->u8 |= DELAYED;
                    dessert_meshif_t* iface = NULL;
                    logForwarded(t->msg, 0, NULL, iface);
                    dessert_meshsend(t->msg, iface);
                    forwarded = 1;
                }
            }
            break;
        case gossip_10:
            if(t->forwarded) {
                if((max(0, t->counter) + t->counter2) < m) {
                    t->msg->u8 |= DELAYED;
                    dessert_meshif_t* iface = NULL;
                    logForwarded(t->msg, 0, NULL, iface);
                    dessert_meshsend(t->msg, iface);
                    forwarded = 1;
                }
                // always drop packet after 2nd forwarding chance
            }
            else {
                // like gossip_3
                if(max(0, t->counter - 1) < m) {
                    t->msg->u8 |= DELAYED;
                    dessert_meshif_t* iface = NULL;
                    logForwarded(t->msg, 0, NULL, iface);
                    dessert_meshsend(t->msg, iface);
                    t->forwarded = 1;
                    uint32_t sec = timeout.tv_sec;
                    uint32_t usec = timeout.tv_usec;
                    struct timeval handle_interval;
                    gettimeofday(&handle_interval, NULL);
                    TIMEVAL_ADD(&handle_interval, sec, usec);
                    dessert_periodic_add((dessert_periodiccallback_t *) handleTrappedPacket, t, &handle_interval, NULL);
                    dessert_debug("keeping packet to monitor forwarding of neighbors: src=" MAC ", seq=%d", EXPLODE_ARRAY6(t->key.addr), t->key.seq);
                    return 0; // do not delete msg and give it a second chance
                }
            }
            break;
        case gossip_11: // TODO: remove/replace
            if((t->counter)-1 < m) {
                float new_p = (p+(((1-p)*p)/(m + 1)));
                if(random() < (((long double) new_p)*((long double) RAND_MAX))) {
                    dessert_debug("forwarding msg: src=" MAC ", seq=%d, received %d<%d duplicates, p_new=%f",
                                  EXPLODE_ARRAY6(t->key.addr), t->msg->u16, t->counter-1, m, new_p);
                    t->msg->u8 |= DELAYED;
                    dessert_meshif_t* iface = NULL;
                    logForwarded(t->msg, 0, NULL, iface);
                    dessert_meshsend(t->msg, iface);
                    forwarded = 1;
                }
            }
            break;
        default:
            dessert_warn("unsupported gossip variant");
    }

    if(!forwarded) {
        dessert_debug("packet not forwarded, dropping it now: src=" MAC ", seq=%d", EXPLODE_ARRAY6(t->key.addr), t->key.seq);
    }

    /*###*/
    pthread_rwlock_wrlock(&packettrap_lock);
    HASH_DEL(trappedpackets, t);
    pthread_rwlock_unlock(&packettrap_lock);
    /*###*/

    destroyTrappedPacket(t);

    return 0;
}
Exemplo n.º 6
0
int main( int argc , char* argv[] )
{
	MPI_Init(      &argc          , &argv ) ;
	MPI_Comm_size( MPI_COMM_WORLD , &size ) ; // same
	MPI_Comm_rank( MPI_COMM_WORLD , &rank ) ; // different

	int x, y, numNeighs;
	double lst[S/size][S];
	int result[S/size][S];

	//
	// manager has rank = 0
	//
	init();
	if( rank == 0 )
	{
		glutInit(&argc,argv);
		glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
		glutInitWindowSize(S*PIX_SCALE,S*PIX_SCALE);
		glutInitWindowPosition(100,50);
		glutCreateWindow("");
		glClearColor(1.0,1.0,1.0,0.0);
		glShadeModel(GL_SMOOTH);
		
		printf("run\n");
		run();

		glutDisplayFunc(displayfunc);
		glutMouseFunc(mousefunc);
		glutKeyboardFunc(keyfunc);
		//
		glutMainLoop();
		//
		return 0;
   }
   //
   // workers have rank > 0
   //
   else
   {
		while (1)
		{
			printf("recieve\n");
			MPI_Recv( lst , S/size , MPI_DOUBLE , 0 , tag , MPI_COMM_WORLD , &status ) ;

			for (x=0; x<S/size; x++)
			{
				for (y=0; y<S; y++)
				{
					t[x+S/size*(rank-1)][y] = lst[x][y];
				}
			}

			for (x=S/size*(rank-1); x<S/size*rank; x++)
			{
				for (y=0; y<S; y++)
				{
					numNeighs = numNeighbors(x, y);
					if (numNeighs==3 || numNeighs==2 && t[x][y]==1) t[x][y] = 1;
					else t[x][y] = 0;
					result[x-S/size*(rank-1)][y] = t[x][y];
				}
			}

			MPI_Send( result , S/size , MPI_DOUBLE , 0 , tag , MPI_COMM_WORLD ) ;
		}
  }
   //
   // boilerplate
   //
   MPI_Finalize() ;
   //
   return 0;
}