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; }
GAParameterList CRGenetics::getGeneticParams() { GAParameterList params; GeneticConfig &config = dynamic_cast<GeneticConfig&>(* (this->config)); GASimpleGA::registerDefaultParameters(params); params.set(gaNpCrossover, config.pCrossover); // likelihood of doing crossover params.set(gaNpMutation, config.pMutation); // probability of mutation params.set(gaNnGenerations, config.generations); // number of generations params.set(gaNscoreFrequency, 1); // how often to record scores params.set(gaNflushFrequency, 10); // how often to flush scores to file params.set(gaNscoreFilename, "bog.dat"); return params; }
int main(int argc, char** argv) { cout << "Example 21\n\n"; cout << "This example shows various uses of the allele set object\n"; cout << "in combination with the real number genome.\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]); } } // First make a bunch of genomes. We'll use each one in turn for a genetic // algorithm later on. Each one illustrates a different method of using the // allele set object. Each has its own objective function. // This genome is created using an array of allele sets. This means that each // element of the genome will assume a value in its corresponding allele set. // For example, since the first allele set is [0,10], the first element of the // genome will be in [0,10]. Notice that you can add allele sets in many other // ways than those shown. GARealAlleleSetArray alleles4; for(int j=1;j<34;j++) { alleles4.add(0,10); } GARealGenome genome4(alleles4, Objective4); // Now that we have the genomes, create a parameter list that will be used for // all of the genetic algorithms and all of the genomes. GAParameterList params; GASteadyStateGA::registerDefaultParameters(params); params.set(gaNnGenerations, 500); params.set(gaNpopulationSize, 110); params.set(gaNscoreFrequency, 10); params.set(gaNflushFrequency, 50); params.set(gaNselectScores, (int)GAStatistics::AllScores); params.parse(argc, argv, gaFalse); // Now do a genetic algorithm for each one of the genomes that we created. GASteadyStateGA ga4(genome4); ga4.parameters(params); ga4.set(gaNscoreFilename, "bog4.dat"); cout << "\nrunning ga number 4 (maximize each gene)..." << endl; ga4.evolve(); cout << "the ga generated:\n" << ga4.statistics().bestIndividual() << endl; return 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; }
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; }
int main(int argc, char** argv) { cout << "Example 21\n\n"; cout << "This example shows various uses of the allele set object\n"; cout << "in combination with the real number genome.\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]); } } // First make a bunch of genomes. We'll use each one in turn for a genetic // algorithm later on. Each one illustrates a different method of using the // allele set object. Each has its own objective function. int length = 8; // This genome uses an enumerated list of alleles. We explictly add each // allele to the allele set. Any element of the genome may assume the value // of any member of the allele set. GARealAlleleSet alleles1; alleles1.add(-10); alleles1.add(0.1); alleles1.add(1.0); alleles1.add(10); alleles1.add(100); GARealGenome genome1(length, alleles1, Objective1); // This genome uses a bounded set of continous numbers. The default arguments // are INCLUSIVE for both the lower and upper bounds, so in this case the // allele set is [0,1] and any element of the genome may assume a value [0,1]. GARealAlleleSet alleles2(0, 1); GARealGenome genome2(length, alleles2, Objective2); // Similar to the previous set, but this one has EXCLUSIVE bounds and we create // the allele set explicitly (even though in this case GARealAlleleSetArray alleles2a; for(int i=0; i<length; i++) alleles2a.add(0, 1, GAAllele::EXCLUSIVE, GAAllele::EXCLUSIVE); GARealGenome genome2a(alleles2a, Objective2); // Here we create a genome whose elements may assume any value in the interval // [0.0, 10.0) discretized on the interval 0.5, i.e. the values 0.0, 0.5, 1.0, // and so on up to but not including 10.0. // Note that the default operators for the real genome are uniform initializer, // gaussian mutator, and uniform crossover. Since gaussian is not the behavior // we want for mutation, we assign the flip mutator instead. GARealAlleleSet alleles3(0,10,0.5,GAAllele::INCLUSIVE,GAAllele::EXCLUSIVE); GARealGenome genome3(length, alleles3, Objective3); genome3.crossover(GARealUniformCrossover); genome3.mutator(GARealSwapMutator); // This genome is created using an array of allele sets. This means that each // element of the genome will assume a value in its corresponding allele set. // For example, since the first allele set is [0,10], the first element of the // genome will be in [0,10]. Notice that you can add allele sets in many other // ways than those shown. GARealAlleleSetArray alleles4; alleles4.add(0,10); alleles4.add(50,100); alleles4.add(-10,-5); alleles4.add(-0.01,-0.0001); alleles4.add(10000,11000); GARealGenome genome4(alleles4, Objective4); // Now that we have the genomes, create a parameter list that will be used for // all of the genetic algorithms and all of the genomes. GAParameterList params; GASteadyStateGA::registerDefaultParameters(params); params.set(gaNnGenerations, 500); params.set(gaNpopulationSize, 110); params.set(gaNscoreFrequency, 10); params.set(gaNflushFrequency, 50); params.set(gaNselectScores, (int)GAStatistics::AllScores); params.parse(argc, argv, gaFalse); // Now do a genetic algorithm for each one of the genomes that we created. GASteadyStateGA ga1(genome1); ga1.parameters(params); ga1.set(gaNscoreFilename, "bog1.dat"); cout << "\nrunning ga number 1 (alternate allele(0) and allele(3))..."<<endl; ga1.evolve(seed); cout << "the ga generated:\n" << ga1.statistics().bestIndividual() << endl; GASteadyStateGA ga2(genome2); ga2.parameters(params); ga2.set(gaNscoreFilename, "bog2.dat"); cout << "\nrunning ga number 2 (continuous descending order)..." << endl; ga2.evolve(); cout << "the ga generated:\n" << ga2.statistics().bestIndividual() << endl; GASteadyStateGA ga2a(genome2a); ga2a.parameters(params); ga2a.set(gaNscoreFilename, "bog2a.dat"); cout << "\nrunning ga number 2a (descending order, EXCLUSIVE)..." << endl; ga2a.evolve(); cout << "the ga generated:\n" << ga2a.statistics().bestIndividual() << endl; GASteadyStateGA ga3(genome3); ga3.parameters(params); ga3.set(gaNscoreFilename, "bog3.dat"); cout << "\nrunning ga number 3 (discretized ascending order)..." << endl; ga3.evolve(); cout << "the ga generated:\n" << ga3.statistics().bestIndividual() << endl; GASteadyStateGA ga4(genome4); ga4.parameters(params); ga4.set(gaNscoreFilename, "bog4.dat"); cout << "\nrunning ga number 4 (maximize each gene)..." << endl; ga4.evolve(); cout << "the ga generated:\n" << ga4.statistics().bestIndividual() << endl; return 0; }
int main(int argc, char *argv[]) { cout << "Example 7\n\n"; cout << "This program reads in a data file then runs a steady-state GA \n"; cout << "whose objective function tries to match the pattern of bits that\n"; cout << "are in the data file.\n\n"; // 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. int i, j; GAParameterList params; GASteadyStateGA::registerDefaultParameters(params); params.set(gaNpopulationSize, 50); // number of individuals in population params.set(gaNpCrossover, 0.8); // likelihood of doing crossover params.set(gaNpMutation, 0.001); // probability of mutation params.set(gaNnGenerations, 200); // number of generations params.set(gaNscoreFrequency, 20); // how often to record scores params.set(gaNflushFrequency, 50); // how often to flush scores to file params.set(gaNscoreFilename, "bog.dat"); params.parse(argc, argv, gaFalse); char datafile[128] = "smiley.txt"; char parmfile[128] = ""; // Parse the command line for arguments. We look for two possible arguments // (after the parameter list has grabbed everything it recognizes). One is the // name of a data file from which to read, the other is the name of a // parameters file from which to read. Notice that any parameters in the // parameters file will override the defaults above AND any entered on the // command line. for(i = 1; i < argc; i++) { if(strcmp("dfile", argv[i]) == 0) { if(++i >= argc) { cerr << argv[0] << ": the data file option needs a filename.\n"; exit(1); } else { sprintf(datafile, argv[i]); continue; } } else if(strcmp("pfile", argv[i]) == 0) { if(++i >= argc) { cerr << argv[0] << ": the parameters file option needs a filename.\n"; exit(1); } else { sprintf(parmfile, argv[i]); params.read(parmfile); 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 GAlib arguments plus:\n"; cerr << " dfile\tdata file from which to read (" << datafile << ")\n"; cerr << " pfile\tparameters file (" << parmfile << ")\n\n"; cerr << "default parameters are:\n" << params << "\n\n"; exit(1); } } // Read in the pattern from the specified file. File format is pretty simple: // two integers that give the height then width of the matrix, then the matrix // of 1's and 0's (with whitespace inbetween). // Here we use a binary string genome to store the desired pattern. This // shows how you can read in directly from a stream into a genome. (This can // be useful in a population initializer when you want to bias your population) ifstream inStream(datafile); if(!inStream) { cerr << "Cannot open " << datafile << " for input.\n"; exit(1); } int height, width; inStream >> height >> width; GA2DBinaryStringGenome target(width, height); inStream >> target; inStream.close(); // Print out the pattern to be sure we got the right one. cout << "input pattern:\n"; for(j = 0; j < height; j++) { for(i = 0; i < width; i++) { cout << (target.gene(i, j) == 1 ? '*' : ' ') << " "; } cout << "\n"; } cout << "\n"; cout.flush(); // Now create the first genome and the GA. When we create the genome, we give // it not only the objective function but also 'user data'. In this case, the // user data is a pointer to our target pattern. From a C++ point of view it // would be better to derive a new genome class with its own data, but here we // just want a quick-and-dirty implementation, so we use the user-data. GA2DBinaryStringGenome genome(width, height, objective, (void *)&target); GASteadyStateGA ga(genome); // When you use a GA with overlapping populations, the default score // frequency (how often the best of generation score is recorded) defaults // to 100. We use the parameters member function to change this value (along // with all of the other parameters we set above). You can also change the // score frequency using the scoreFrequency member function of the GA. Each of // the parameters can be set individually if you like. // Here we just use the values that were set in the parameter list. ga.parameters(params); // The default selection method is RouletteWheel. Here we set the selection // method to TournamentSelection. GATournamentSelector selector; ga.selector(selector); // The following member functions override the values that were set using the // parameter list. They are commented out here so that you can see how they // would be used. // We can control the amount of overlap from generation to generation using the // pReplacement member function. If we specify a value of 1 (100%) then the // entire population is replaced each generation. Notice that the percentage // must be high enough to have at least one individual produced in each // generation. If not, the GA will post a warning message. // ga.pReplacement(0.3); // Often we use the number of generations as the criterion for terminating the // GA run. Here we override that and tell the GA to use convergence as a // termination criterion. Note that you can pass ANY function as the stopping // criterion (as long as it has the correct signature). // Notice that the values we set here for p- and n-convergence override those // that we set in the parameters object. ga.terminator(GAGeneticAlgorithm::TerminateUponConvergence); // ga.pConvergence(0.99); // converge to within 1% // ga.nConvergence(100); // within the last 100 generations // Evolve the GA 'by hand'. When you use this method, be sure to initialize // the GA before you start to evolve it. You can print out the status of the // current population by using the ga.population() member function. This is // also how you would print the status of the GA to disk along the way (rather // than waiting to the end then printing the scores, for example). ga.initialize(); while(!ga.done()) { ++ga; } ga.flushScores(); // Now that the GA is finished, we set our default genome to equal the contents // of the best genome that the GA found. Then we print it out. genome = ga.statistics().bestIndividual(); cout << "the ga generated:\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(); cout << "best of generation data are in '" << ga.scoreFilename() << "'\n"; return 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; }
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; }
int main(int argc, char *argv[]) { cout << "Example 3\n\n"; cout << "This program reads in a data file then runs a simple GA whose\n"; cout << "objective function tries to match the pattern of bits that are\n"; cout << "in the data file.\n\n"; // 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 and declare the params variable. // We use the genetic algorithm's configure member to set up the parameter list // so that it will parse for the appropriate arguments. Notice that the // params argument 'removes' from the argv list any arguments that it // recognized (actually it just re-orders them and changes the value of argc). // Once the GA's parameters are registered, we set some values that we want // that are different than the GAlib defaults. Then we parse the command line. GAParameterList params; GASimpleGA::registerDefaultParameters(params); params.set(gaNscoreFilename, "bog.dat"); params.set(gaNflushFrequency, 50); params.set(gaNpMutation, 0.001); params.set(gaNpCrossover, 0.8); params.parse(argc, argv, gaFalse); int i, j; char filename[128] = "smiley.txt"; // Parse the command line for arguments. 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) { continue; } 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); } } // Read in the pattern from the specified file. File format is pretty simple: // two integers that give the height then width of the matrix, then the matrix // of 1's and 0's (with whitespace inbetween). 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(); // Print out the pattern to be sure we got the right one. cout << "input pattern:\n"; for(j = 0; j < height; j++) { for(i = 0; i < width; i++) { cout << (target[i][j] == 1 ? '*' : ' ') << " "; } cout << "\n"; } cout << "\n"; cout.flush(); // Now create the GA and run it. GA2DBinaryStringGenome genome(width, height, objective, (void *)target); GASimpleGA ga(genome); ga.parameters(params); ga.evolve(); cout << "best of generation data are in '" << ga.scoreFilename() << "'\n"; genome = ga.statistics().bestIndividual(); cout << "the ga generated:\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; }
class AlgoGen{ float Objective(GAGenome &); public: //constructeur AlgoGen(){ } //destructeur ~AlgoGen(){ } } int main(int argc, char** argv) { //Parametrage pour obtenir un résultats identiques sur plusieurs execution unsigned int seed = 0; for(int ii=1; ii<argc; ii++) { if(strcmp(argv[ii++],"seed") == 0) { seed = atoi(argv[ii]); } } /////////////////////// // création des génomes /////////////////////// // crée un génome à 33 alleles, comprise aléatoirement entre 0 et 10 GARealAlleleSetArray alleles; for(int k=1;k<=33;k++) alleles.add(0,10); GARealGenome genome(alleles, Objective); // paramétres de l'algorithme génétique GAParameterList params; GASteadyStateGA::registerDefaultParameters(params); params.set(gaNnGenerations, 500); params.set(gaNpopulationSize, 110); params.set(gaNscoreFrequency, 10); params.set(gaNflushFrequency, 50); params.set(gaNselectScores, (int)GAStatistics::AllScores); params.parse(argc, argv, gaFalse); // execution de l'algorithme GASteadyStateGA ga(genome); ga.parameters(params); ga.set(gaNscoreFilename, "bog.dat"); cout << "\n execution de ga (maximise le poid de l'epi)..." << endl; ga.evolve(); cout << "l'algorithme a généré :\n" << ga.statistics().bestIndividual() << endl; return 0; }