int main() { std::cout << "[t-eoPartiallyMappedXover] => START" << std::endl; Solution sol1, sol2; sol1.resize(9); sol2.resize(9); for(int i = 0; i < sol1.size(); i++) sol1[i] = i; sol2[0] = 3; sol2[1] = 4; sol2[2] = 1; sol2[3] = 0; sol2[4] = 7; sol2[5] = 6; sol2[6] = 5; sol2[7] = 8; sol2[8] = 2; std::cout << sol1 << std::endl; std::cout << sol2 << std::endl; eoPartiallyMappedXover<Solution> xover; xover(sol1, sol2); std::cout << "apres" << std::endl; std::cout << sol1 << std::endl; std::cout << sol2 << std::endl; int verif[9]; for(int i = 0; i < sol1.size(); i++) verif[i] = -1; for(int i = 0; i < sol1.size(); i++) verif[ sol1[i] ] = 1; for(int i = 0; i < sol1.size(); i++) assert(verif[i] != -1); for(int i = 0; i < sol2.size(); i++) verif[i] = -1; for(int i = 0; i < sol2.size(); i++) verif[ sol2[i] ] = 1; for(int i = 0; i < sol2.size(); i++) assert(verif[i] != -1); std::cout << "[t-eoPartiallyMappedXover] => OK" << std::endl; return EXIT_SUCCESS; }
void main_function() { const unsigned SIZE = 8; unsigned i, j; eoBooleanGenerator gen; Chrom chrom(SIZE), chrom2; chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); std::cout << "chrom: " << chrom << std::endl; chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom)); std::cout << "chrom: " << chrom << std::endl; chrom[0] = chrom[SIZE - 1] = false; chrom.fitness(binary_value(chrom)); std::cout << "chrom: " << chrom << std::endl; chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom)); std::cout << "chrom.className() = " << chrom.className() << std::endl; std::cout << "chrom: " << chrom << std::endl << "chrom2: " << chrom2 << std::endl; std::ostringstream os; os << chrom; std::istringstream is(os.str()); is >> chrom2; chrom.fitness(binary_value(chrom2)); std::cout << "\nTesting reading, writing\n"; std::cout << "chrom: " << chrom << "\nchrom2: " << chrom2 << '\n'; std::fill(chrom.begin(), chrom.end(), false); std::cout << "--------------------------------------------------" << std::endl << "eoMonOp's aplied to .......... " << chrom << std::endl; eoInitFixedLength<Chrom> random(chrom.size(), gen); random(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBinRandom ............ " << chrom << std::endl; eoOneBitFlip<Chrom> bitflip; bitflip(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBitFlip .............. " << chrom << std::endl; eoBitMutation<Chrom> mutation(0.5); mutation(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBinMutation(0.5) ..... " << chrom << std::endl; eoBitInversion<Chrom> inversion; inversion(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBinInversion ......... " << chrom << std::endl; eoBitNext<Chrom> next; next(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBinNext .............. " << chrom << std::endl; eoBitPrev<Chrom> prev; prev(chrom); chrom.fitness(binary_value(chrom)); std::cout << "after eoBinPrev .............. " << chrom << std::endl; std::fill(chrom.begin(), chrom.end(), false); chrom.fitness(binary_value(chrom)); std::fill(chrom2.begin(), chrom2.end(), true); chrom2.fitness(binary_value(chrom2)); std::cout << "--------------------------------------------------" << std::endl << "eoBinOp's aplied to ... " << chrom << " " << chrom2 << std::endl; eo1PtBitXover<Chrom> xover; std::fill(chrom.begin(), chrom.end(), false); std::fill(chrom2.begin(), chrom2.end(), true); xover(chrom, chrom2); chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); std::cout << "eoBinCrossover ........ " << chrom << " " << chrom2 << std::endl; for (i = 1; i < SIZE; i++) { eoNPtsBitXover<Chrom> nxover(i); std::fill(chrom.begin(), chrom.end(), false); std::fill(chrom2.begin(), chrom2.end(), true); nxover(chrom, chrom2); chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); std::cout << "eoBinNxOver(" << i << ") ........ " << chrom << " " << chrom2 << std::endl; } for (i = 1; i < SIZE / 2; i++) for (j = 1; j < SIZE / 2; j++) { eoBitGxOver<Chrom> gxover(i, j); std::fill(chrom.begin(), chrom.end(), false); std::fill(chrom2.begin(), chrom2.end(), true); gxover(chrom, chrom2); chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); std::cout << "eoBinGxOver(" << i << ", " << j << ") ..... " << chrom << " " << chrom2 << std::endl; } // test SGA algorithm eoGenContinue<Chrom> continuator1(50); eoFitContinue<Chrom> continuator2(65535.f); eoCombinedContinue<Chrom> continuator(continuator1, continuator2); eoCheckPoint<Chrom> checkpoint(continuator); eoStdoutMonitor monitor; checkpoint.add(monitor); eoSecondMomentStats<Chrom> stats; monitor.add(stats); checkpoint.add(stats); eoProportionalSelect<Chrom> select; eoEvalFuncPtr<Chrom> eval(binary_value); eoSGA<Chrom> sga(select, xover, 0.8f, bitflip, 0.1f, eval, checkpoint); eoInitFixedLength<Chrom> init(16, gen); eoPop<Chrom> pop(100, init); apply<Chrom>(eval, pop); sga(pop); pop.sort(); std::cout << "Population " << pop << std::endl; std::cout << "\nBest: " << pop[0].fitness() << '\n'; /* Commented this out, waiting for a definite decision what to do with the mOp's // Check multiOps eoMultiMonOp<Chrom> mOp( &next ); mOp.adOp( &bitflip ); std::cout << "before multiMonOp............ " << chrom << std::endl; mOp( chrom ); std::cout << "after multiMonOp .............. " << chrom << std::endl; eoBinGxOver<Chrom> gxover(2, 4); eoMultiBinOp<Chrom> mbOp( &gxover ); mOp.adOp( &bitflip ); std::cout << "before multiBinOp............ " << chrom << " " << chrom2 << std::endl; mbOp( chrom, chrom2 ); std::cout << "after multiBinOp .............. " << chrom << " " << chrom2 <<std::endl; */ }
int main(int argc, char** argv) { const unsigned int T_SIZE = 3; // size for tournament selection const unsigned int VEC_SIZE = 3; // Number of object variables in genotypes const unsigned int POP_SIZE = 10; // Size of population const unsigned int MAX_GEN = 1000; // Maximum number of generation before STOP const unsigned int MIN_GEN = 10; // Minimum number of generation before ... const unsigned int STEADY_GEN = 10; // stop after STEADY_GEN gen. without improvement const float P_CROSS = 0.8; // Crossover probability const float P_MUT = 0.5; // mutation probability const double EPSILON = 0.01; // range for real uniform mutation double SIGMA = 0.3; // std dev. for normal mutation // some parameters for chosing among different operators const double hypercubeRate = 0.5; // relative weight for hypercube Xover const double segmentRate = 0.5; // relative weight for segment Xover const double uniformMutRate = 0.5; // relative weight for uniform mutation const double detMutRate = 0.5; // relative weight for det-uniform mutation const double normalMutRate = 0.5; // relative weight for normal mutation const unsigned int SEED = 42; // seed for random number generator po::options_description desc; std::string matrixdir, model, nullmodel, trainingset, testingset, lastrun; desc.add_options() ("matrixdir", po::value<std::string>(&matrixdir), "The directory set up by SOFT2Matrix") ("model", po::value<std::string>(&model), "The gene regulatory network model") ("nullmodel", po::value<std::string>(&nullmodel), "The gene regulatory network null (scrambled) model") ("trainingset", po::value<std::string>(&trainingset), "The list of arrays which have been selected for inclusion in the training set") ("testingset", po::value<std::string>(&testingset), "The list of arrays which have been selected for inclusion in the testing set") ("lastrun", po::value<std::string>(&lastrun), "The output file from the last run, to re-use scores from (optional)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); std::string wrong; if (!vm.count("help")) { if (!vm.count("matrixdir")) wrong = "matrixdir"; else if (!vm.count("model")) wrong = "model"; else if (!vm.count("trainingset")) wrong = "trainingset"; else if (!vm.count("testingset")) wrong = "testingset"; else if (!vm.count("nullmodel")) wrong = "nullmodel"; } if (wrong != "") std::cerr << "Missing option: " << wrong << std::endl; if (vm.count("help") || wrong != "") { std::cout << desc << std::endl; return 1; } if (!fs::is_directory(matrixdir)) { std::cout << "Matrix directory doesn't exist." << std::endl; return 1; } if (!fs::is_regular(model)) { std::cout << "Model file doesn't exist or not regular file." << std::endl; return 1; } if (!fs::is_regular(nullmodel)) { std::cout << "Null model file doesn't exist or not regular file." << std::endl; return 1; } if (!fs::is_regular(trainingset)) { std::cout << "Training set file doesn't exist or not regular file." << std::endl; return 1; } if (!fs::is_regular(testingset)) { std::cout << "Testing set file doesn't exist or not regular file." << std::endl; return 1; } std::list<double> lastRun; if (fs::is_regular(lastrun)) { std::ifstream flastrun(lastrun.c_str()); static const boost::regex prev(".*SVM Result: .* Result \\(([^\\)]+)\\).*"); while (flastrun.good()) { std::string l; std::getline(flastrun, l); boost::smatch m; if (!boost::regex_match(l, m, prev)) { continue; } lastRun.push_back(strtod(m[1].str().c_str(), NULL)); } } ExpressionMatrixProcessor emp(matrixdir); GRNModel m(model, emp, 30); GRNModel m2(nullmodel, emp, 30); std::list<std::string> trainingArrays, testingArrays; m.loadArraySet(trainingset, trainingArrays); m.loadArraySet(testingset, testingArrays); m.loadSVMTrainingData(trainingArrays); m2.loadArraySet(trainingset, trainingArrays); m2.loadArraySet(testingset, testingArrays); m2.loadSVMTrainingData(trainingArrays); // We seed it just so we can restart if need be. rng.reseed(SEED); EvaluateSVMFit eval(m, m2, trainingArrays, lastRun, 30, testingArrays.size()); std::vector<double> minVals, maxVals; // log(gamma) minVals.push_back(-15); maxVals.push_back(15); // log(C) minVals.push_back(-15); maxVals.push_back(2); // nu minVals.push_back(0); maxVals.push_back(1); eoRealVectorBounds rvb(minVals, maxVals); eoRealInitBounded<Indi> random(rvb); eoPop<Indi> pop(POP_SIZE, random); apply<Indi>(eval, pop); pop.sort(); std::cout << "Initial Population" << std::endl; std::cout << pop; eoDetTournamentSelect<Indi> selectOne(T_SIZE); eoSelectPerc<Indi> select(selectOne);// by default rate==1 eoGenerationalReplacement<Indi> replace; eoSegmentCrossover<Indi> xoverS; eoHypercubeCrossover<Indi> xoverA; eoPropCombinedQuadOp<Indi> xover(xoverS, segmentRate); xover.add(xoverA, hypercubeRate, true); eoUniformMutation<Indi> mutationU(EPSILON); eoDetUniformMutation<Indi> mutationD(EPSILON); eoNormalMutation<Indi> mutationN(SIGMA); eoPropCombinedMonOp<Indi> mutation(mutationU, uniformMutRate); mutation.add(mutationD, detMutRate); mutation.add(mutationN, normalMutRate, true); eoGenContinue<Indi> genCont(MAX_GEN); eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN); eoCombinedContinue<Indi> continuator(genCont); continuator.add(steadyCont); eoSGATransform<Indi> transform(xover, P_CROSS, mutation, P_MUT); eoEasyEA<Indi> gga(continuator, eval, select, transform, replace); gga(pop); pop.sort(); std::cout << "Final Population:" << std::endl << pop << std::endl; return 0; }
// GA function accepts data matrix, legal gene matrix, and number of total genes wanted in final matrix // New stopping criterion: when PD does not increase for maxGenStalled generations int optimizeDecisivnessGA (vector < vector <int> > & data, vector < vector <int> > const& legal, int const& numAdd, bool const& referenceTaxonPresent, int const& numProcs) { // initialize random number generator - already done in main // srand((unsigned)time(0)); // Constants. Some should probably be user specified: tournamentSize, populationSize, mutationProbability, maxgen // int numTaxa = data.size(); // not used // int numLoci = data[0].size(); // not used int numInitialLoci = countLociPresent(data); int tournamentSize = 5; // size of tournament group. const int populationSize = 500; double mutationProbability = 0.9; // probability of mutation, otherwise xover //double stepReplaceProbability = 0.01; int maxgen = 100000; // maximum number of generations; ramp up to 100000 or whatever int numTrees = 100; // ramp up to 1000 double bestSolution = 0.0; vector < vector <int> > bestConfiguration; int genStalled = 0; // number of generations without an increase in best fitness. int maxGenStalled = 5000; // Store fitness double fitness[populationSize]; // cout << "initialize " << endl; // Initialize population vector < vector <int> > population[populationSize]; // int numAdd = maxGenes - numInitialLoci; // number of genes to add int maxGenes = numInitialLoci + numAdd; // cout << "Initial count = " << numInitialLoci << "; adding " << numAdd // << " sampled characters for total of " << maxGenes << " occupied cells of a possible " // << data.size() * data[0].size() << "." << endl; // Function currently errors out when too many genes initially present. // This should be changed to allow genes to be removed. cout << endl << "SETTING UP INITIAL POPULATION" << endl << endl; cout << "Population consists of " << populationSize << " individuals." << endl; if (numAdd < 0) { // subtract genes; not sure when this will be used... cout << numAdd << " populated cells will be removed." << endl; for (int i = 0; i < populationSize; i++) { population[i] = data; for (int j = numAdd; j < 0; j++) { mutate(population[i], legal, 0, 1); } } } else { // add genes cout << numAdd << " additional random taxon-character cells will be populated for each individual..." << endl; for (int i = 0; i < populationSize; i++) { population[i] = data; for (int j = 0; j < numAdd; j++) { // Randomly add numAdd genes in legal positions mutate(population[i], legal, 1, 0); // last 2 arguments are add, remove (boolean) } } } cout << "Done." << endl << endl; //cout << "Best solution from initial population = " << bestSolution << "." << endl; // Calculate initial fitness. For each matrix, crunch through 1000 trees cout << "Calculating initial fitnesses for all individuals..." << endl; for (int i = 0; i < populationSize; i++) { fitness[i] = calcFit(referenceTaxonPresent, numTrees, population[i], numProcs); // cout << "Fitness for individual " << i << " is: " << fitness[i] << "." << endl; if (fitness[i] > bestSolution) { bestSolution = fitness[i]; bestConfiguration = population[i]; // cout << "Best solution from initial population = " << bestSolution << "." << endl; } } cout << "Done." << endl; cout << "Best solution from initial population = " << bestSolution << "." << endl; bool done = 0; // flag to end evolution loop int gen = 0; // counter for number of generations // Check for out of bounds parameter values if (populationSize < 3) { cout << "Population size must be greater than 2" << endl; return(1); } if (tournamentSize < 2) { cout << "Tournament group size must be greater than 1" << endl; return(1); } // Evolution loop cout << endl << "STARTING EVOLUTION" << endl << endl; cout << "Running for a total of " << maxgen << " generations." << endl << endl; // cout << "Progress:" << endl; while (!done) { gen = gen + 1; cout << "Generation " << gen; // Choose tournament group // initialize best and worst with random int random = (int)(rand() % (populationSize)); int best = random; // integer to hold position of best member of tournament group int worst = random; // position of worst member of tournament group double bestFit = fitness[random]; // best fitness double worstFit = fitness[random]; // worst fitness // selection step //for (int i = 1; i < tournamentSize; i++) for (int i = 0; i < tournamentSize; i++) { random = (int)(rand() % populationSize); if (fitness[random] > bestFit) { bestFit = fitness[random]; best = random; } if (fitness[random] < worstFit) { worstFit = fitness[random]; worst = random; } } // make sure best and worst are not the same // if they are the same, choose new best randomly from population while (best == worst) { best = (int)(rand() % (populationSize)); } // Copy best individual to worst individual population[worst] = population[best]; // enter stepwise function. too demanding. // if (gen % 1000 == 0) { // cout << ": Entering stepwise phase." << endl; // stepReplace (population[worst], legal, maxGenes, referenceTaxonPresent, numProcs); // } // else { // Mutate with some probability, otherwise xover double randmu = (double) rand() / RAND_MAX; if (randmu < mutationProbability) { // mutate; change one cell. mutate(population[worst], legal, 1, 1); } else { // xover with random individual in population int randx = (int)(rand() % populationSize); while (randx == worst) { randx = (int)(rand() % populationSize); } xover(population[worst], population[randx], legal, maxGenes); } // } // Calculate fitness of new individual fitness[worst] = calcFit(referenceTaxonPresent, numTrees, population[worst], numProcs); if (fitness[worst] > bestSolution) { bestSolution = fitness[worst]; bestConfiguration = population[worst]; genStalled = 0; } else { genStalled += 1; } // Check to see if max number of generations has been reached cout << ": best solution thus far = " << bestSolution << "." << endl; if (gen == maxgen || genStalled == maxGenStalled) { done = 1; } } // End of evolution loop // double bestFit = 0; // int bestInd = 0; // for (int i = 0; i < populationSize; i++) // { // if (fitness[i] > bestFit) { // bestFit = fitness[i]; // bestInd = i; // } // } // cout << endl << "Best result found: " << bestFit << endl; // copy best evolved matrix to original data matrix // data = population[bestInd]; //printData(data); cout << endl << "Best result found: " << bestSolution << endl; data = bestConfiguration; cout << endl; return(0); }