Esempio n. 1
0
population::population(int N_in, int L_in, double r_in, int seed_in, gsl_rng* rng_in, vector< vector<double> >& fit) {
    try {
        if (fit.size() != N_in || fit[0].size() != L_in) {throw "Incorrect Fitness Landscape dimensions!";}
        else if (r_in < 0 || r_in > 1 || N_in < 0 || L_in <0) {throw "Bad inputs. Check arguments.";}
        else {
            N = N_in;
            L = L_in;
            r = r_in;
            gen_pop = 0;
            neutral = false;
            avgFit = 0;
            selective_weight = vector<double>(N);
            genetic_weight = vector< vector<int> >(N,vector<int>(L));
            fixations = vector< vector<fixation_event> > (N);
            seed = seed_in ? seed_in : get_random_seed();
            rng = rng_in;
            gsl_rng_set(rng,seed);
            blockHist = gsl_histogram_alloc(L);
            gsl_histogram_set_ranges_uniform(blockHist,1,L+1); //Questionable range choice. As it stands now, the bins are partitioned as follows {[1,2),[2,3)......[L,L+1)}. Thus if all have length L, then average will come out to be (L+.5). Will have to rescale.
            map<int,double> genome_fit;
            for(int i=0;i<N;i++) {
                genome_fit = convert_vector_toMap(fit[i]);
                if (!genome_fit.empty()) {pop.push_back(genome(i, L, rng, genome_fit));}
                else {pop.push_back(genome(i,L,rng));}
                avgFit += pop[i].get_fit();
            }
            avgFit/=N;
            update_selection_weights();
            updateBlockSizes();
        }
    }
    catch (const char* Message) {
        cout << "Error:" << Message << "\n";
    }
}
Esempio n. 2
0
int
main(int argc, char** argv) {
  cout << "This program tries to fill a 1DBinaryStringGenome with\n";
  cout << "alternating 1s and 0s using a simple genetic algorithm.  It runs\n";
  cout << "in parallel using PVM and a population on each process.\n\n";
  cout.flush();

  GA1DBinaryStringGenome genome(GENOME_LENGTH);
  PVMDemeGA ga(genome);
  ga.parameters(argc, argv);
  ga.parameters("settings.txt");
  if(ga.spawn("slave") < 0) exit(1);

  cout << "initializing..." << endl;
  ga.initialize();
  cout << ga.statistics().bestIndividual() << endl;
  cout << "evolving..." << endl;
  while(!ga.done()){
    ga.step();
    cout << ga.statistics().bestIndividual() << endl;
  }
  ga.flushScores();

  cout << "\nThe GA found an individual with a score of ";
  cout << ga.statistics().bestIndividual().score() << endl;

  return 0;
}
Esempio n. 3
0
//Overloaded Constructors
population::population(int N_in, int L_in, double r_in, int seed_in, gsl_rng* rng_in) { //Neutral Evolution!
    try {
        if (r_in < 0 || r_in > 1 || N_in < 0 || L_in <0) {throw "Bad inputs. Check arguments.";}
        else {
            N = N_in;
            L = L_in;
            r = r_in;
            gen_pop = 0;
            neutral = true;
            avgFit = 0;
            selective_weight = vector<double>(N); //All zeros
            genetic_weight = vector< vector<int> >(N,vector<int>(L));
            fixations = vector< vector<fixation_event> > (N);
            seed = seed_in ? seed_in:get_random_seed();
            rng = rng_in;
            gsl_rng_set(rng,seed);
            blockHist = gsl_histogram_alloc(L);
            gsl_histogram_set_ranges_uniform(blockHist,1,L+1);
            for(int i=0;i<N;i++) {
                pop.push_back(genome(i,L,rng));
            }
            updateBlockSizes();
        }
    }
    catch(const char* Message) {cout << "Error: " << Message << "\n";}
}
Esempio n. 4
0
//-------------------------------------------------------------------------
//	this constructor creates a base genome from supplied values and creates 
//	a population of 'size' similar (same topology, varying weights) genomes
//-------------------------------------------------------------------------
Cga::Cga(int  size,
         int  inputs,
         int  outputs,
         HWND hwnd,
         int  cx,
         int  cy):  m_iPopSize(size),
                    m_iGeneration(0),
                    m_pInnovation(NULL),
                    m_iNextGenomeID(0),
                    m_iNextSpeciesID(0),
                    m_iFittestGenome(0),
                    m_dBestEverFitness(0),
                    m_dTotFitAdj(0),
                    m_dAvFitAdj(0),
                    m_hwnd(hwnd),
                    cxClient(cx),
                    cyClient(cy)
{
	//create the population of genomes
	for (int i=0; i<m_iPopSize; ++i)
	{
			m_vecGenomes.push_back(CGenome(m_iNextGenomeID++, inputs, outputs));
	}

	//create the innovation list. First create a minimal genome
	CGenome genome(1, inputs, outputs);

	//create the innovations
  m_pInnovation = new CInnovation(genome.Genes(), genome.Neurons());

  //create the network depth lookup table
  vecSplits = Split(0, 1, 0);
}
Esempio n. 5
0
QString NeatGenome::getGenomeAsString() const {
	QString genomeString;
	QTextStream genome(&genomeString);
	bool first = true;
	for(QListIterator<NeatNodeGene*> i(mNodes); i.hasNext();) {
		NeatNodeGene *node = i.next();
		if(first) {
			first = false;
		}
		else {
			genome << "|";
		}
		genome << node->mId << "," << node->mType;
	}
	genome << "#";
	first = true;
	for(QListIterator<NeatConnectionGene*> i(mConnectionGenes); i.hasNext();) {
		NeatConnectionGene *link = i.next();
		if(first) {
			first = false;
		}
		else {
			genome << "|";
		}
		genome << link->mId << "," << link->mOutputNode << "," << link->mInputNode << "," 
			   << link->mWeight << "," << (link->mEnabled ? "1" : "0");
	}	

	return genomeString;
}
Esempio n. 6
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;
}
Esempio n. 7
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;
}
int main(int argc, char *argv[]) {
	cout << "Example 6\n\n";
	cout << "This example uses a SteadyState GA and Tree<int> genome.  It\n";
	cout << "tries to maximize the size of the tree genomes that it\n";
	cout << "contains.  The genomes contain ints in its 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.

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

// Set the default values of the parameters.

	GAParameterList params;
	GASteadyStateGA::registerDefaultParameters(params);
	params.set(gaNpopulationSize, 30);
	params.set(gaNpCrossover, 0.7);
	params.set(gaNpMutation, 0.01);
	params.set(gaNnGenerations, 100);
	params.set(gaNscoreFilename, "bog.dat");
	params.set(gaNscoreFrequency, 10); // record score every 10th generation
	params.set(gaNflushFrequency, 10); // dump scores every 10th recorded score
	params.parse(argc, argv, gaFalse); // Parse the command line for GAlib args.

// Now create the GA and run it.  We first create a chromsome with the
// operators we want.  Once we have the genome set up, create the genetic
// algorithm, set the parameters, and let it go.

	GATreeGenome<int> genome(objective);
	genome.initializer(TreeInitializer);
	genome.mutator(GATreeGenome<int>::SwapSubtreeMutator);

	GASteadyStateGA ga(genome);
	ga.parameters(params);
	ga.evolve(seed);

	genome = ga.statistics().bestIndividual();
//  cout << "the ga generated this tree:\n" << genome << "\n";
	cout << genome.size() << " nodes, " << genome.depth() << " levels deep.\n";
	cout << "best of generation data are in '" << ga.scoreFilename() << "'\n";

	return 0;
}
Esempio n. 9
0
void GenomeFile::loadGenomeFileIntoMap() {

    string genomeLine;
    int lineNum = 0;
    vector<string> genomeFields;            // vector for a GENOME entry

    // open the GENOME file for reading
    ifstream genome(_genomeFile.c_str(), ios::in);
    if ( !genome ) {
        cerr << "Error: The requested genome file (" << _genomeFile << ") could not be opened. Exiting!" << endl;
        exit (1);
    }

    while (getline(genome, genomeLine)) {

        Tokenize(genomeLine,genomeFields);  // load the fields into the vector
        lineNum++;

        // ignore a blank line
        if (genomeFields.size() > 0) {
            if (genomeFields[0].find("#") == string::npos) {

                // we need at least 2 columns
                if (genomeFields.size() >= 2) {
                    char *p2End;
                    long c2;
                    // make sure the second column is numeric.
                    c2 = strtol(genomeFields[1].c_str(), &p2End, 10);

                    // strtol  will set p2End to the start of the string if non-integral, base 10
                    if (p2End != genomeFields[1].c_str()) {
                        string chrom       = genomeFields[0];
                        int size           = atoi(genomeFields[1].c_str());
                        _chromSizes[chrom] = size;
                        _chromList.push_back(chrom);
                        _startOffsets.push_back(_genomeLength);
                        _genomeLength += size;
                    }
                }
                else {
                    cerr << "Less than the req'd two fields were encountered in the genome file (" << _genomeFile << ")";
                    cerr << " at line " << lineNum << ".  Exiting." << endl;
                    exit (1);
                }
            }
        }
        genomeFields.clear();
    }
}
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";
Esempio n. 11
0
int main(int argc, char **argv)
{
  // MPI init
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &mpi_tasks);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);

  // 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
  unsigned int seed = 0;
  for(int i=1 ; i<argc ; i++)
    if(strcmp(argv[i++],"seed") == 0)
      seed = atoi(argv[i]);

  // Declare variables for the GA parameters and set them to some default values.
  int popsize  = 2; // Population
  int ngen     = 2; // Generations
  float pmut   = 0.03;
  float pcross = 0.65;

  // popsize / mpi_tasks must be an integer
  popsize = mpi_tasks * int((double)popsize/(double)mpi_tasks+0.999);

  // Create the phenotype for two variables.  The number of bits you can use to
  // represent any number is limited by the type of computer you are using.
  // For this case we use 10 bits for each var, ranging the square domain [0,5*PI]x[0,5*PI]
  ///GABin2DecPhenotype map;
  ///GABin2DecPhenotype map;
  ///map.add(10, 0.0, 5.0 * M_PI);
  ///map.add(10, 0.0, 5.0 * M_PI);

  // Create the template genome using the phenotype map we just made.
  ///GABin2DecGenome genome(map, objective);
  //GA1DArrayGenome<double> genome(2, objective);
  GA1DArrayGenome<double> genome(3, dynamixObjective);
  // define own initializer, can do the same for mutator and comparator
  genome.initializer(::Initializer);

  // Now create the GA using the genome and run it. We'll use sigma truncation
  // scaling so that we can handle negative objective scores.
  GASimpleGA ga(genome); // TODO change to steady-state
  GALinearScaling scaling;
  ga.minimize();		// by default we want to minimize the objective
  ga.populationSize(popsize);
  ga.nGenerations(ngen);
  ga.pMutation(pmut);
  ga.pCrossover(pcross);
  ga.scaling(scaling);
  if(mpi_rank == 0)
    ga.scoreFilename("evolution.txt");
  else
    ga.scoreFilename("/dev/null");
  ga.scoreFrequency(1);
  ga.flushFrequency(1);
  ga.selectScores(GAStatistics::AllScores);
  // Pass MPI data to the GA class
  ga.mpi_rank(mpi_rank);
  ga.mpi_tasks(mpi_tasks);
  ga.evolve(seed);

  // Dump the GA results to file
  if(mpi_rank == 0)
  {
    genome = ga.statistics().bestIndividual();
    printf("GA result:\n");
    printf("x = %f, y = %f\n",
	genome.gene(0), genome.gene(1));
  }

  MPI_Finalize();

  return 0;
}
Esempio n. 12
0
int
main(int, char** argv) {
  int status = 0;
  int mytid = pvm_mytid();
  int masterid = pvm_parent();
  if(mytid < 0 || masterid < 0) {
    cerr << "\n" << argv[0] << ": Couldn't get slave/master IDs.  Aborting.\n";
    exit(1);
  }

  GA1DBinaryStringGenome genome(GENOME_LENGTH,GenomeEvaluator);
  GASteadyStateGA ga(genome);

  status = pvm_initsend(PvmDataDefault);
  status = pvm_send(masterid, MSG_READY);

  int done = 0;
  while(!done){
    int bufid = pvm_recv(-1, -1);
    int ival;
    if(bufid >= 0) {
      int bytes, msgtag, tid;
      status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
      switch(msgtag) {
      case MSG_DONE:
	done = 1;
	break;

      case MSG_SET_POPULATION_SIZE:
	ival = gaDefPopSize;
	status = pvm_upkint(&ival, 1, 1);
	ga.populationSize(ival);
	break;

      case MSG_INITIALIZE:
	ga.initialize();
	break;

      case MSG_STEP:
	ival = 0;
	status = pvm_upkint(&ival, 1, 1);
	for(int i=0; i<ival; i++)
	  ga.step();
	ival = ga.generation();
	  status = pvm_initsend(PvmDataDefault);
	status = pvm_pkint(&ival, 1, 1);
	status = pvm_send(masterid, MSG_STEP_COMPLETE);
	break;

      case MSG_INCOMING_MIGRATION:
	RecvMigration(ga);
	break;

      case MSG_SEND_MIGRATION:
	{
	  int toid = 0, count = 0;
	  status = pvm_upkint(&toid, 1, 1);
	  status = pvm_upkint(&count, 1, 1);
	  SendMigration(toid, ga, count);
	}
	break;

      case MSG_SEND_POPULATION:
	SendPopulation(masterid, ga.population());
	break;

      case MSG_SEND_STATISTICS:
	SendStatistics(masterid, ga.statistics());
	break;

      default:
	cerr << argv[0] << ": unknown msgtag: " << msgtag << "\n";
	break;
      }
    }
    else {
      cerr << argv[0] << ": error from pvm_recv: " << bufid << "\n";
    }
  }

  pvm_exit();
  return 0;
}
Esempio n. 13
0
genome genome::operator+(genome g2){
    try {
        if (g2.L != L) {
            throw "Genome sizes are not equal!";
        }
        else {
            vector<block> offspring; 
            //gsl_rng_set(rng,seed);
            int crossPoint = (int)gsl_rng_uniform_int(rng,L-1); //Obtain the random crossover point. 
            //Compute Crossover
            int index1 = find_block_index(crossPoint,0,g.size());
            int index2 = g2.find_block_index(crossPoint,0,g2.g.size());
            for (int i=0; i<index1; i++) {
                offspring.push_back(g[i]);
            }
            if (g[index1].dat != g2.g[index2].dat){
                //If they are different -> create two blocks
                if (g[index1].fit_loci.empty() && g2.g[index2].fit_loci.empty()) { //If neutral, don't worry about updating fitness
                    if (crossPoint >= g[index1].l) {
                        offspring.push_back(block(g[index1].l,crossPoint,g[index1].dat));
                    }
                    if (crossPoint+1 <= g2.g[index2].r) {
                        offspring.push_back(block(crossPoint+1,g2.g[index2].r,g2.g[index2].dat));
                    }
                }
                else { //Partition up fitness hash tables amongst the composite blocks.
                    map<int,double> fit_loci_b1; map<int,double> fit_loci_b2;
                    if (!g[index1].fit_loci.empty()) {
                        fit_loci_b1.insert(g[index1].fit_loci.begin(),g[index1].fit_loci.lower_bound(crossPoint+1));
                    }
                    if (!g2.g[index2].fit_loci.empty()) {
                        fit_loci_b2.insert(g2.g[index2].fit_loci.lower_bound(crossPoint+1),g2.g[index2].fit_loci.end());
                    }
                    //Create two blocks - conditional on the fact that the crossover point didn't fall between blocks. 
                    //If so, then we don't need to create one or the other or both!
                    if (crossPoint >= g[index1].l) {
                        if (fit_loci_b1.empty()) {offspring.push_back(block(g[index1].l,crossPoint,g[index1].dat));}
                        else {offspring.push_back(block(g[index1].l,crossPoint,g[index1].dat, fit_loci_b1));}
                    }
                    if (crossPoint+1 <= g2.g[index2].r) {
                        if (fit_loci_b2.empty()) {offspring.push_back(block(crossPoint+1,g2.g[index2].r,g2.g[index2].dat));}
                        else {offspring.push_back(block(crossPoint+1,g2.g[index2].r,g2.g[index2].dat, fit_loci_b2));}
                    }
                }
            }
            else{
                //Else create one (merge event).
                block merge_block;
                if (g[index1].fit_loci.empty() && g2.g[index2].fit_loci.empty()) { //If neutral, don't worry about updating fitness
                    merge_block = block(g[index1].l,g2.g[index2].r,g[index1].dat);
                }
                else { //Stitch together the fitness hash tables for each block to create one composite hash table.
                    map<int,double> fit_loci;
                    if (!g[index1].fit_loci.empty()) {
                        fit_loci.insert(g[index1].fit_loci.begin(),g[index1].fit_loci.lower_bound(crossPoint+1));
                    }
                    if (!g2.g[index2].fit_loci.empty()) {
                        fit_loci.insert(g2.g[index2].fit_loci.lower_bound(crossPoint+1),g2.g[index2].fit_loci.end());
                    }
                    if (fit_loci.empty()) {merge_block = block(g[index1].l,g2.g[index2].r,g[index1].dat);}
                    else {merge_block = block(g[index1].l,g2.g[index2].r,g[index1].dat,fit_loci);}
                }
                offspring.push_back(merge_block);
            }
            for (int j=(index2+1); j<g2.g.size();j++) {
                offspring.push_back(g2.g[j]);
            }
            return genome(rng,offspring);
            /*
            while(!g[i].containsCross(loc1,crossPoint) || !g2.g[j].containsCross(loc2,crossPoint)) {
                //Create offspring genome if i is still iterating.
                if (i>=j && !g[i].containsCross(loc1,crossPoint)) { //If i stops iterating, it will immediately become less than j.
                    offspring.push_back(g[i]);
                }
                //Iterate through both genomes simultaneously, provided they don't individually contain the crossover point.
                if (!g[i].containsCross(loc1,crossPoint)) {
                    loc1 += g[i].len;
                    i++; 
                }
                if (!g2.g[j].containsCross(loc2,crossPoint)) {
                    loc2 += g2.g[j].len;
                    j++;
                }
            }
            vector<block> newBlocks = crossBlocks(g[i],g2.g[j], loc1, loc2, crossPoint); 
            for (int k = 0; k < newBlocks.size(); k++) {
                offspring.push_back(newBlocks[k]);
            }   
            //Traverse the second genome until it ends. 
            for (int k = j+1; k < g2.g.size(); k++) {
                offspring.push_back(g2.g[k]); //Transmit block from second parent.
            }
            */ 
        }
    }
    catch(const char* Message) {
        cout << "Error:" << Message << "\n";
    }
}
    /**
     * Test to see if the GA can derive the correct answer
     */
    void dataFrameTest()
    {
      // load data frame
      cout << "Importing data frame... ";
      shared_ptr<DataFrame> df(new DataFrame);
      fstream fs("OttawaCars.xml", ios_base::in);
      if (fs.is_open() == false)
      {
        throw Exception("Error opening OttawaGroundCover.xml");
      }
      df->import(fs);
      cout << "done." << endl;

      shared_ptr<CalculatorGenome> genome(new CalculatorGenome());
      genome->setInitializationDepth(4);
      genome->addBasicMathNodeTypes();

      // create source node for each factor
      for (unsigned int i = 0; i < df->getNumFactors(); i++)
      {
        shared_ptr<DataFrameCalculatorNodeSource> src(new DataFrameCalculatorNodeSource(df, i));
        string label = df->getFactorLabelFromIndex(i);
        if (label != "MAX_Z_GROUND" && label != "MIN_Z_GROUND" && 
          label != "MAX_Z_AERIAL" && label != "MIN_Z_AERIAL")
        {
          genome->addNodeType(src, label, 2.0 / (double)df->getNumFactors());
        }
      }

      // create a fitness function using symmetric uncertainty
      shared_ptr<FeatureScoreCalculator> fsc(new SymmetricUncertaintyCalculator());
      shared_ptr<FeatureScoreFitnessFunction> fitness(new FeatureScoreFitnessFunction(df, fsc));

      GeneticAlgorithm ga(genome, fitness);
      ga.setPopulationSize(500);

      // population size
      // mutation rate
      // mutation severity
      // free pass
      // keep best
      // mating percent
      // fresh meat

      int c = 0;
      for (unsigned int s = 0; s < 300; s++)
      {
        ga.step();
        c+= ga.getPopulation().size();
        shared_ptr<CalculatorGenome> best = 
          dynamic_pointer_cast<CalculatorGenome>(ga.getBestGenome());
        cout << c << "\t" << best->getScore() << "\t" << best->toString() << endl;
//         if (1 / best->getScore() < 1.0)
//         {
//           break;
//         }
        //cout << endl;
        for (unsigned int i = 0; i < ga.getPopulation().size() && i < 10; i++)
        {
          cout << "  " << ga.getPopulation()[i]->getScore() << "\t" << 
            ga.getPopulation()[i]->toString() << endl;
        }
      }
    }
Esempio n. 15
0
int
main(int argc, char *argv[])
{
  cout << "Example 19\n\n";
  cout << "This program runs the DeJong test problems.\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.

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

  GAParameterList params;
  GASteadyStateGA::registerDefaultParameters(params);
  params.set(gaNpopulationSize, 30);	// population size
  params.set(gaNpCrossover, 0.9);	// probability of crossover
  params.set(gaNpMutation, 0.001);	// probability of mutation
  params.set(gaNnGenerations, 400);	// number of generations
  params.set(gaNpReplacement, 0.25);	// how much of pop to replace each gen
  params.set(gaNscoreFrequency, 10);	// how often to record scores
  params.set(gaNflushFrequency, 50);	// how often to dump scores to file
  params.set(gaNscoreFilename, "bog.dat");
  params.parse(argc, argv, gaFalse);    // parse command line for GAlib args

  int whichFunction = 0;

  for(int i=1; i<argc; i++){
    if(strcmp("function", argv[i]) == 0 || strcmp("f", argv[i]) == 0){
      if(++i >= argc){
        cerr << argv[0] << ": you must specify a function (1-5)\n";
        exit(1);
      }
      else{
	whichFunction = atoi(argv[i]) - 1;
	if(whichFunction < 0 || whichFunction > 4){
	  cerr << argv[0] << ": the function must be in the range [1,5]\n";
	  exit(1);
	}
        continue;
      }
    }
    else if(strcmp("seed", argv[i]) == 0){
      if(++i < argc) continue;
      continue;
    }
    else {
      cerr << argv[0] << ":  unrecognized arguement: " << argv[i] << "\n\n";
      cerr << "valid arguements include standard GAlib arguments plus:\n";
      cerr << "  f\twhich function to evaluate (all)\n";
      cerr << "parameters are:\n\n" << params << "\n\n";
      exit(1);
    }
  }

// Create the phenotype map depending on which dejong function we are going
// to be running.

  GABin2DecPhenotype map;
  switch(whichFunction){
  case 0:
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    break;

  case 1:
    map.add(16, -2.048, 2.048);
    map.add(16, -2.048, 2.048);
    break;

  case 2:
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    map.add(16, -5.12, 5.12);
    break;

  case 3:
    {
      for(int j=0; j<30; j++)
	map.add(16, -1.28, 1.28);
    }
    break;

  case 4:
    map.add(16, -65.536, 65.536);
    map.add(16, -65.536, 65.536);
    break;

  default:
    map.add(16, 0, 0);
    break;
  }

// Now create the sample genome and run the GA.

  GABin2DecGenome genome(map, objective[whichFunction]);
  //  GAStatistics stats;

  GASteadyStateGA ga(genome);
  ga.parameters(params);
  GASigmaTruncationScaling scaling;
  ga.scaling(scaling);

  cout << "running DeJong function number " << (whichFunction + 1) << " ...\n";

  ga.evolve(seed);

  cout << "the ga generated:\n" << ga.statistics().bestIndividual() << "\n";
  cout << "\nthe statistics for the run are:\n" << ga.statistics();
  cout << "\nbest-of-generation data are in 'bog.dat'\n";
  cout.flush();

  return 0;
}
Esempio n. 16
0
CRAlgorithmStatistics CRGenetics::execute_one_vs_all(std::vector<std::vector<functions::RealVector> > &traj, bool initialize) {
  functions::FormattedTime t1, t2;
  struct timeval t;
  gettimeofday(&t, NULL);
  
  t1.getTime();
  CRAlgorithmStatistics ret;
  GeneticConfig &config = dynamic_cast<GeneticConfig&>(* (this->config));
  
  sim->setTrajectories(traj);
  
  if (config.debug) {
    cout << "CRGenetics::run --> Associating the proper functions to genome algorithm\n";
  }
    
  if (bounds == NULL) {
    cerr << "CRGenetics::execute_one_vs_all() --> This should not happen: bounds = NULL\n";
    return ret;
  } 
  
  if (initialize) {
    GARealGenome genome(*bounds, CRALgorithmOneObjective, (void *)this);
    setGeneticOperators(genome);
  
    // The same process has to be applied to the population
    GAPopulation population(genome, config.population);
    if (config.initializer_type == "Deterministic") {
      population.initializer(GAPopulationInitializer);
    }

    delete algorithm;
    algorithm = new GASimpleGA(population);
    setGeneticParameters();
  }
  
  // Run genetics
  if (!config.custom_evolution) {
      if (config.debug) {
	cout << "CRGenetics::run --> Letting the algorithm evolve.\n";
      }
      algorithm->evolve();
    } else {
      customEvolution(ret, t, initialize);
    }
    
  // Calculate spended time and show it
  t2.getTime();
  ret.setExecutionTime(t2 - t1);
  
  // Get best flight plan
  GARealGenome &best = (GARealGenome &) algorithm->statistics().bestIndividual();
  FlightPlan best_wp(get1vsAllFlightPlan(geneToVector(best)));
    
  // Get the minimum objetive value and store it for statistics purposes...
  ret.setMinObjetive( best.score() );
    
  // Show the best flight plan
  cout << "CRGenetics::run --> Evolution finished. Best flight plan:\n";
  cout << best_wp.toString() << endl;
  
  sim->getParticle(0)->getController()->setFlightPlan(best_wp);
  
  if (config.export_trajectories) {
	if (sim->exportTrajectory(config.trajectory_filename)) {
	  cout << "Trajectories exported successfully.\n";
	}
      }
    
  return ret;
}
Esempio n. 17
0
int
main(int argc, char **argv)
{
  cout << "Example 9\n\n";
  cout << "This program finds the maximum value in the function\n";
  cout << "  y = - x1^2 - x2^2\n";
  cout << "with the constraints\n";
  cout << "     -5 <= x1 <= 5\n";
  cout << "     -5 <= x2 <= 5\n";
  cout << "\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.

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

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

  int popsize  = 30;
  int ngen     = 100;
  float pmut   = 0.01;
  float pcross = 0.6;

// Create a phenotype for two variables.  The number of bits you can use to
// represent any number is limited by the type of computer you are using.  In
// this case, we use 16 bits to represent a floating point number whose value
// can range from -5 to 5, inclusive.  The bounds on x1 and x2 can be applied
// here and/or in the objective function.

  GABin2DecPhenotype map;
  map.add(16, -5, 5);
  map.add(16, -5, 5);

// Create the template genome using the phenotype map we just made.

  GABin2DecGenome genome(map, objective);

// Now create the GA using the genome and run it.  We'll use sigma truncation
// scaling so that we can handle negative objective scores.

  GASimpleGA ga(genome);
  GASigmaTruncationScaling scaling;
  ga.populationSize(popsize);
  ga.nGenerations(ngen);
  ga.pMutation(pmut);
  ga.pCrossover(pcross);
  ga.scaling(scaling);
  ga.scoreFilename("bog.dat");
  ga.scoreFrequency(10);
  ga.flushFrequency(50);
  ga.evolve(seed);

// Dump the results of the GA to the screen.

  genome = ga.statistics().bestIndividual();
  cout << "the ga found an optimum at the point (";
  cout << genome.phenotype(0) << ", " << genome.phenotype(1) << ")\n\n";
  cout << "best of generation data are in '" << ga.scoreFilename() << "'\n";

  return 0;
}
Esempio n. 18
0
int main(int argc, char **argv)
{
  std::chrono::time_point<std::chrono::system_clock> program_start, program_end;
  program_start = std::chrono::system_clock::now();

  // MPI init - this has to happen before getopt() so the argv can be properly trimmed
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &mpi_tasks);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
                         
  char hostname[1024];                                                                                                       
  hostname[1023] = '\0';                                          
  gethostname(hostname, 1023);

  srand(time(NULL));

  double mutation_rate = 0.01;
  double crossover_rate = 0.01;
  int population_size = 10;
  int n_generations = 10;

    char c='h';
  // Handle command line arguments
  while ((c = getopt (argc, argv, "t:g:p:c:m:s:h:e:x:")) != -1)
    switch (c)
      {
      case 'x':
	experiment_path = optarg;
      break;
      case 't':
	n_trials = atoi(optarg);
	break;
      case 'g':
        n_generations = atoi(optarg);
        break;
      case 'p':
        population_size = atoi(optarg);
        break;
      case 'm':
        mutation_rate = strtod(optarg, NULL);
	break;
      case 'c':
	crossover_rate = strtod(optarg, NULL);
	break;
      case 's':
        mutation_stdev = strtod(optarg, NULL);
	break;
      case 'e':
        elitism = atoi(optarg);
	break;
      case 'h':
	printf("Usage: %s -p {population size} -g {number of generations} -t {number of trials} -c {crossover rate} -m {mutation rate} -s {mutation standard deviation} -e {elitism 0 or 1}", argv[0]);
	break;
      case '?':
        if (optopt == 'p')
          fprintf (stderr, "Option -%c requires an argument specifying the population size.\n", optopt);
	else if (optopt == 'g')
	  fprintf (stderr, "Option -%c requires an argument specifying the number of generations.\n", optopt);
	else if (optopt == 't')
	  fprintf (stderr, "Option -%c requires an argument specifying the number of trials.\n", optopt);
	else if (optopt == 'c')
	  fprintf (stderr, "Option -%c requires an argument specifying the crossover rate.\n", optopt);
	else if (optopt == 'm')
	  fprintf (stderr, "Option -%c requires an argument specifying the mutation rate.\n", optopt);
	else if (optopt == 's')
	  fprintf (stderr, "Option -%c requires an argument specifying the mutation standard deviation.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
	printf("Usage: %s -p {population size} -g {number of generations} -t {number of trials} -c {crossover rate} -m {mutation rate} -s {mutation standard deviation}", argv[0]);
        abort ();
      }

  if (experiment_path.empty())
    {
      printf("Usage: %s -p {population size} -g {number of generations} -t {number of trials} -c {crossover rate} -m {mutation rate} -s {mutation standard deviation} -x {argos experiment file}\n", argv[0]);
      exit(1);
    }

  float max_float = std::numeric_limits<float>::max();

    //printf("%s:\tworker %d ready.\n", hostname, mpi_rank);                                          

  // 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
  unsigned int seed = 12345;
  for(int i=1 ; i<argc ; i++)
    if(strcmp(argv[i++],"seed") == 0)
      seed = atoi(argv[i]);
	
  // popsize / mpi_tasks must be an integer
  population_size = mpi_tasks * int((double)population_size/(double)mpi_tasks+0.999);
  
  if (mpi_rank==0)
    {
      printf("Population size: %d\nNumber of trials: %d\nNumber of generations: %d\nCrossover rate: %f\nMutation rate: %f\nMutation stdev: %f\nAllocated MPI workers: %d\n", population_size, n_trials, n_generations, crossover_rate, mutation_rate, mutation_stdev, mpi_tasks);
      	printf("elitism: %d\n", elitism);
    }

  // Define the genome
  GARealAlleleSetArray allele_array;
  
  allele_array.add(0, 1.0); // Probability of switching to search
  allele_array.add(0, 1.0); // Probability of returning to nest
  allele_array.add(0, 4*M_PI); // Uninformed search variation
  allele_array.add(0, 20); // Rate of informed search decay
  allele_array.add(0, 20); // Rate of site fidelity
  allele_array.add(0, 20); // Rate of laying pheremone
  allele_array.add(0, 20); // Rate of pheremone decay
  
    
  // Create the template genome using the phenotype map we just made.
  GARealGenome genome(allele_array, objective);
  genome.crossover(GARealUniformCrossover);
  genome.mutator(GARealGaussianMutatorStdev); // Specify our version of the Gaussuan mutator
  genome.initializer(CPFAInitializer);
 
  // Now create the GA using the genome and run it.
  GASimpleGA ga(genome);
  GALinearScaling scaling;
  ga.maximize();		// Maximize the objective
 
  ga.populationSize(population_size);
  ga.nGenerations(n_generations);
  ga.pMutation(mutation_rate);
  ga.pCrossover(crossover_rate);
  ga.scaling(scaling);
  if (elitism == 1)
    ga.elitist(gaTrue);
  else
    ga.elitist(gaFalse);
  if(mpi_rank == 0)
    ga.scoreFilename("evolution.txt");
  else
    ga.scoreFilename("/dev/null");
  ga.recordDiversity(gaTrue);
  ga.scoreFrequency(1);
  ga.flushFrequency(1);
  ga.selectScores(GAStatistics::AllScores);
  
  // Pass MPI data to the GA class
  ga.mpi_rank(mpi_rank);
  ga.mpi_tasks(mpi_tasks);
  //ga.evolve(seed); // Manual generations

// initialize the ga since we are not using the evolve function
  ga.initialize(seed); // This is essential for the mpi workers to be sychronized

    // Name the results file with the current time and date
 time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    stringstream ss;

    boost::filesystem::path exp_path(experiment_path);
    
    ss << "results/CPFA-evolution-"
       << exp_path.stem().string() << '-'
       <<GIT_BRANCH<<"-"<<GIT_COMMIT_HASH<<"-"
       << (now->tm_year) << '-'
       << (now->tm_mon + 1) << '-'
       <<  now->tm_mday << '-'
       <<  now->tm_hour << '-'
       <<  now->tm_min << '-'
       <<  now->tm_sec << ".csv";

    string results_file_name = ss.str();

    if (mpi_rank == 0)
      {
    // Write output file header
    ofstream results_output_stream;
	results_output_stream.open(results_file_name, ios::app);
	results_output_stream << "Population size: " << population_size << "\nNumber of trials: " << n_trials << "\nNumber of generations: "<< n_generations<<"\nCrossover rate: "<< crossover_rate<<"\nMutation rate: " << mutation_rate << "\nMutation stdev: "<< mutation_stdev << "Algorithm: CPFA\n" << "Number of searchers: 6\n" << "Number of targets: 256\n" << "Target distribution: power law" << endl;
	results_output_stream << "Generation" 
			      << ", " << "Compute Time (s)"
			      << ", " << "Convergence"
			      << ", " << "Mean"
			      << ", " << "Maximum"
			      << ", " << "Minimum"
			      << ", " << "Standard Deviation"
			      << ", " << "Diversity"
			      << ", " << "ProbabilityOfSwitchingToSearching"
			      << ", " << "ProbabilityOfReturningToNest"
			      << ", " << "UninformedSearchVariation"
			      << ", " << "RateOfInformedSearchDecay"
			      << ", " << "RateOfSiteFidelity"
			      << ", " << "RateOfLayingPheromone"
			      << ", " << "RateOfPheromoneDecay";

	results_output_stream << endl;
	results_output_stream.close();
      }

	while(!ga.done())
	  {

	    std::chrono::time_point<std::chrono::system_clock>generation_start, generation_end;
	    if (mpi_rank == 0)
	      {
		generation_start = std::chrono::system_clock::now();
	      }
	    
      // Calculate the generation
      ga.step();

    if(mpi_rank == 0)
      {
	generation_end = std::chrono::system_clock::now();
	std::chrono::duration<double> generation_elapsed_seconds = generation_end-generation_start;
	ofstream results_output_stream;
	results_output_stream.open(results_file_name, ios::app);
       results_output_stream << ga.statistics().generation() 
			     << ", " << generation_elapsed_seconds.count()
			     << ", " << ga.statistics().convergence()
			     << ", " << ga.statistics().current(GAStatistics::Mean)
			     << ", " << ga.statistics().current(GAStatistics::Maximum)
			     << ", " << ga.statistics().current(GAStatistics::Minimum)
			     << ", " << ga.statistics().current(GAStatistics::Deviation)
			     << ", " << ga.statistics().current(GAStatistics::Diversity);
       
	  for (int i = 0; i < GENOME_SIZE; i++)
	    results_output_stream << ", " << dynamic_cast<const GARealGenome&>(ga.population().best()).gene(i);

	  
	  const GARealGenome& best_genome = dynamic_cast<const GARealGenome&>(ga.statistics().bestIndividual());
	  results_output_stream << endl;
	  
	  results_output_stream << "The GA found an optimum at: ";
	  results_output_stream << best_genome.gene(0);
	  for (int i = 1; i < GENOME_SIZE; i++)
	    results_output_stream << ", " << best_genome.gene(i);
	  results_output_stream << " with score: " << best_genome.score();
	  results_output_stream << endl;
	  results_output_stream.close();
      }
	  }
	// Display the GA's progress
	if(mpi_rank == 0)
	  {
	    cout << ga.statistics() << " " << ga.parameters() << endl;
	  }
	
  MPI_Finalize();

  program_end = std::chrono::system_clock::now();
 
  std::chrono::duration<double> program_elapsed_seconds = program_end-program_start;

  if(mpi_rank == 0)
    printf("Run time was %f seconds\n", program_elapsed_seconds.count());

  return 0;
  }
Esempio n. 19
0
int
main(int argc, char** argv) {
  cout << "This program tries to fill a 1DBinaryStringGenome with\n";
  cout << "alternating 1s and 0s using a simple genetic algorithm.  It runs\n";
  cout << "in parallel using PVM.\n\n";
  cout.flush();

  GAParameterList params;
  GASimpleGA::registerDefaultParameters(params);
  params.set(gaNpopulationSize, 150);
  params.set(gaNnGenerations, 100);
  params.set(gaNscoreFilename, "bog.dat");
  params.set(gaNflushFrequency, 10);
  params.set(gaNscoreFrequency, 1);
  params.parse(argc, argv);

  int usepvm = 1;
  int length = 32;
  PVMData data;			// our own PVM data structure used by pops
  data.nreq = 5;		// by default we want this many slaves to run

  for(int i=1; i<argc; i++){
    if(strcmp("nopvm", argv[i]) == 0){
      usepvm = 0;
      continue;
    }
    else if(strcmp("len", argv[i]) == 0 || strcmp("l", argv[i]) == 0){
      if(++i >= argc){
        cerr << argv[0] << ": genome length needs a value.\n";
        exit(1);
      }
      else{
        length = atoi(argv[i]);
        continue;
      }
    }
    else if(strcmp("nslaves", argv[i]) == 0 || strcmp("ns", argv[i]) == 0){
      if(++i >= argc){
        cerr << argv[0] << ": number of slaves needs a value.\n";
        exit(1);
      }
      else{
        data.nreq = atoi(argv[i]);
        continue;
      }
    }
    else {
      cerr << argv[0] << ":  unrecognized arguement: " << argv[i] << "\n\n";
      cerr << "valid arguements include standard GAlib arguments plus:\n";
      cerr << "  nopvm\t\tdo not use pvm\n";
      cerr << "  nslaves n\tnumber of slave processes (" << data.nreq << ")\n";
      cerr << "  len l\t\tlength of bit string (" << length << ")\n";
      cerr << "\n";
      exit(1);
    }
  }

  if(usepvm && StartupPVM(argv[0], data)) exit(1);

  GA1DBinaryStringGenome genome(length, GenomeEvaluator);
  GAPopulation pop(genome,1);
  if(usepvm){
    pop.initializer(PopulationInitializer);
    pop.evaluator(PopulationEvaluator);
    pop.userData((void*)&data);
  }
  GASimpleGA ga(pop);
  ga.parameters(params);

  time_t tmStart = time(NULL);

  cout << "initializing the GA...\n"; cout.flush();
  ga.initialize();
  cout << "evolving the solution "; cout.flush();
  while(!ga.done()){
    ga.step();
    if(ga.generation() % 10 == 0){
      cout << ga.generation() << " ";
      cout.flush();
    }
  }
  ga.flushScores();

  time_t tmFinish = time(NULL);

  genome = ga.statistics().bestIndividual();
  cout << "\nThe evolution took " << tmFinish-tmStart << " seconds.\n";
  cout << "The GA found an individual with a score of "<<genome.score()<<"\n";
  if(length < 80) cout << genome << "\n";

  if(usepvm) ShutdownPVM(data);

  return 0;
}
Esempio n. 20
0
const Genotype* DeterministicRank::select() {
	return genome()->at( idNext++ % nTruncation );
}
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;
}
Esempio n. 22
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;
}
Esempio n. 23
0
int
main(int argc, char *argv[])
{

  // 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.

  unsigned int seed = 0;

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

  // our genome is 32 bits long

  GA1DBinaryStringGenome genome(32, MinEntropy);

  GASimpleGA ga(genome);

  ga.selectScores(GAStatistics::AllScores);
  ga.recordDiversity(gaTrue);
  ga.scoreFilename("bog.dat");
  ga.flushFrequency(1);
  ga.scoreFrequency(1);
  ga.parameters(argc, argv);
  ga.evolve(seed);


  // These parameters are unusual for genetic algorithms.
  // The mutation is way too high.
  // But only with this mutation good rules were found.
  // Aren't we too close to a random search?

  ga.populationSize(100);
  ga.pCrossover(1);
  ga.pMutation(0.5);
  ga.nGenerations(200);

  while(!ga.done()) {
    ga.step();
  }

  // Let's do a fine tunning second pass

  ga.pCrossover(0);
  ga.pMutation(0.001);
  ga.nGenerations(600);

  while(!ga.done()) {
    ga.step();
  }

//  cout << "\nthe statistics for the run are:\n" << ga.statistics();
//  cout << "\nthe parameters for the run are:\n" << ga.parameters();
//  cout << "\nthe ga generated:\n";

  cout << ga.statistics().bestIndividual() << "\n";
  cout.flush();

  return EXIT_SUCCESS;
}
Esempio n. 24
0
CRAlgorithmStatistics CRGenetics::execute()
{
  CRAlgorithmStatistics ret;
  solved = false;
  
  // Load some needed stuff
  if (config->debug) {
    cout << "CRGenetics::run --> Loading system data.\n";
  }
  
  GeneticConfig &config = dynamic_cast<GeneticConfig&>(* (this->config));
  
  iterations = 0;
  struct timeval t1, t2;
  gettimeofday(&t1, NULL);

  if (!ret.getError()) {
    // Make a first simulation to check if there exist some collisions in the system
    if (config.debug) {
      cout << "CRGenetics::run --> Simulating system in order to check for collisions...\n";
    }
    
    bool collision;
    float min_distance;
    if ( sim->run(collision) ) { // Simulating the whole system saving trajectory.
      if (!collision) {
	      cout << "CRGenetics::run --> No collisions found. It is not necessary to run GA algorithm.\n";
// 				cout << "CRGenetics::run --> Min distance = " << min_distance << endl;
	      
	      ret.setSolved(false);
	      ret.setCollisionDetected(false);
      } else {
	      ret.setCollisionDetected(true);
	      cout << "CRGenetics::run --> Collisions found, initiating the CR Algorithm\n";
// 				cout << "CRGenetics::run --> Min distance = " << min_distance << endl;
      }
    } else {
      cerr << "CRGenetics::run --> An error was found while simulating the system. Aborting.\n";
      ret.setError(true);
    }
	
  }
  
  if ( !ret.getError() && ret.getCollisionDetected() ) {
    // Beggining of the algorithm.
    
    // Associate the objetive and population initializer functions to genome and population
    if (config.debug) {
      cout << "CRGenetics::run --> Associating the proper functions to genome algorithm\n";
    }
    
    if (bounds == NULL) {
      cerr << "CRGenetics::execute() --> This should not happen: bounds = NULL\n";
      return ret;
    }
    
    GARealGenome genome(*bounds, CRALgorithmObjective, (void *)this);
    setGeneticOperators(genome);
    
    // The same process has to be applied to the population
    GAPopulation population(genome, config.population);
    if (config.initializer_type == "Deterministic") {
      population.initializer(GAPopulationInitializer);
    }

    // Define parameters. There is an option to do this from file.
    population.userData((void *) this);

    if (config.debug) {
      cout << "CRGenetics::run --> Creating the algorithm.\n";
    }
    
    delete algorithm;
    algorithm = new GASimpleGA(population);
    cout << "CRGenetics::run --> Setting the GAAlgorithm parameters.\n";
    setGeneticParameters();
    
    if (!config.custom_evolution) {
      if (config.debug) {
	cout << "CRGenetics::run --> Letting the algorithm evolve.\n";
      }
      algorithm->evolve();
    } else {
      customEvolution(ret, t1, true);
    }
    
    // Calculate spended time and show it
    gettimeofday(&t2,NULL);
    cout << "\n\n CRGenetics::run --> Spended time = " << functions::showTime(t1,t2) << endl;
    ret.setExecutionTime(functions::calculateLapseTime(t1, t2));

    // Get best flight plan
    GARealGenome &best = (GARealGenome &) algorithm->statistics().bestIndividual();
    vector<FlightPlan> best_wp(getGeneticFlightPlan(best));
    
    // Get the minimum objetive value and store it for statistics purposes...
    ret.setMinObjetive( best.score() );
    
    // Show the best flight plan
    cout << "CRGenetics::run --> Evolution finished. Best flight plan:\n";
    cout << functions::printToStringVector(best_wp) << endl;
    
    // Show genetic statistics
    cout << algorithm->statistics() << endl;
    
    // Check for collisions in the solution
    bool collision;
// 		float min_d;
    
    
    bool ok;
    try {
      ok = simulateSystem(best_wp, collision);
    } catch(...) {
      ok = false;
    }

    
    
    if (collision || !ok) {
      if (!ok) {
	cerr << "CRGenetics::run --> Error while simulating the best flight plan\n";
      }
      ret.setSolved(false);
      cout  << "CRGenetics::run --> The problem was not solved.\n"; // Min distance = " << min_d << "\n";
    } else {
      cout  << "CRGenetics::run --> The problem was solved successfully.\n";// Min distance = " << min_d << "\n";
    
      if (config.export_trajectories) {
	if (sim->exportTrajectory(config.trajectory_filename)) {
	  cout << "Trajectories exported successfully.\n";
	}
      }
      if (config.export_solution) {
	if (exportSolution(config.solution_filename, best_wp)) {
		cout << "CRGenetics::execute() --> Solution flight plans exported successfully.\n";
	}
      }
      if (config.export_evolution) {
	
      }
		    
      ret.setSolved(true);
    }
	
  }
  
  return ret;
}
Esempio n. 25
0
int
main(int argc, char *argv[]) {
  cout << "Random Seed Test\n\n";
  cout << "This program does three runs of a genetic algorithm, with the \n";
  cout << "random seed resetting between each run.  Each of the three runs \n";
  cout << "should be identical\n\n";
  cout.flush();

  GAParameterList params;
  GASteadyStateGA::registerDefaultParameters(params);
  params.set(gaNnGenerations, 100);
  params.set(gaNflushFrequency, 5);
  params.set(gaNpMutation, 0.001);
  params.set(gaNpCrossover, 0.8);
  params.parse(argc, argv, gaFalse);

  int i,j;
  char filename[128] = "smiley.txt";
  unsigned int seed=0;

  for(i=1; i<argc; i++){
    if(strcmp("file", argv[i]) == 0 || strcmp("f", argv[i]) == 0){
      if(++i >= argc){
        cerr << argv[0] << ": the file option needs a filename.\n";
        exit(1);
      }
      else{
        sprintf(filename, argv[i]);
        continue;
      }
    }
    else if(strcmp("seed", argv[i]) == 0){
      if(++i >= argc){
        cerr << argv[0] << ": the seed option needs a filename.\n";
        exit(1);
      }
      else {
	seed = atoi(argv[i]);
	continue;
      }
    }
    else {
      cerr << argv[0] << ":  unrecognized arguement: " << argv[i] << "\n\n";
      cerr << "valid arguments include standard GAlib arguments plus:\n";
      cerr << "  f\tfilename from which to read (" << filename << ")\n";
      cerr << "\n";
      exit(1);
    }
  }

  const int n=5;

  cout << n << " random numbers\n";
  GAResetRNG(seed);
  for(i=0; i<n; i++)
    cout << " " << GARandomFloat();
  cout << "\n";

  cout << n << " random numbers\n";
  GAResetRNG(seed);
  for(i=0; i<n; i++)
    cout << " " << GARandomFloat();
  cout << "\n";

  cout << n << " random numbers\n";
  GAResetRNG(seed);
  for(i=0; i<n; i++)
    cout << " " << GARandomFloat();
  cout << "\n";
  cout.flush();

  ifstream inStream(filename);
  if(!inStream){
    cerr << "Cannot open " << filename << " for input.\n";
    exit(1);
  }

  int height, width;
  inStream >> height >> width;

  short **target = new short*[width];
  for(i=0; i<width; i++)
    target[i] = new short[height];

  for(j=0; j<height; j++)
    for(i=0; i<width; i++)
      inStream >> target[i][j];

  inStream.close();

  GA2DBinaryStringGenome genome(width, height, objective, (void *)target);
  GASimpleGA ga(genome);
  ga.parameters(params);

  // first run

  GAResetRNG(seed);
  genome.initialize();
  cout << genome << "\n";
  ga.set(gaNscoreFilename, "bog1.dat");
  ga.evolve();

  genome = ga.statistics().bestIndividual();
  cout << "run 1:  the random seed is: " << GAGetRandomSeed() << "\n";
  for(j=0; j<height; j++){
    for(i=0; i<width; i++)
      cout << (genome.gene(i,j) == 1 ? '*' : ' ') << " ";
    cout << "\n";
  }
  cout << "\n"; cout.flush();

  // second run

  GAResetRNG(seed);
  genome.initialize();
  cout << genome << "\n";
  ga.set(gaNscoreFilename, "bog2.dat");
  ga.evolve();

  genome = ga.statistics().bestIndividual();
  cout << "run 2:  the random seed is: " << GAGetRandomSeed() << "\n";
  for(j=0; j<height; j++){
    for(i=0; i<width; i++)
      cout << (genome.gene(i,j) == 1 ? '*' : ' ') << " ";
    cout << "\n";
  }
  cout << "\n"; cout.flush();

  // third run

  GAResetRNG(seed);
  genome.initialize();
  cout << genome << "\n";
  ga.set(gaNscoreFilename, "bog3.dat");
  ga.evolve();

  genome = ga.statistics().bestIndividual();
  cout << "run 3:  the random seed is: " << GAGetRandomSeed() << "\n";
  for(j=0; j<height; j++){
    for(i=0; i<width; i++)
      cout << (genome.gene(i,j) == 1 ? '*' : ' ') << " ";
    cout << "\n";
  }
  cout << "\n"; cout.flush();

  for(i=0; i<width; i++)
    delete target[i];
  delete [] target;

  return 0;
}
Esempio n. 26
0
int
main(int argc, char **argv)
{
  cout << "Example 16\n\n";
  cout << "This example uses a SteadyState GA and Tree<int> genome.  It\n";
  cout << "tries to maximize the size of the tree genomes that it\n";
  cout << "contains.  The genomes contain points in its nodes.  Two\n";
  cout << "different runs are made:  first with the swap subtree mutator,\n";
  cout << "second with the destructive mutator.\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.

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

  GATreeGenome<Point> genome(objective);
  genome.initializer(TreeInitializer);
  genome.crossover(GATreeGenome<Point>::OnePointCrossover);

  genome.mutator(GATreeGenome<Point>::SwapSubtreeMutator);
  GAPopulation swappop(genome, 50);

  genome.mutator(GATreeGenome<Point>::DestructiveMutator);
  GAPopulation destpop(genome, 50);

  GASteadyStateGA ga(genome);
  ga.nGenerations(10);

// first do evolution with subtree swap mutator.

  ga.population(swappop);

  cout << "initializing...";
  ga.initialize(seed);
  cout << "evolving for " << ga.nGenerations() << " generations...";
  while(!ga.done()){
    ga.step();
    cout << ".";
    cout.flush();
  }
  cout << "\n";

  genome = ga.statistics().bestIndividual();
  cout << "the ga generated a tree with " << genome.size();
  cout << " nodes, " << genome.depth() << " levels deep.\n";

// now do evolution with destructive swap mutator

  ga.population(destpop);

  cout << "\ninitializing...";
  ga.initialize();
  cout << "evolving for " << ga.nGenerations() << " generations...";
  while(!ga.done()){
    ga.step();
    cout << ".";
    cout.flush();
  }
  cout << "\n";

  genome = ga.statistics().bestIndividual();
  cout << "the ga generated a tree with " << genome.size();
  cout << " nodes, " << genome.depth() << " levels deep.\n";

  return 0;
}