Beispiel #1
0
/*
 * Redeseneaza zona din dreapta dupa ce utilizatorul a miscat sau a
 * modificat dreptunghiul in zona din stanga.
 */
void redraw_right_area()
{
	int restidx, pi;

	set(3);
	setwritemode(COPY_PUT);
	setcolor(LIGHTBLUE);
	clearviewport();
	for (int i = 0; i <= REF; i++)
	{
		if ((x[i] >= x1) && (x[i] <= x2) && (y[i] >= y1) && (y[i] <= y2))
		{
			moveto(newX(x[i]), newY(y[i]));
			pi = i;
			restidx = i+1;
			i = REF+1;
		}
	}
	for (i = restidx; i <= REF; i++)
	{
		if ((x[i] >= x1) && (x[i] <= x2) && (y[i] >= y1) && (y[i] <= y2))
		{
			if ((pi+1) == i)
			{
				lineto(newX(x[i]), newY(y[i]));
			}
			else
			{
				moveto(newX(x[i]), newY(y[i]));
			}
			pi = i;
		}
	}
}
Beispiel #2
0
void NewPosition(MazewarInstance::Ptr m)
//void NewPosition(MazewarInstance *m)
{
	Loc newX(0);
	Loc newY(0);
	Direction dir(0); /* start on occupied square */

	while (M->maze_[newX.value()][newY.value()]) {
	  /* MAZE[XY]MAX is a power of 2 */
	  newX = Loc(random() & (MAZEXMAX - 1));
	  newY = Loc(random() & (MAZEYMAX - 1));

	  /* In real game, also check that square is
	     unoccupied by another rat */
	}

	/* prevent a blank wall at first glimpse */

	if (!m->maze_[(newX.value())+1][(newY.value())]) dir = Direction(NORTH);
	if (!m->maze_[(newX.value())-1][(newY.value())]) dir = Direction(SOUTH);
	if (!m->maze_[(newX.value())][(newY.value())+1]) dir = Direction(EAST);
	if (!m->maze_[(newX.value())][(newY.value())-1]) dir = Direction(WEST);

	m->xlocIs(newX);
	m->ylocIs(newY);
	m->dirIs(dir);
}
Beispiel #3
0
/* TODO... finish this function as described below
 * move bugs 
 * if they move onto food, feed them
 * if they move onto another bug, no big deal.  Two bugs
 * can be in the same square.  Let's say bug#2 and bug #6 are in the same
 * square.  Well, both bugs are still in the bug_list, so they
 * will still be able to move next time step.
 * Since the world[][] array can only hold either a 2 or a 6, we'll just
 * put one of them there.  The easiest thing to do is just put which
 * ever bug moves into the square first into the square.  When the next
 * bug moves into the square, update his x and y (in bug_list) so that
 * he is in the square, leave the other bug alone (i.e., it's also in
 * the same square) and then set world[x][y] = 6 (the bug # of the second
 * bug).  No harm done.  The graphics will draw only the second bug
 * but who cares.  The next time step they'll move into different squares
 * (probably) and no one will notice.
 * NOTE: only the first bug to move into the square gets to eat the food
 * there.
 */
void moveBugs(void) {
    int total_age = 0;
    int total_gen = 0;

    /* update each bug in turn (but don't kill them) */
    for (int k = 0; k < bug_list.size(); ++k) {
        /* Clear the current square if we are the only one here.
         */
        if (world[bug_list[k].x][bug_list[k].y] ==  k) {
            world[bug_list[k].x][bug_list[k].y] = EMPTY;
        }
        /* Update bug position. */
        bug_list[k].x = newX(bug_list[k].x, bug_list[k].dir);
        bug_list[k].y = newY(bug_list[k].y, bug_list[k].dir);
        /* Bug eating behavior. */
        if (world[bug_list[k].x][bug_list[k].y] == FOOD) {
            bug_list[k].health += EAT_HEALTH;
        }
        /* Put the bug in the new spot. */
        world[bug_list[k].x][bug_list[k].y] = k;
        /* Bug movement health cost. */
        bug_list[k].health -= MOVE_HEALTH;
        /* Bug turn based on genes. */
        bug_list[k].dir = (bug_list[k].dir+chooseDir(bug_list[k].genes))%8;
        /* Bug statistics. */
        bug_list[k].age += 1;

        total_age += bug_list[k].age;
        total_gen += bug_list[k].generation;
    }
    average_age = total_age / bug_list.size();
    average_generation = total_gen / bug_list.size();
}
Beispiel #4
0
/*!
 * \brief Apply median filter to data
 */
void Data2D::medianFilter(int length)
{
	double data[length], avg, result;
	int m, i = length/2, n = length/2, miny, maxy;
	Array<double> newY(x_.nItems());
	
	// Set boundary values
	for (m=0; m<n; ++m)
	{
		newY[m] = y_[m];
		newY[x_.nItems()-1-m] = y_[m];
	}

	// Now loop over remaining points
	while (n < (x_.nItems()-i))
	{
		// Grab data values, and determine min/max values
		miny = 0;
		maxy = 0;
		for (m=-i; m<=i; ++m)
		{
			data[m+i] = y_[n+m];
			if (data[m+i] < data[miny]) miny = m+i;
			if (data[m+i] > data[maxy]) maxy = m+i;
		}

		// Determine median value (without sorting)
		// First, calculate average value
		avg = 0.0;
		for (m=0; m<length; ++m) if ((m != miny) && (m != maxy)) avg += data[m];
		avg /= length-2;
		// Now find value closest to the average
		result = data[0];
		for (m=0; m<length; ++m) if ((m != miny) && (m != maxy) && (fabs(data[m]-avg) < fabs(result-avg))) result = data[m];
		
		// Store median value
		newY[n] = result;
		
		++n;
	}
	
	// Store new values
	y_ = newY;
}
Beispiel #5
0
/* Makes sure bugs move properly in all directions */
TEST(MovementTests, SimpleMovementTest)
{
    bug_list.clear();

    for (int i = 0; i < 8; i++)
    {
        Bug b = initBug(0, 0, i);
        bug_list.push_back(b);
    }
    initWorld();

    moveBugs();
    ASSERT_EQ(bug_list.size(), 8);
    ASSERT_EQ(world[0][0], EMPTY);

    int i = 0;
    for (auto &bug : bug_list)
    {
        ASSERT_EQ(bug.x, newX(0, i));
        ASSERT_EQ(bug.y, newY(0, i));
        ASSERT_EQ(world[bug.x][bug.y], i++);
    }
}
Beispiel #6
0
	void PixelFlow::computeFlow( const Image& image, Math::Vector< int, 2 >& result, int& difference, Image* pDebugImg)
	{
		//decliaring variables
		int xCut = 0;
		int yCut = 0;
		int temp = 0;
		int xIndex = 0;
		int yIndex = 0;
		int xBufSize = 0;
		int yBufSize = 0;
		int width= image.widthStep;
		int hight = image.height; 
		int xSize = int(x.size());
		int ySize = int(y.size());
		Math::Vector< int, 4 > xRec;
		Math::Vector< int, 4 > yRec;

		calculateIncrisedCoordiants(width, hight, 0.5, topL, bottomR, xRec,  yRec);

		
		std::vector<int> newX( xRec(2) - xRec(0) + 1, 0 );
		std::vector<int> newY( yRec(3) - yRec(1) + 1, 0 );
		
		if(xRec(2) != width)
		{	
			if(((int)x.size())%2 != 0)
				xBufSize = int(x.size());
			else
				xBufSize = int(x.size())+1;
		}
		else
		{	
			xBufSize = int(newX.size()) - int(x.size()/2);
		}
		
		if(yRec(3) != hight)
		{	
			if(((int)y.size())%2 != 0)
				yBufSize = int(y.size());
			else
				yBufSize = int(y.size())+1;
		}
		else
		{	
			yBufSize = int(newY.size()) - int(y.size()/2) ;
		}
		
		std::vector<int> xErrorBuf(xBufSize, 255);
		std::vector<int> yErrorBuf(yBufSize, 255);
						
		//calculating the updated buffer
		for (int i = 0; i < xRec(2) - xRec(0); i++)
			for(int j = 0; j < xRec(3) - xRec(1); j++)
			{	
				int temp = (xRec(1)  + j)*image.width +  xRec(0) + i;
				newX[i] += ((unsigned char*)image.imageData)[temp];
			}
		
		for(int i = 0; i < int(newX.size()); i++)
			newX[i] /= xRec(3) - xRec(1);

		for (int i = 0; i < yRec(2) - yRec(0); i++)
			for(int j = 0; j < yRec(3) - yRec(1); j++)
			{	
				int temp = (yRec(1)  + j)*image.width +  yRec(0) + i;
				newY[j] += ((unsigned char*)image.imageData)[temp];
			}

		for(int i = 0; i < int(newY.size()); i++)
			newY[i] /= yRec(2) - yRec(0);

		//check whether there was a cut
		if(xRec(2) == width)
			xCut = 1;
		if(xRec(0)== 0)
			if(xCut != 1)
				xCut = -1;
			else
				xCut = 2;
			
		//calculating the error buffer
		calculateErrorBuffer(x,newX, xErrorBuf,xCut);

		//check whether there was a cut
		if(yRec(3) == hight)
			yCut = 1;
		if(yRec(1)== 0)
			if(yCut != 1)
				yCut = -1;
			else
				yCut = 2;

		//calculating the error buffer
		calculateErrorBuffer(y,newY, yErrorBuf,yCut);
		
		//finding the best shift in x direction
		temp = xErrorBuf[0];

		for (int i = 1; i <int(xErrorBuf.size()); i++)
			if(temp > xErrorBuf[i])
			{
				temp = xErrorBuf[i];
				xIndex = i;	
			}
		
		//finding the best shift in y direcion
		temp = yErrorBuf[0];
		
		for (int i = 1; i < int(yErrorBuf.size()); i++)
			if(temp > yErrorBuf[i])
			{
				temp = yErrorBuf[i];
				yIndex = i;
			}
		
		//if the nuew buffer is cut from left, the error buffer is shifting on xdif, or ydif
		int xdif, ydif;

		xdif = int(newX.size()) - 2*int(x.size()/2) - int(x.size());
		ydif = int(newY.size()) - 2*int(y.size()/2) - int(y.size());
		
		//returning the reslt
		if(xCut == 0 || xCut == 1)	
		{	
			result(0) = xIndex- int(x.size()/2);
		}
		else
		if(xCut = -1)
		{
			result(0) = xIndex - 2*int(x.size()/2)-xdif;
		}

		if(yCut == 0 || yCut == 1)	
		{	
			result(1) = yIndex - int(y.size()/2) ;
		}
		else
		if(yCut = -1)
		{
			result(1) = yIndex - 2*int(y.size()/2) -ydif;
		}
		
		//TO BE MODIFIED::
		difference = 0;

		//visualizing the error buffer
		if(pDebugImg)
		{
			CvPoint p1,p2;
				
			if(int(xErrorBuf.size()) < width -50)
			{	
				p1.y = 10;
				p2.y = 20;
				
				for (int i = 0; i < int(xErrorBuf.size()); i++)
				{	
					p1.x = width - int(xErrorBuf.size()) - 50 + i ;
					p2.x = width - int(xErrorBuf.size()) - 50 + i ;
					int color = std::min( int(xErrorBuf[i]) + 50, 255 );
					cvLine(pDebugImg,p1,p2,cvScalar(0,0,color),10,CV_AA,0);
				}

				p1.x = width -10;
				p2.x = width -20;
				
				for (int i = 0; i < int(yErrorBuf.size()); i++)
				{	
					p1.y = i + 50;
					p2.y = i + 50;
					int color = std::min( int(yErrorBuf[i]) + 50, 255 );
					cvLine(pDebugImg,p1,p2,cvScalar(0,0,color),10,CV_AA,0);
				}
			}
		}
	}
Beispiel #7
0
// Load the data.
void GPCMDataReader::load(
    std::vector<std::string> filelist,      // List of files from which to load the data.
    std::vector<double> noiselist           // Amount of noise to add to each file.
    )
{
    // Read data files.
    int i = 0;
    for (std::vector<std::string>::iterator itr = filelist.begin();
         itr != filelist.end(); ++itr)
    {
        // Load the file.
        MatrixXd data = loadFile(*itr);

        // Load auxiliary data.
        MatrixXd aux = loadAuxFile(*itr);

        // Check for blank auxiliary data.
        if (aux.cols() == 0)
            aux.setZero(data.rows(),1);

        // Add noise if desired.
        addDataNoise(data,noiselist[i]);

        // Concatenate into Y.
        MatrixXd newY(data.rows()+Y.rows(),data.cols());
        MatrixXd newAux(data.rows()+Y.rows(),aux.cols());

        // Store data.
        if (Y.rows() > 0)
            newY << Y,data;
        else
            newY = data;

        // Store auxiliary.
        if (auxData.rows() > 0)
            newAux << auxData,aux;
        else
            newAux = aux;

        // Switch over to the new matrices.
        Y = newY;
        auxData = newAux;

        // Concatenate into sequence.
        sequence.push_back(Y.rows());

        // Increment index.
        i++;
    }

    // Do any additional processing here, such as computing velocities and building supplementary
    // data structures.
    postProcessData();

    // Remove constant entries.
    MatrixXd constantEntries;
    std::vector<int> constantIndices;
    std::vector<int> variableIndices;
    int totalIndices = removeConstantEntries(Y,constantEntries,
        constantIndices,variableIndices);

    // Remove constant entries from scales.
    if (supplementary->getScale().cols() > 0)
    {
        MatrixXd newScale(1,variableIndices.size());
        for (unsigned i = 0; i < variableIndices.size(); i++)
        {
            newScale(0,i) = supplementary->getScale()(0,variableIndices[i]);
        }
        supplementary->getScale() = newScale;
    }

    // Pass duplicate entry information to supplement.
    supplementary->setConstant(constantEntries,constantIndices,variableIndices,totalIndices);
}
//---------------------------------------------------------
void NDG2D::OutputVTK(const DMat& FData, int order, int zfield)
//---------------------------------------------------------
{
  static int count = 0;
  string output_dir = ".";

  // The caller loads each field of interest into FData, 
  // storing (Np*K) scalars per column.
  //
  // For high (or low) resolution output, the user can 
  // specify an arbitrary order of interpolation for 
  // exporting the fields.  Thus while a simulation may 
  // use N=3, we can export the solution fields with 
  // high-order, regularized elements (e.g. with N=12).

  string buf = umOFORM("%s/sim_N%02d_%04d.vtk", output_dir.c_str(), order, ++count);
  FILE *fp = fopen(buf.c_str(), "w");
  if (!fp) {
    umLOG(1, "Could no open %s for output!\n", buf.c_str());
    return;
  }

  // Set flags and totals
  int Output_N = std::max(2, order);
  int Ncells=0, Npts=0;

  Ncells = OutputSampleNelmt2D(Output_N);
  Npts   = OutputSampleNpts2D (Output_N);

  // set totals for Vtk output
  int vtkTotalPoints = this->K * Npts;
  int vtkTotalCells  = this->K * Ncells;
  int vtkTotalConns  = (this->EToV.num_cols()+1) * this->K * Ncells;


  //-------------------------------------
  // 1. Write the VTK header details
  //-------------------------------------
  fprintf(fp, "# vtk DataFile Version 2");
  fprintf(fp, "\nNuDG++ 2D simulation");
  fprintf(fp, "\nASCII");
  fprintf(fp, "\nDATASET UNSTRUCTURED_GRID\n");
  fprintf(fp, "\nPOINTS %d double", vtkTotalPoints);

  int newNpts=0;

  //-------------------------------------
  // 2. Write the vertex data
  //-------------------------------------

  DMat newX, newY, newZ, newFData;

  // Build new {X,Y,Z} vertices that regularize the 
  // elements, then interpolate solution fields onto 
  // this new set of elements:
  OutputSampleXYZ(Output_N, newX, newY, newZ, FData, newFData, zfield);
//double maxF1 = newFData.max_col_val_abs(1), scaleF=1.0;
//if (maxF1 != 0.0) { scaleF = 1.0/maxF1; }

  newNpts = newX.num_rows();

  if (zfield>0)
  {
    // write 2D vertex data, with z-elevation
    for (int k=1; k<=this->K; ++k) {
      for (int n=1; n<=newNpts; ++n) {
        // use exponential format to allow for
        // arbitrary (astro, nano) magnitudes:
        fprintf(fp, "\n%20.12e %20.12e %20.12e", 
                      newX(n, k), newY(n, k), newZ(n,k)); //*scaleF);
      }
    }
  } else {
    // write 2D vertex data to file
    for (int k=1; k<=this->K; ++k) {
      for (int n=1; n<=newNpts; ++n) {
        // use exponential format to allow for
        // arbitrary (astro, nano) magnitudes:
        fprintf(fp, "\n%20.12e %20.12e  0.0", 
                      newX(n, k), newY(n, k));
      }
    }
  }


  //-------------------------------------
  // 3. Write the element connectivity
  //-------------------------------------
  IMat newELMT;

  // Number of indices required to define connectivity
  fprintf(fp, "\n\nCELLS %d %d", vtkTotalCells, vtkTotalConns);

  // build regularized tri elements at selected order
  OutputSampleELMT2D(Output_N, newELMT);
  newNpts = OutputSampleNpts2D(Output_N);

  int newNTri = newELMT.num_rows();
  int newNVert = newELMT.num_cols();

  // write element connectivity to file
  for (int k=0; k<this->K; ++k) {
    int nodesk = k*newNpts;
    for (int n=1; n<=newNTri; ++n) {
      fprintf(fp, "\n%d", newNVert);
      for (int i=1; i<=newNVert; ++i) {
        fprintf(fp, " %5d", nodesk+newELMT(n, i));
      }
    }
  }


  //-------------------------------------
  // 4. Write the cell types
  //-------------------------------------

  // For each element (cell) write a single integer 
  // identifying the cell type.  The integer should 
  // correspond to the enumeration in the vtk file:
  // /VTK/Filtering/vtkCellType.h

  fprintf(fp, "\n\nCELL_TYPES %d", vtkTotalCells);

  for (int k=0; k<this->K; ++k) {
    fprintf(fp, "\n");
    for (int i=1; i<=Ncells; ++i) {
      fprintf(fp, "5 ");            // 5:VTK_TRIANGLE
      if (! (i%10))
        fprintf(fp, "\n");
    }
  }
  
  //-------------------------------------
  // 5. Write the scalar "vtkPointData"
  //-------------------------------------

  fprintf(fp, "\n\nPOINT_DATA %d", vtkTotalPoints);

  // For each field, write POINT DATA for each point 
  // in the vtkUnstructuredGrid. 

  int Nfields = FData.num_cols();
  for (int fld=1; fld<=Nfields; ++fld)
  {
    fprintf(fp, "\nSCALARS field%d double 1", fld);
    fprintf(fp, "\nLOOKUP_TABLE default");

    // Write the scalar data, using exponential format 
    // to allow for arbitrary (astro, nano) magnitudes:
    for (int n=1; n<=newFData.num_rows(); ++n) {
      fprintf(fp, "\n%20.12e ", newFData(n, fld));
    }
  }

  // add final newline to output
  fprintf(fp, "\n");
  fclose(fp);
}
Beispiel #9
0
long main(long argc, char * argv[]) {
    long n, m, i, j;
	if (readBMP("in.bmp") == 0) {
        printf("Error");
        return 0;
    }
    double ang =(double)angle/180.0 * M_PI; //угол задается define'ом
	long top, bot, lft, rgt; 
	double sinn=sin(ang);
	double coss=cos(ang); 
	n=hat.height;
	m=hat.width;	
	
	//Вычиление координат углов после поворота
	long d1=newY(0,0,sinn,coss);
    long d2=newY(0,n-1,sinn,coss);
    long d3=newY(m-1,0,sinn,coss);
    long d4=newY(m-1,n-1,sinn,coss);
	top=max(d1, max(d2, max(d3, d4)));
	bot=min(d1, min(d2, min(d3, d4)));
	
	d1=newX(0,0,sinn,coss);
    d2=newX(0,n-1,sinn,coss);
    d3=newX(m-1,0,sinn,coss);
    d4=newX(m-1,n-1,sinn,coss);	
    rgt=max(d1, max(d2, max(d3, d4)));
	lft=min(d1, min(d2, min(d3, d4)));
	
	pxl pic[top-bot+1][rgt-lft+1]; //новая картинка
	
	for(i=0; i<=top-bot; i++)
		for(j=0; j<=rgt-lft; j++){
			//вычисление старых координат по новым
			d1=(i+bot)*sinn+(j+lft)*coss; 
			d2=-(j+lft)*sinn+(i+bot)*coss;
	
			if(d1>=0 && d1<m && d2<n && d2>=0){
				pic[i][j].a=img[d2][d1].a;
				pic[i][j].b=img[d2][d1].b;
				pic[i][j].c=img[d2][d1].c;
			}
			else{
				pic[i][j].a=255;
				pic[i][j].b=255;
				pic[i][j].c=255;
			}			
		}	
	
	//изменение hat 
	hat.width=rgt-lft+1;
	hat.height=top-bot+1;
	hat.size=(3*hat.width+hat.width%4)*hat.height+sizeof(hat);

	FILE* file = fopen("out.bmp","wb");
    if(file == NULL) return 0;
    fwrite(&hat, sizeof(hat), 1, file);
	char dump[3]={255};
	for(i=0; i<hat.height; i++){
		for(j=0; j<hat.width; j++)
			fwrite(&pic[i][j], sizeof(pxl), 1, file);
		fwrite(dump, sizeof(char), hat.width%4, file);
	}
	    
    fclose(file);	
    return 0;
}
Beispiel #10
0
/*---moveBugs---------------------------------------------------------------

	Updates state of global variables bug_list and world to move the bugs 
	according to their current direction and position and select their new 
	direction using a random probably based on their genes. Bug health will be 
	updated due to movement and also if a bug lands on a space in the world 
	array that contains food.

	Inputs: none
	Outputs: none

	Time Complexity: O(n*GENE_TOTAL) -> O(n), with the understanding that a large
	gene total could indicate a large prefactor

 --------------------------------------------------------------------------*/
void moveBugs(void) {
	int total_age = 0;
	int total_gen = 0;
	
	for (int k = 0; k < bug_list.size(); k += 1) {

		//update world where bug is moving from to EMPTY

		if (world[bug_list[k].x][bug_list[k].y] == k)
			world[bug_list[k].x][bug_list[k].y] = EMPTY;

		//new position in each bug's x and y
		bug_list[k].x = wrap(newX(bug_list[k].x,bug_list[k].dir));
		bug_list[k].y = wrap(newY(bug_list[k].y,bug_list[k].dir));

		// see if new position contains food, update health

		if (world[bug_list[k].x][bug_list[k].y] == FOOD){
			bug_list[k].health+=EAT_HEALTH;
		}

		//after checking for food, bug now occupies this spot in the world

		world[bug_list[k].x][bug_list[k].y] = k;

		//bug loses some health from moving
		
		bug_list[k].health -= MOVE_HEALTH;

		//bug's new direction determined according to his genes


		vector <int> prob_array(GENE_TOTAL);
		int i2 = 0;												//will iterate from 0 -> GENE_TOTAL

		/*this nested loop populates a probability array with GENE_TOTAL elements. Each element
		is assigned a direction to turn based on the bug's genes and represents 1/GENE_TOTAL 
		chance of the bug turning that direction*/

		for (int j = 0; j < 8; j++){							//goes through the 8 genes
			for (int i = 0; i < bug_list[k].genes[j]; i++){		
				prob_array[i2] = j;								//bug_list[k].genes[j] elements will be given value j
				i2++;
			}
		}

		int tmp = rand() % GENE_TOTAL;
		bug_list[k].dir = (bug_list[k].dir + prob_array[tmp])%8; //new direction as a function of old direction

		//update stats

		bug_list[k].age += 1;
		total_age += bug_list[k].age;
		total_gen += bug_list[k].generation;

	}


	if (bug_list.size()){
		average_age = total_age / bug_list.size();
		average_generation = total_gen / bug_list.size();
	}
}