Beispiel #1
0
void ImportBinary(void)
{
	// Import the Polygon list from a binary file
	std::fstream Input("SaveFile.tie", std::ios_base::binary | std::ios_base::in);
	if (Input.bad())		return;
	if (!Input.good())		return;
	for (unsigned int i = 0; i < POLYGON_COUNT; i++) Input.read((char*)&PolygonList[i], sizeof(Poly));
	Input.close();

	// Clear the Evolve surface and allow a new fitness to be calculated
	ClearSurface(Evolve);
	Fitness = 0.0;
	
	printf("\n\n\nTriangle List Imported!");

	// Normally after this occurs, a single mutation would be set and the resulting fitness would be higher than
	// what is was before importing. To prevent this, calculate the fitness before returning to the loop
	
	// Draw the Evolve Image
	ClearSurface(Evolve);
	for (unsigned int i = 0; i < POLYGON_COUNT; i++)
		if (PolygonList[i].BitFlag & DEFINED_BIT)
			filledPolygonRGBA(Evolve, PolygonList[i].X, PolygonList[i].Y, VERTEX_COUNT, PolygonList[i].Color[0], PolygonList[i].Color[1], PolygonList[i].Color[2], PolygonList[i].Color[3]);

	Fitness = CalculateFitness();
	memcpy((void*)((Uint32*)Best->pixels), (void*)((Uint32*)Evolve->pixels), Evolve->pitch * Evolve->h);

	GoodMutations = 0;
	Mutations = 0;
	Attempts = 0;
	OpeningTick = SDL_GetTicks();
	OutputInformation(Fitness, GoodMutations, Mutations, Attempts, 0.0);
}
Beispiel #2
0
bool GenAlgo::Initialize()
{
	int i ,j;

	/*NOTE:: lenChromo_tot = Sum(lenChromo_var) . Thus all the variables are 
	*	     considered in a single choromosome.							   */
	lenChromo_tot = 0;
	for (int k = 0; k < nVAR; k++)	lenChromo_tot += lenChromo_var[k];
	
	MaxFitness_Calculations = 10000 * nVAR;		//According to CEC 2013 benchmark.

	POPU = new INDIVIDUAL[nPOPU];	
	Temp_popu = new INDIVIDUAL[nPOPU];

	best_fitness_array = new Fitness[nGEN];

	for (i = 0; i < nPOPU; i++)
	{
		POPU[i].fChromo = new char[lenChromo_tot];
		Temp_popu[i].fChromo = new char[lenChromo_tot];

		for (j = 0; j < lenChromo_tot; j++)
		{
			POPU[i].fChromo[j] = (rand() % 2) ;   // randomly initialises the chorosome string (mod2 random number generation)
		}	

		POPU[i].fFitness = CalculateFitness(POPU[i]);	//calculates the fittness level.
	}

	return SUCCESS;
	
}
Population::Population(size_t population_size, double mutation_rate,
					   double nonterminal_crossover_rate, 
					   size_t tournament_size, size_t depth_min, 
					   size_t depth_max, double const_min, double const_max, 
					   size_t var_count, std::vector<SolutionData> solutions) {
	solutions_ = solutions;

	mutation_rate_ = mutation_rate;
	nonterminal_crossover_rate_ = nonterminal_crossover_rate;
	tournament_size_ = tournament_size;

	var_count_ = var_count;
	const_min_ = const_min;
	const_max_ = const_max;

	best_fitness_ = DBL_MAX;
	worst_fitness_ = DBL_MIN;
	avg_fitness_ = 0;

	largest_tree_ = 0;
	smallest_tree_ = SIZE_MAX;
	avg_tree_ = 0;

	/* Generate the population */
	if (depth_min > depth_max) {
		size_t temp = depth_max;
		depth_max = depth_min;
		depth_min = temp;
	}
	if (population_size % 2 != 0) {
		++population_size; /* Force population to be even */
	}
	RampedHalfAndHalf(population_size, depth_min, depth_max);
	CalculateFitness();
}
Beispiel #4
0
bool TestEvolution(void)
{
	// Test the temp fitness against the current fitness. If it is greater or equal, replace 
	// all pixels in Best with pixels from Evolve and update the current fitness.
	Attempts++;
	TempFitness = CalculateFitness();
	if (TempFitness > Fitness)
	{
		Mutations++;
		if (TempFitness != Fitness) GoodMutations++;

		// Copy over all pixels to the Best surface and write in the new fitness
		memcpy((void*)((Uint32*)Best->pixels), (void*)((Uint32*)Evolve->pixels), Evolve->pitch * Evolve->h);
		Fitness = TempFitness;

		// Output information to console
		OutputInformation(Fitness, GoodMutations, Mutations, Attempts, (SDL_GetTicks() - OpeningTick) / 1000.0);

		// Return an indication that the triangle list mutation was successful
		return true;
	}
	else PolygonList[ListIterator] = TempPolygon;
	
	// Return an indication that the triangle list mutation was not successful
	return false;
}
void Population::Evolve(size_t elitism_count) {
	std::vector<Individual> evolved_pop(pop_.size());
	std::vector<size_t> elites = Elitism(elitism_count);
	
	/* Choosing elite individuals uses raw fitness */
	for (size_t j = 0; j < elitism_count; ++j) {
		evolved_pop[j] = pop_[elites[j]];
	}

	for (size_t j = elitism_count; j < pop_.size(); ++j) {
		size_t p1 = SelectIndividual();
		size_t p2;
		do {
			p2 = SelectIndividual();
		} while (p2 == p1);

		Individual parent1(pop_[p1]);
		Individual parent2(pop_[p2]);
		Crossover(&parent1, &parent2);

		evolved_pop[j] = parent1;
		evolved_pop[j].Mutate(mutation_rate_);
	}
	this->pop_ = evolved_pop;
	CalculateFitness();
}
Beispiel #6
0
/* Counters of food sources are also initialized in this function*/
void init(int index)
{
    int i,j,kk,k,ii;
    /*for(i=1;i<=S;i++)
    {       
         fprintf(file,"ub[%d]=%d lb[%d]=%d\n",i,ub[i],i,lb[i]);
    }*/
    for(kk=1;kk<=S;kk++)
    {
        for(ii=1;ii<=J;ii++)
           Foods[index][kk][ii].number=0.0;
        for(ii=1;ii<=10;ii++)
           num[kk][ii]=1;
        for (j=1;j<=J;j++)
        {          
                r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                //fprintf(file,"r=%f\n",r);
                Foods[index][kk][j].number=r*(ub[kk]-lb[kk])+lb[kk];
                Foods[index][kk][j].pos=j;  
                solution[kk][j].number=Foods[index][kk][j].number;
                solution[kk][j].pos=j;
        }
        qsort(Foods[index][kk],J+1,sizeof(Foods[index][kk][1]),cmp);//***使用快速排序 
        for(k=1;k<=J;k++)
        {
            for(j=1;j<=sm[kk];j++)
            {
              if((int)(Foods[index][kk][k].number)==j)
              {
                order[kk][j][num[kk][j]]=Foods[index][kk][k].pos;
                num[kk][j]++;
                break;
              }
            }              
        }
     }
         /*fprintf(file,"initial\n");
         for(i=1;i<=S;i++)
        {
            fprintf(file,"stages=%d\n",i);
            for(j=1;j<=sm[i];j++)
            {     
                fprintf(file,"num=%d ",num[i][j]);     
                fprintf(file,"machines=%d\n",j);
                fprintf(file,"jobs=\n");
                for(k=1;k<num[i][j];k++)  
                fprintf(file,"%d ",order[i][j][k]);
                fprintf(file,"\n");
            }
            fprintf(file,"\n");
        } */ 
        f[index]= procetime(S,J,sm,protime,order,num);
	    fitness[index]=CalculateFitness(f[index]);
	    trial[index]=0;
	   // fprintf(file,"f[%d]=%f\n",index,f[index]);
}
Beispiel #7
0
bool GenAlgo::Run(const int func_no)
{

	int nPopu,
		totGen,
		indx_f = 0,				//Index of one parent.	
		indx_m = 0;				//Index of another parent.
	bool rslt;		

	func_num = func_no;

	/*INPUT PARAMETERS FROM USER*/
	rslt = InputParams();

	totGen = nGEN;
	Fitness_Calculations = 0;	//Setting the fittness calculations count to 0.

	/*INITIALIZE THE 0TH GEN POPULATION*/
	Initialize(); 
	Fitness_Calculations += nPOPU;

	do
	{		
		CHILDREN child1, child2;	//This are used to store the children temporaryly
		nPopu = nPOPU;	

		//ShowPopu();

		if (Fitness_Calculations > MaxFitness_Calculations)	break;		//Maximum number of fittness calculations has occured.

		while ((nPopu -= 2) >= 0)
		{
			/*allocation memory*/
			child1.fChromo = new char[lenChromo_tot];
			child2.fChromo = new char[lenChromo_tot];
			child1.fFitness = child2.fFitness = NULL;


			/*SELECT PARENTS*/
			GetParents(&indx_f, &indx_m);

			/*DO CROSSOVER*/
			CreateChildren(child1, child2, &indx_f, &indx_m);

			/*MUTATES THE CHILDREN*/
			MutateChildren(child1);
			MutateChildren(child2);

			/*CALCULATE FITNESS OF OFFSPRINGS*/
			child1.fFitness = CalculateFitness(child1);	
			child2.fFitness = CalculateFitness(child2);
			Fitness_Calculations += 2;

			/*IDENTIFY GOOD CHILDS AND STORE THEM*/
			IdentifyChilds(child1, child2, indx_f, indx_m, nPOPU - nPopu - 2);


			/*cleaning up*/
			indx_f = indx_m;
			delete[] child1.fChromo;
			delete[] child2.fChromo;
			child1.fFitness = child2.fFitness = NULL;
		}

		/*UPDATE NEW GEN POPULATION*/
		CopyPopulation(nGEN - totGen);

		std::cout << "\nGen no :: " << nGEN - totGen << std::endl;
		std::cout << "**************" << std::endl;
		ShowDude();

	} while (--totGen);

	ShowStatistics();

	ShowDude();		

return true;
}
Beispiel #8
0
// PROGRAM START
int main(int argc, char *argv[])
{
	srand((unsigned int)(time(0)));

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	RMASK = 0xff000000;
	GMASK = 0x00ff0000;
	BMASK = 0x0000ff00;
	AMASK = 0x000000ff;
#else
	RMASK = 0x000000ff;
	GMASK = 0x0000ff00;
	BMASK = 0x00ff0000;
	AMASK = 0xff000000;
#endif

	// Load in the target image and create the two additional surfaces
	Target = IMG_Load("TestImage.png");
	if (Target->w > IMAGE_MAX_W) return -1;
	if (Target->h > IMAGE_MAX_H) return -2;
	Best		= SDL_CreateRGBSurface(SDL_SWSURFACE, Target->w, Target->h, 32, RMASK, GMASK, BMASK, AMASK);
	Evolve		= SDL_CreateRGBSurface(SDL_SWSURFACE, Target->w, Target->h, 32, RMASK, GMASK, BMASK, AMASK);

	// If the surfaces are wider or taller than the maximum render area, decide how to scale it to fit
	RenderScale = 1.0;
	if ((Target->w > RENDER_MAX_W) || (Target->h > RENDER_MAX_H))
		RenderScale = ((Target->w > Target->h) ? (double)(Target->w) / (double)(RENDER_MAX_W) : (double)(Target->h) / (double)(RENDER_MAX_H));

	// Find the pixel byte size (to avoid dividing over and over later (probably 4)
	TargetPixelSize = Target->pitch / Target->w;
	EvolvePixelSize = Evolve->pitch / Evolve->w;

	// Create bit shifting elements for later based on the system endian-ness and whether the image is 24-bit or 32-bit
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	TargetBitMask_R		= 0xff << (8 * (TargetPixelSize - 1));
	TargetPixelShift_R	= 8 * (TargetPixelSize - 1);
	TargetBitMask_G		= 0xff << (8 * (TargetPixelSize - 2));
	TargetPixelShift_G	= 8 * (TargetPixelSize - 2);
	TargetBitMask_B		= 0xff << (8 * (TargetPixelSize - 3));
	TargetPixelShift_B	= 8 * (TargetPixelSize - 3);
	EvolveBitMask_R 	= 0xff << (8 * (EvolvePixelSize - 1));
	EvolvePixelShift_R	= 8 * (EvolvePixelSize - 1);
	EvolveBitMask_G 	= 0xff << (8 * (EvolvePixelSize - 2));
	EvolvePixelShift_G	= 8 * (EvolvePixelSize - 2);
	EvolveBitMask_B 	= 0xff << (8 * (EvolvePixelSize - 3));
	EvolvePixelShift_B	= 8 * (EvolvePixelSize - 3);
#else
	TargetBitMask_R		= 0xff << (8 * (TargetPixelSize - 3));
	TargetPixelShift_R	= 8 * (TargetPixelSize - 3);
	TargetBitMask_G 	= 0xff << (8 * (TargetPixelSize - 2));
	TargetPixelShift_G	= 8 * (TargetPixelSize - 2);
	TargetBitMask_B 	= 0xff << (8 * (TargetPixelSize - 1));
	TargetPixelShift_B	= 8 * (TargetPixelSize - 1);
	EvolveBitMask_R 	= 0xff << (8 * (EvolvePixelSize - 3));
	EvolvePixelShift_R	= 8 * (EvolvePixelSize - 3);
	EvolveBitMask_G 	= 0xff << (8 * (EvolvePixelSize - 2));
	EvolvePixelShift_G	= 8 * (EvolvePixelSize - 2);
	EvolveBitMask_B 	= 0xff << (8 * (EvolvePixelSize - 1));
	EvolvePixelShift_B	= 8 * (EvolvePixelSize - 1);
#endif

	// Load in the parts of the render rects that don't change
	SourceRect.x		= SourceRect.y	= 0;
	DestinationRect.w	= SourceRect.w	= Target->w;
	DestinationRect.h	= SourceRect.h	= Target->h;

	// Create the window
	if(!Window.DefineWindow(SCREEN_W, SCREEN_H, 32, false, "Triangle Image Evolution")) return -1;
	OpeningTick = SDL_GetTicks();
	TotalTime = 0.0;

	// Define all ListPolygon instances to a RANDOM state
	for (unsigned int i = 0; i < POLYGON_COUNT; i++) RandPolygon(&PolygonList[i]);

	// Calculate the starting fitness
	TempFitness		= 0.0;
	Fitness			= CalculateFitness();

	// Set the mutation information to NULL
	Attempts		= 0;
	Mutations		= 0;
	GoodMutations	= 0;
	RenderSwitch	= true;

	// Define the mutation type
	MutationType = Mutate1;

	while (true)
	{
		// Poll for input
		if(SDL_PollEvent(&event) > 0)
		{
			if(event.type & (SDL_KEYUP | SDL_KEYDOWN))
			{
				nKeyArray = SDL_GetKeyState(&nKeys);
				if (nKeyArray[SDLK_ESCAPE]) break;
				if (nKeyArray[SDLK_RETURN]) RenderSwitch = !RenderSwitch;
				if (nKeyArray[SDLK_1])		ExportBinary();
				if (nKeyArray[SDLK_2])		ImportBinary();
				if (nKeyArray[SDLK_3])		MutationType = Mutate1;
				if (nKeyArray[SDLK_4])		MutationType = Mutate2;
			}
		}

		// Go through a mutation sequence
		MutationType(PolygonList);

		if (RenderSwitch) RenderScreen(RenderScale);
	}

	SDL_FreeSurface(Target);
	SDL_FreeSurface(Best);
	SDL_FreeSurface(Evolve);
	Window.Undefine();
	printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
	return 0;
}
Beispiel #9
0
//----------------------UpdateShipFromAction---------------------------
//
//  this is the main workhorse. It reads the ships decoded string of
//  actions and performs them, updating the lander accordingly. It also 
//  checks for impact and updates the fitness score.
//
//----------------------------------------------------------------------
bool CLander::UpdateShip()
{
   //just return if ship has crashed or landed
  if (m_bCheckedIfLanded)
  {
    return false;
  }
 
  //this will be the current action
  action_type action;

  //check that we still have an action to perform. If not then
  //just let the lander drift til it hits the ground
  if (m_cTick >= m_vecActions.size())
  {
    action = non;
  }

  else
  {
    action = m_vecActions[m_cTick++];
  }
  	

	//switch the jet graphic off
  m_bJetOn = false;
  
	switch (action)
	{
	case rotate_left:

		m_dRotation -= ROTATION_PER_TICK;

		if (m_dRotation < -PI)
		{
			m_dRotation += TWO_PI;
		}
		break;

	case rotate_right:

		m_dRotation += ROTATION_PER_TICK;

		if (m_dRotation > TWO_PI)
		{
			m_dRotation -= TWO_PI;
		}
		break;

	case thrust:
    {
      //the lander's acceleration per tick calculated from
      //the force the thruster exerts and the lander's mass
      double ShipAcceleration = THRUST_PER_TICK/m_dMass;

	    //resolve the acceleration vector into its x, y components
      //and add to the lander's velocity vector
      m_vVelocity.x += ShipAcceleration * sin(m_dRotation);
		  m_vVelocity.y += ShipAcceleration * cos(m_dRotation);
		  
      //switch the jet graphic on
      m_bJetOn = true;
    }

		break;

	case non:

		break;

	}//end switch


  //now add in the gravity vector
	m_vVelocity.y += GRAVITY_PER_TICK;

  //update the lander's position	
  m_vPos += m_vVelocity;

	
	//bounds checking
	if (m_vPos.x > WINDOW_WIDTH)
	{
		m_vPos.x = 0;
	}
	
	if (m_vPos.x < 0)
	{
		m_vPos.x = WINDOW_WIDTH;
	}

  //now we check to see if the lander has crashed or landed

  //create a copy of the landers verts before we transform them
	m_vecShipVBTrans = m_vecShipVB;

	//transform the vertices
  WorldTransform(m_vecShipVBTrans);

	//if we are lower than the ground then we have finished this run
	if (TestForImpact(m_vecShipVBTrans))
  {
    //check if user has landed ship
    if (!m_bCheckedIfLanded)
    {
       //calculate fitness if we haven't already
      if (!m_dFitness)
      {
        CalculateFitness();
    
        m_bCheckedIfLanded = true;
      }
    
      return false;
    }
  }
    
  return true;
}
Beispiel #10
0
void SendOnlookerBees()
//跟随蜂 
{

          int i,j,t,kk,k,ii;
          i=1;
          t=0;
          /*onlooker Bee Phase*/
          while(t<FoodNumber)
        {

                r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
              
                if(r<prob[i]) /*choose a food source depending on its probability to be chosen*/
                {        
                       t++;
                       r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                       neighbour=(int)(r*(FoodNumber-1)+1);
                       while(neighbour==i)
                       {
                            r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                            neighbour=(int)(r*(FoodNumber-1)+1);
                       }
                       for(kk=1;kk<=S;kk++)
                       {
                            for(ii=1;ii<=10;ii++)
                              num[kk][ii]=1;
                            /*The parameter to be changed is determined randomly*/
                            r = ((double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                            param2change=(int)(r*(J-1)+1);
                            /*A randomly chosen solution is used in producing a mutant solution of the solution i*/
                            /*r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                            neighbour=(int)(r*FoodNumber);
                            
                            /*Randomly selected solution must be different from the solution i*/        
                            /*while(neighbour==i)
                            {
                                r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                                neighbour=(int)(r*FoodNumber);
                            }*/
                          
                            for(j=1;j<=J;j++)
                            {
                                solution[kk][j].number=Foods[i][kk][j].number;
                                solution[kk][j].pos=Foods[i][kk][j].pos;
                            }   
                            /*v_{ij}=x_{ij}+\phi_{ij}*(x_{kj}-x_{ij}) */
                            r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                            solution[kk][param2change].number=Foods[i][kk][param2change].number+(Foods[i][kk][param2change].number-Foods[neighbour][kk][param2change].number)*(r-0.5)*2;
                    
                            /*if generated parameter value is out of boundaries, it is shifted onto the boundaries*/
                            while (solution[kk][param2change].number<lb[kk])
                            {
                                r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                                solution[kk][param2change].number=r*(ub[kk]-lb[kk])+lb[kk];
                            }
                           while (solution[kk][param2change].number>=ub[kk])
                           {
                                r = (   (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
                                solution[kk][param2change].number=r*(ub[kk]-lb[kk])+lb[kk];
                           }
                            qsort(solution[kk],J+1,sizeof(solution[kk][1]),cmp);//***使用快速排序 
                             for(k=1;k<=J;k++)
                            {
                                for(j=1;j<=sm[kk];j++)
                                {
                                  if((int)(solution[kk][k].number)==j)
                                  {
                                    order[kk][j][num[kk][j]]=solution[kk][k].pos;
                                    num[kk][j]++;
                                    break;
                                  }
                                }              
                            }
                    }
                    /*fprintf(file,"SendOnlookerBees:\n");
                    for(int ii=1;ii<=S;ii++)
                    {
                        fprintf(file,"stages=%d\n",ii);
                        for(j=1;j<=sm[ii];j++)
                        {     
                            fprintf(file,"num=%d ",num[ii][j]);     
                            fprintf(file,"machines=%d\n",j);
                            fprintf(file,"jobs=\n");
                            for(k=1;k<num[ii][j];k++)  
                            fprintf(file,"%d ",order[ii][j][k]);
                            fprintf(file,"\n");
                        }
                        fprintf(file,"\n");
                    } */ 
                     ObjValSol= procetime(S,J,sm,protime,order,num);
        	         FitnessSol=CalculateFitness(ObjValSol);
                    /*a greedy selection is applied between the current solution i and its mutant*/
                        if (FitnessSol>fitness[i])
                        {
                        /*If the mutant solution is better than the current solution i, replace the solution with the mutant and reset the trial counter of solution i*/
                            trial[i]=0;
                            for(kk=1;kk<=S;kk++)
                            {
                                for(j=1;j<=J;j++)
                                {
                                    Foods[i][kk][j].number=solution[kk][j].number;
                                    Foods[i][kk][j].pos=solution[kk][j].pos;
                                }
                            }
                            f[i]=ObjValSol;
                            fitness[i]=FitnessSol;
                        }
                        else
                        {   /*if the solution i can not be improved, increase its trial counter*/
                            trial[i]=trial[i]+1;
                        }
           }
          /*if */
            i++;
            if (i==FoodNumber+1)
            i=1;
      }/*while*/
        /*end of onlooker bee phase     */
}