Ejemplo n.º 1
0
	void GAStuff()
	{
		GARandomSeed(1);
		genome = new GAListGenome<int>(Objective);
		genome->initializer(::Initializer);
		genome->mutator(::Mutator);
		genome->comparator(::Comparator);
		genome->crossover(XOVER);
		dbg<<"inicijalizovao genom\n";

		ga = new GASteadyStateGA(*genome);
		dbg<<"napravio ga\n";
		ga->minimize();
		ga->pReplacement(1.0);
		ga->populationSize(100);
		ga->nGenerations(100);
		ga->pMutation(0.1);
		ga->pCrossover(1.0);
		ga->pMutation(0.3);
		ga->terminator(Terminator);
		//ga->pConvergence(1);
		ga->selectScores(GAStatistics::AllScores);
		//ga->terminator(GAGeneticAlgorithm::TerminateUponPopConvergence);
		//ga.parameters(argc, argv);
		ga->initialize(seed);
		dbg<<"inicijalozovao GA\n";
	}
Ejemplo n.º 2
0
// To initialize this genetic algorithm, we make sure all of our spawns are
// not evolving then we tell them all to initialize themselves.  Then we wait
// and copy their populations into our own.  Update our stats based upon the
// harvested populations.
void
PVMDemeGA::initialize(unsigned int seed) {
  GARandomSeed(seed);

  if(_mid == 0) return;

#ifdef DEBUG
  cerr << "sending initialize command to slaves...\n";
#endif

  for(int j=0; j<_ntid; j++) {
    _status = pvm_initsend(PvmDataDefault);
    _status = pvm_send(_tid[j], MSG_INITIALIZE);
  }

  collect();

  for(int i=0; i<_ntid; i++) {
    pstats[i].reset(*deme[i]);
    pop->individual(i).copy(deme[i]->best());
  }

  pop->touch();
  stats.reset(*pop);
}
Ejemplo n.º 3
0
int
main(int argc, char **argv)
{
  cout << "Example 4\n\n";
  cout << "This program tries to fill a 3DBinaryStringGenome with\n";
  cout << "alternating 1s and 0s using a SteadyStateGA\n\n"; cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii++],"seed") == 0) {
      GARandomSeed((unsigned int)atoi(argv[ii]));
    }
  }

  int depth    = 3;
  int width    = 10;
  int height   = 5;

// Now create the GA and run it.  First we create a genome of the type that
// we want to use in the GA.  The ga doesn't use this genome in the
// optimization - it just uses it to clone a population of genomes.

  GA3DBinaryStringGenome genome(width, height, depth, objective);

// Now that we have the genome, we create the genetic algorithm and set
// its parameters - number of generations, mutation probability, and crossover
// probability.  By default the GA keeps track of the best of generation scores
// and also keeps one genome as the 'best of all' - the best genome 
// that it encounters from all of the generations.  Here we tell the GA to
// keep track of all scores, not just the best-of-generation.

  GASteadyStateGA ga(genome);
  ga.populationSize(100);
  ga.pReplacement(0.50);	// replace 50% of population each generation
//  ga.nReplacement(4);	          // number of individuals to replace each gen
  ga.nGenerations(200);
  ga.pMutation(0.001);
  ga.pCrossover(0.9);
  ga.scoreFilename("bog.dat");	// name of file for scores
  ga.scoreFrequency(10);	// keep the scores of every 10th generation
  ga.flushFrequency(50);	// specify how often to write the score to disk
  ga.selectScores(GAStatistics::AllScores);
  ga.evolve();

// Now we print out the best genome.

  cout << "the ga generated:\n" << ga.statistics().bestIndividual() << "\n";
  cout << "best of generation data are in 'bog.dat'\n";

// That's it!

  return 0;
}
Ejemplo n.º 4
0
// Do some basic stupidity checks then initialize the population.  We must
// also initialize our temporary genomes, but we don't have to evaluate
// them.  Finally, reset the statistics.
void
GAIncrementalGA::initialize(unsigned int seed)
{
  GARandomSeed(seed);

  pop->initialize();
  pop->evaluate(gaTrue);

  stats.reset(*pop);

  if(!scross) GAErr(GA_LOC, className(), "initialize", gaErrNoSexualMating);
}
Ejemplo n.º 5
0
// Initialize the population, set the random seed as needed, do a few stupidity
// checks, reset the stats.  We must initialize the old pop because there is no
// guarantee that each individual will get initialized during the course of our
// operator++ operations.  We do not evaluate the old pop because that will
// happen as-needed later on.
void
GASimpleGA::initialize(unsigned int seed)
{
  GARandomSeed(seed);

  pop->initialize();
  pop->evaluate(gaTrue);	// the old pop will get it when the pops switch
//  oldPop->initialize();

  stats.reset(*pop);

  if(!scross)
    GAErr(GA_LOC, className(), "initialize", gaErrNoSexualMating);
}
Ejemplo n.º 6
0
int
main(int argc, char **argv)
{

// a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii++],"seed") == 0) {
      GARandomSeed((unsigned int)atoi(argv[ii]));
    }
  }

// Declare variables for the GA parameters and set them to some default values.

  //int width    = 50;
  //int height   = 41;
  int length=730;
  int popsize  = 100;
  int ngen     = 4000;
  float pmut   = 0.001;
  float pcross = 0.9;

// Now create the GA and run it.  Fist we create a genome of the type that
// we want to use in the GA.  The ga doesn't operate on this genome in the
// optimization - it just uses it to clone a population of genomes.

  GA1DBinaryStringGenome genome(length, Objective);

// Now that we have the genome, we create the genetic algorithm and set
// its parameters - number of generations, mutation probability, and crossover
// probability.  And finally we tell it to evolve itself.

  GASteadyStateGA ga(genome);
  ga.populationSize(popsize);
  ga.nGenerations(ngen);
  ga.pMutation(pmut);
  ga.pCrossover(pcross);
  ga.nBestGenomes(90);
  ga.evolve();

// Now we print out the best genome that the GA found.

  cout << "The GA found:\n" << ga.statistics().bestPopulation() << "\n";

// That's it! 
fclose(fp);
  return 0;
}
float Objective(GAGenome &);	// This is the declaration of our obj function.
// The definition comes later in the file.

int main(int argc, char **argv) {
	cout << "Example 1\n\n";
	cout << "This program tries to fill a 2DBinaryStringGenome with\n";
	cout << "alternating 1s and 0s using a SimpleGA\n\n";
	cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

	for (int ii = 1; ii < argc; ii++) {
		if (strcmp(argv[ii++], "seed") == 0) {
			GARandomSeed((unsigned int) atoi(argv[ii]));
		}
	}

// Declare variables for the GA parameters and set them to some default values.

	int width = 10;
	int height = 5;
	int popsize = 30;
	int ngen = 400;
	float pmut = 0.001;
	float pcross = 0.9;

// Now create the GA and run it.  First we create a genome of the type that
// we want to use in the GA.  The ga doesn't operate on this genome in the
// optimization - it just uses it to clone a population of genomes.

	GA2DBinaryStringGenome genome(width, height, Objective);

// Now that we have the genome, we create the genetic algorithm and set
// its parameters - number of generations, mutation probability, and crossover
// probability.  And finally we tell it to evolve itself.

	GASimpleGA ga(genome);
	ga.populationSize(popsize);
	ga.nGenerations(ngen);
	ga.pMutation(pmut);
	ga.pCrossover(pcross);
	ga.evolve();

// Now we print out the best genome that the GA found.

	cout << "The GA found:\n" << ga.statistics().bestIndividual() << "\n";
Ejemplo n.º 8
0
// We only use the sexual mating, so only check for that one.  Initialize each
// of the popultions and set stats appropriately.
void
GADemeGA::initialize(unsigned int seed) {
  GARandomSeed(seed);

  for(unsigned int i=0; i<npop; i++) {
    deme[i]->initialize();
    deme[i]->evaluate(gaTrue);
    pstats[i].reset(*deme[i]);
    pop->individual(i).copy(deme[i]->best());
  }
  pop->touch();
  stats.reset(*pop);

  if(!scross) GAErr(GA_LOC, className(), "initialize", gaErrNoSexualMating);
}
Ejemplo n.º 9
0
int
main(int argc, char *argv[])
{
  cout << "Example 11\n\n";
  cout << "This program illustrates the use of order-based lists.  The\n";
  cout << "list in this problem contains 25 numbers, 0 to 24.  It tries\n";
  cout << "to put them in descending order from 24 to 0.\n\n";
  cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii++],"seed") == 0) {
      GARandomSeed((unsigned int)atoi(argv[ii]));
    }
  }

// Set the default values of the parameters.

  GAParameterList params;
  GASteadyStateGA::registerDefaultParameters(params);
  params.set(gaNpopulationSize, 30);	// population size
  params.set(gaNpCrossover, 0.6);	// probability of crossover
  params.set(gaNpMutation, 0.01);	// probability of mutation
  params.set(gaNnGenerations, 1000);	// number of generations
  params.set(gaNpReplacement, 0.5);	// how much of pop to replace each gen
  params.set(gaNscoreFrequency, 10);	// how often to record scores
  params.set(gaNnReplacement, 4);	// how much of pop to replace each gen
  params.set(gaNflushFrequency, 10);	// how often to dump scores to file
  params.set(gaNscoreFilename, "bog.dat");
//  params.read("settings.txt");	        // grab values from file first
  params.parse(argc, argv, gaFalse); // parse command line for GAlib args

// Now create the GA and run it.  We first create a genome with the
// operators we want.  Since we're using a template genome, we must assign
// all three operators.  We use the order-based crossover site when we assign
// the crossover operator.

  GAListGenome<int> genome(objective);
  genome.initializer(ListInitializer);
  genome.mutator(GAListGenome<int>::SwapMutator);

// Now that we have our genome, we create the GA (it clones the genome to 
// make all of the individuals for its populations).  Set the parameters on 
// the GA then let it evolve.

  GASteadyStateGA ga(genome);
  ga.crossover(GAListGenome<int>::PartialMatchCrossover);
  ga.parameters(params);
  ga.evolve();

// Assign the best that the GA found to our genome then print out the results.

  genome = ga.statistics().bestIndividual();
  cout << "the ga generated the following list (objective score is ";
  cout << genome.score() << "):\n" << genome << "\n";
  cout << "best of generation data are in '" << ga.scoreFilename() << "'\n";
  cout << ga.parameters() << "\n";

//  char *fn;
//  ga.get(gaNscoreFilename, &fn);
//  cout << "filename is '" << fn << "'\n";

  return 0;
}
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
	srand(time(NULL));

	GARandomSeed();

	bool gameIsRunning = false;

	// SDL
	SDL_Window* window = nullptr;
	SDL_Event sdlEvent;
	SDL_Renderer* renderer = nullptr;

	TextureManager* textureManager = nullptr;
	MyB2DebugDraw* debugDraw = nullptr;
	MyB2ContactListener* contactListener = nullptr;

	// Fonts
	TTF_Font* font = nullptr;

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		return -1;
	}

	window = SDL_CreateWindow("GA Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
	if (!window)
	{
		return -1;
	}

	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

	if (!renderer)
	{
		return -1;
	}

	SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

	// Initialize SDL PNG loading
	int imgFlags = IMG_INIT_PNG;
	if (!(IMG_Init(imgFlags) & imgFlags))
	{
		printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
		return -1;
	}

	// Initialize SDL ttf
	if (TTF_Init() == -1)
	{
		printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError());
		return -1;
	}

	// Open ttf font
	font = TTF_OpenFont((dir_fonts + "OpenSans-Regular.ttf").c_str(), 12);

	textureManager = TextureManager::GetInstance();
	textureManager->Init(renderer, dir_assets);

	// Game variables
	//float dt = 1.0f / 10.0f;
	double dt_fixed = 1.0 / 60.0;
	float t = 0.0f;
	auto currentTime = std::chrono::system_clock::now();

	debugDraw = new MyB2DebugDraw(renderer);

	debugDraw->SetFlags(b2Draw::e_shapeBit
		//| b2Draw::e_aabbBit
		| b2Draw::e_jointBit
		| b2Draw::e_centerOfMassBit);

	contactListener = new MyB2ContactListener();

	// Box2D
	b2Vec2 gravity(0.0f, 0.0f);
	b2World* box2Dworld = new b2World(gravity);
	//box2Dworld->SetDebugDraw(debugDraw);
	box2Dworld->SetContactListener(contactListener);

	Game* game = new Game(window, renderer, WINDOW_WIDTH, WINDOW_HEIGHT, box2Dworld, textureManager, font);
	game->Init(dir_assets, dir_fonts, dir_textures, dt_fixed);
	gameIsRunning = true;

	vec2 curMouseClickPos;

	while (gameIsRunning)
	{
		while (SDL_PollEvent(&sdlEvent) != 0)
		{
			if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) 
			{
				SDL_GetMouseState(&curMouseClickPos.x, &curMouseClickPos.y);
			}

			if (sdlEvent.type == SDL_QUIT)
			{
				gameIsRunning = false;
			}
			else if (sdlEvent.type == SDL_KEYDOWN)
			{
				switch (sdlEvent.key.keysym.sym)
				{
				case SDLK_w:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::THRUST_FORWARD, true);
					break;
				case SDLK_s:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::THRUST_BACKWARD, true);
					break;
				case SDLK_a:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::TORQUE_LEFT, true);
					break;
				case SDLK_d:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::TORQUE_RIGHT, true);
					break;
				case SDLK_r:
					if (game->GetPlayerShip())
						game->GetPlayerShip()->Reset();
					break;
				case SDLK_e:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::STRAFE_RIGHT, true);
					break;
				case SDLK_q:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::STRAFE_LEFT, true);
					break;
				case SDLK_SPACE:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::SHOOT, true);
					break;
				case SDLK_LSHIFT:
					game->GetPlayerShip()->ActivateEventTrigger(Ship::STABILIZE, true);
					break;
				case SDLK_ESCAPE:
					gameIsRunning = false;
					break;
				}
			}
			else if (sdlEvent.type == SDL_KEYUP)
			{
				switch (sdlEvent.key.keysym.sym)
				{
					case SDLK_w:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::THRUST_FORWARD, false);
						break;
					case SDLK_s:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::THRUST_BACKWARD, false);
						break;
					case SDLK_a:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::TORQUE_LEFT, false);
						break;
					case SDLK_d:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::TORQUE_RIGHT, false);
						break;
					case SDLK_e:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::STRAFE_RIGHT, false);
						break;
					case SDLK_q:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::STRAFE_LEFT, false);
						break;
					case SDLK_SPACE:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::SHOOT, false);
						break;
					case SDLK_LSHIFT:
						game->GetPlayerShip()->ActivateEventTrigger(Ship::STABILIZE, false);
						break;
				}
			}
		}

		// Update game
		//game->Update(dt);

		// Draw game
		//game->Draw();

		// Present final canvas
		//SDL_RenderPresent(renderer);
	}

	if (game)
	{
		delete game;
		game = nullptr;
	}

	if (debugDraw)
	{
		delete debugDraw;
		debugDraw = nullptr;
	}

	if (contactListener)
	{
		delete contactListener;
		contactListener = nullptr;
	}

	TextureManager::Destroy();
	textureManager = nullptr;

	TTF_CloseFont(font);
	font = nullptr;

	SDL_DestroyWindow(window);
	window = nullptr;

	SDL_DestroyRenderer(renderer);
	renderer = nullptr;

	TTF_Quit();
	IMG_Quit();
	SDL_Quit();

	_CrtDumpMemoryLeaks();

    return 0;
}
Ejemplo n.º 11
0
int
main(int argc, char *argv[])
{
  cout << "Example 8\n\n";
  cout << "This program runs a steady-state GA whose objective function\n";
  cout << "tries to maximize the size of the list and tries to make lists\n";
  cout << "that contain the number 101 in the nodes.  The lists contain\n";
  cout << "ints in the nodes.\n\n";
  cout.flush();

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  for(int i=1; i<argc; i++) {
    if(strcmp(argv[i++],"seed") == 0)
      GARandomSeed((unsigned int)atoi(argv[i]));
  }

// Create the initial genome for the genetic algorithm to use.  Set the
// initializer and mutation before we make the genetic algorithm.

  GAListGenome<int> genome(objective);
  genome.initializer(ListInitializer);
//  genome.mutator(GAListGenome<int>::SwapMutator);
  genome.mutator(GAListGenome<int>::DestructiveMutator);

// Now that we have a genome, we use it to create our GA.  After creating the
// GA we set the parameters and tell the GA to use sigma truncation scaling
// rather than the default (linear scaling).  Set the crossover to single
// point crossover.  The genetic algorithm handles crossover since genomes
// don't know about other genomes.  We could set the crossover on the genome
// if we wanted - either way will work.

  GASteadyStateGA ga(genome);
  GASigmaTruncationScaling scale;
  ga.scaling(scale);
  ga.crossover(GAListGenome<int>::OnePointCrossover);

// Set the default parameters we want to use, then check the command line for
// other arguments that might modify these.

  ga.set(gaNpopulationSize, 40);	// population size
  ga.set(gaNpCrossover, 0.6);		// probability of crossover
  ga.set(gaNpMutation, 0.05);		// probability of mutation
  ga.set(gaNnGenerations, 50);		// number of generations
  ga.set(gaNscoreFrequency, 1);		// how often to record scores
  ga.set(gaNflushFrequency, 10);	// how often to dump scores to file
  ga.set(gaNselectScores,		// which scores should we track?
	 GAStatistics::Maximum|GAStatistics::Minimum|GAStatistics::Mean);
  ga.set(gaNscoreFilename, "bog.dat");
  ga.parameters(argc, argv);

// Evolve the genetic algorithm then dump out the results of the run.

  ga.evolve();

  genome = ga.statistics().bestIndividual();
//  cout << "the ga generated the list:\n" << genome << "\n";
  cout << "the list contains " << genome.size() << " nodes\n";
  cout << "the ga used the parameters:\n" << ga.parameters() << "\n";

  return 0;
}