예제 #1
0
파일: ea.cpp 프로젝트: veimox/locokit69
void EA<T>::evolve(unsigned int generations, int solution)
{
    bool solution_found = false;
    for (unsigned int i = 0; i < generations; i++) {
        evaluate();
        for (unsigned int i = 0; i < population.size(); i++) {
            if (population[i]->getFitness() == solution) {
                solution_found = true;
                std::cout << generation << " generations. Found solution: ";
                population[i]->printChromosome();
            }
        }
        if (solution_found) {
            break;
        }

        generation++;

        evaluate();
        select();
        reproduce();
        replace();
    }
    std::cout << "Solution not found..." << std::endl;
}
예제 #2
0
파일: main.c 프로젝트: davsebamse/ze_codes
int main()
{
	int gen = 0;
	char go = 1;

	srand(time(NULL));

	/* 1. Choose the initial ppopulation */
	initial_population();
	/* 2. Evaluate the fitness of each individual in the population */
	fitness();
	/* 3. Repeat */
	while((gen++ < MAX_GENS)  && go)
	{
/*		printf("Find the best fittest\n");*/
	/* 	1. Select the best-ranking individuals to reproduce */
		find_the_best_individuals();
		/* Select the reproduce no, dynamicly (Ver. 2) */
		reproduce();
	/*		2. Breed new generation through crossover and mutation (genetic operations) and give birth to offspring */
	/*		3. Evaluate the individual fitnesses of the offspring */
	/*		4. Replace worst ranked part of the population with offspring */
		fitness();
		find_the_best_individuals();
		if (population[0].fitness < OK_SNIT)
			go = 0;
	}
	/* 4. Until <terminating condition> */
	print_population();
	printf("No of gen: %d\n",gen);
	return 0;
}
int main(int argn, char *argv[]) {
  int i;
  double v;
  double lambda;
  
  parsecomamndline(argn,argv);
  initialize();
  populationconstraint(0);
  populationconstraint(0);
  if(quiet==0)print_populationdensity(0);
  if(averagepopdens) {
    init_averagepopdens();
  }
  if (quiet<2) fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e %.10e %.10e\n",0,0.,populationvariance,populationsize,1,xg,ucp,dv);
  for(i=1;i<=maxSteps;i++) {
    reproduce(i);
    lambda = populationconstraint(i);
    
    if(i%outputstep == 0) {
      if (quiet<2)fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e %.10e %.10e\n",i*epsilon,allshifts*dx + popdens_1stmom/popdens_0thmom,populationvariance,populationsize,lambda,xg,ucp,dv);
      if (quiet==0) print_populationdensity(i);
      if (averagepopdens_havefile) update_averagepopdens();
      if (averagepopdens_havecovarfile) update_averagecovar();
    }
  }
  
  if(write_to_file)write_popdens();
  if(averagepopdens_havefile)write_averagepopdens();
  if(averagepopdens_havecovarfile)write_averagecovar();
  cleanup();
  return 0;
}
void reproduce(int *b, int *g) {
  if(rand()%2)
    (*b)++;
  else {
    (*g)++;
    reproduce(b, g);
  }
}
예제 #5
0
파일: fitness.c 프로젝트: emkev/genetic
int main(int argc , char **argv)
{
  int i , j , t , targetlen , parent_a , parent_b ;
  int *numcorrect; 
  char **newpop , **oldpop , **swap;
  double *normfit;

  //srandom(seed);
  srand((unsigned)time(NULL));

  // whether to consider forcing the size to be even . 

  targetlen = 10;
  printf("hello! \n");
  newpop = malloc(sizeof(char *) * size);
  oldpop = malloc(sizeof(char *) * size);
  printf("hello 1-1 \n");
  numcorrect = malloc(sizeof(int) * size);
  normfit = malloc(sizeof(double) * size);
  printf("hello2 \n");
  for(i = 0 ; i < size ; i++)
  {
    newpop[i] = malloc(sizeof(char) * targetlen + 1);
    oldpop[i] = malloc(sizeof(char) * targetlen + 1);
    for(j = 0 ; j < targetlen ; j++)
    {
      oldpop[i][j] = random_letter_or_space();
    }
    newpop[i][targetlen] = 0;
    oldpop[i][targetlen] = 0;
  }

  for(t = 0 ; t < steps ; t++)
  {
    compute_fitness(oldpop , numcorrect , normfit);
    dump_stats(numcorrect , oldpop , t + 1 , targetlen);
    for(i = 0 ; i < size ; i += 2)
    {
      parent_a = select_one(normfit);
      parent_b = select_one(normfit);
      // whether to add parent_a can not be equal to parent_b .  
      //printf("p_a = %d , p_b = %d \n" , parent_a , parent_b);
      reproduce(oldpop , newpop , parent_a , parent_b , targetlen , i);
    }
    
    swap = oldpop;
    oldpop = newpop;
    newpop = swap; 
    /*
    swap = newpop;
    newpop = oldpop;
    oldpop = swap;
    */
  }
  exit(0);
}
예제 #6
0
void TestWidget::setupWidgets(void)
{
    setWindowTitle(this->title);
    QMenuBar *menubar = new QMenuBar(this);
    QMenu *menu = new QMenu(QString("Title: ") + this->title);
    QAction *action_reproduce = new QAction("Reproduce", this);
    menu->addAction(action_reproduce);
    menubar->addMenu(menu);
    setMenuBar(menubar);
    menubar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    setCentralWidget(new QWidget(this));
    centralWidget()->setLayout(new QVBoxLayout(centralWidget()));
    QPushButton *button = new QPushButton("Reproduce", this);
    button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    centralWidget()->layout()->setContentsMargins(0,0,0,0);
    centralWidget()->layout()->setSpacing(0);
    centralWidget()->layout()->addWidget(button);
    connect(action_reproduce, SIGNAL(triggered()), SLOT(reproduce()));
    connect(button, SIGNAL(clicked()), SLOT(reproduce()));
}
int main() {
  int couples,i,boys=0,girls=0;
  printf("Enter the number of couples : ");
  scanf("%d",&couples);
  time_t seconds;
  time(&seconds);
  srand((unsigned int) seconds);
  for(i=0;i<couples;i++)
    reproduce(&boys, &girls);
  printf("\nBoys are %d and Girls are %d (including couples)\n",boys+couples,girls+couples);
  exit(0);
}
예제 #8
0
//prey.cc
void Prey::moveFrom(Coordinate from, Coordinate to) {
  Cell *toCell;
  --timeToReproduce;
  if (to != from) {
    toCell = getCellAt(to);
    delete toCell;
    setOffset(to);
    assignCellAt(to, this);
    if (timeToReproduce <= 0) {
      timeToReproduce = TimeToReproduce;
      assignCellAt(from, reproduce(from));
    }
    else
      assignCellAt(from, new Cell(from));
  }
}
예제 #9
0
파일: sendmsg02.c 프로젝트: 1587/ltp
int main(int argc, char *argv[])
{
	int lc;
	long seconds;

	tst_parse_opts(argc, argv, options, &help);
	setup();

	seconds = tflag ? SAFE_STRTOL(NULL, t_opt, 1, LONG_MAX) : 15;
	for (lc = 0; TEST_LOOPING(lc); lc++)
		reproduce(seconds);
	tst_resm(TPASS, "finished after %ld seconds", seconds);

	cleanup();
	tst_exit();
}
int main(int argn, char *argv[]) {
  int i=1;
  double v;
  
  parsecomamndline(argn,argv);
  initialize();
  init_subpopulation();
  populationconstraint(0);
  
//   print_populationdensity(0);
//   exit(1);
  
  if(averagepopdens) {
    init_averagepopdens();
  }
  if (quiet<2) fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e\n",i*epsilon,0.,populationvariance,populationsize,subpop_popsize,current_fixation_prob);
  
  while(subpop_count_extinctions + subpop_count_fixations < maxSteps) {
    reproduce(i);
    populationconstraint(i);
    
    
    if(i%outputstep == 0) {
      if (quiet<2)fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e\n",i*epsilon,allshifts*dx + popdens_1stmom/popdens_0thmom,populationvariance,populationsize,subpop_popsize,current_fixation_prob);
      if (quiet==0) print_populationdensity(i);
      if (averagepopdens) update_averagepopdens();
    }
    if(current_fixation_prob < subpop_final_threshold) {
      reset_subpopulation();
      subpop_count_extinctions++;
      printf("# event ( %d of %d ): extinction %lf\n",subpop_count_extinctions+subpop_count_fixations,maxSteps,i*epsilon);
      i=0;
    }
    if(current_fixation_prob > 1-subpop_final_threshold) {
      reset_subpopulation();
      subpop_count_fixations++;
      printf("# event ( %d of %d ): fixation %lf\n",subpop_count_extinctions+subpop_count_fixations,maxSteps,i*epsilon);
      i=0;
    }
    i++;
  }
  if(write_to_file)write_popdens();
  if(averagepopdens)write_averagepopdens();
  cleanup();
  return 0;
}
예제 #11
0
파일: gabump.c 프로젝트: Stray/CBofN
int main(int argc, char **argv)
{
  int i, j, t, parent_a, parent_b;
  char **swap, **newpop, **oldpop;
  double *fit, *normfit;
  
  get_options(argc, argv, options, help_string);

  srandom(seed);

  /* Force the size to be even. */
  size += (size / 2 * 2 != size);

  /* Initialize the population. */
  newpop = xmalloc(sizeof(char *) * size);
  oldpop = xmalloc(sizeof(char *) * size);
  fit = xmalloc(sizeof(double) * size);
  normfit = xmalloc(sizeof(double) * size);
  for(i = 0; i < size; i++) {
    newpop[i] = xmalloc(sizeof(char) * len + 1);
    oldpop[i] = xmalloc(sizeof(char) * len + 1);
    for(j = 0; j < len; j++)
      oldpop[i][j] = random() % 2 + '0';
    oldpop[i][len] = 0;
    newpop[i][len] = 0;
  }

  /* For each time step... */
  for(t = 0; t < gens; t++) {
    compute_fitness(oldpop, fit, normfit);
    dump_stats(t, oldpop, fit);

    /* Pick two parents by fitness and mate them until the
     * next generation has been made.
     */
    for(i = 0; i < size; i += 2) {
      parent_a = select_one(normfit);
      parent_b = select_one(normfit);
      reproduce(oldpop, newpop, parent_a, parent_b, i);
    }
    /* Make everything old new again. */
    swap = newpop; newpop = oldpop; oldpop = swap;
  }

  exit(0);
}
예제 #12
0
파일: ea.cpp 프로젝트: veimox/locokit69
Chromosome<T>* EA<T>::evolveThreaded(unsigned int generations, unsigned int threads)
{
    Gnuplot fitnessPlot;
    std::ofstream fitnessFile;
    fitnessFile.open("fitness_funtion.cvs", std::ios::trunc);
    fitnessFile << "Generation,Fitness value,";
    for (unsigned int gen_number = 0; gen_number < population[0]->getChromosome().size(); ++gen_number)
        fitnessFile << "Gen " << gen_number << ",";
    fitnessFile << std::endl;
    fitnessValuesMax.clear();
    for (unsigned int i = 0; i < generations; i++) {

        generation++;

        std::cout << "Generation " << generation;
        evaluateThreaded(threads);
        std::cout << " evaluated." << std::endl;
        select();
        reproduce();
        replace();

        fitnessValuesMax.push_back(std::make_pair(generation, selected[0]->getFitness()));
        fitnessFile << generation << "," << selected[0]->getFitness();
        for (auto gen : selected[0]->getChromosome())
            fitnessFile << "," << gen;
        fitnessFile << std::endl;
    }
    evaluateThreaded(threads);
    fitnessFile.close();

    int best_index = 0;
    double max = 0;
    for (unsigned int i = 0; i < population.size(); i++) {
        if (population[i]->getFitness() > max) {
            max = population[i]->getFitness();
            best_index = i;
        }
    }

    //fitnessPlot << "set fitnessValuesMax [-2:2]\nset yrange [-2:2]\n";
    fitnessPlot << "plot '-' with lines title 'Fitness values'\n";
    fitnessPlot.send1d(fitnessValuesMax);

    return population[best_index];
}
int main(void) {
  unsigned i, j, s;
  int minRandom;
  initGraph();

  /* Решение с генериране на произволни цикли */  
  minRandom = n*101;
  for (s = 0; s < maxSteps; s++) {
    for (i = 0; i < PSIZE; i++) {
      randomCycle(i);
      result[i] = evaluate(i);
    }
    for (j=0; j< PSIZE; j++) if (result[j]<minRandom) minRandom = result[j];
  }
  printf("Оптимално решение, намерено при генериране на произволни %ld цикъла: %d\n",
           PSIZE*maxSteps, minRandom);

  /* Решение с Генетичен Аглоритъм със същия брой итерации */  
  for (s = 0; s < maxSteps; s++) reproduce(s);
  printf("Най-късите цикли, намерени от генетичния алгортиъм: \n");
  for (i = 10; i > 0; i--) printf("%d, ", result[i]);
  printf(" %d\n", result[0]);
  return 0;
}
예제 #14
0
 void next_generation( population_type &pop , fitness_type &fitness )
 {
     reproduce( pop , fitness );
 }
예제 #15
0
파일: osil.c 프로젝트: mduwalsh/project
int main(int argc, char** argv)
{  
  if(argc^7){
    printf("Usage: ./osil bits seed N G Mu Chi\n");
    exit(1);
  }
  if ((sizeof(int) < 4)|| (sizeof(long int) < 8)){
    printf("Assumptions concerning bits are invalid: int has %d bits, unsigned long int has %d bits\n",
	   (int)(8*sizeof(int)), (int)(8*sizeof(unsigned long)));
    return 1;
  }
  L = atol(argv[1]);                     // bit length
  if (L > 32){
    printf("Can't have more thqan 32 bits\n");
    return 1;
  }
  int seed = atoi(argv[2]);
  N = (unsigned long)atoi(argv[3]);      // no. of individuals in finite population
  G = (unsigned long)atol(argv[4]);      // no. of generations
  Mu_n = atof(argv[5]);          
  Chi_n = atof(argv[6]);

  int i,j, n, m;
  double *d1, *d2, dst1, dst2;
  unsigned long *tmp_ptr;
  char fname[200];                       // file name
  FILE *fp;                              // data file pointer
  
  d1 = calloc(G, sizeof(double));
  d2 = calloc(G, sizeof(double));
  
  initrand(seed);
  setup();   
         
  init();                             // initializes memory for pop, M and Cr and also installs values for these  
  merge_sort(Pop[0], N);    
  // infinite population simulation   
  calc_px_from_finite_population(P0); // calculates haploids proportion using finite set
  P1 = g_w(G, P0, P1);
  display_p(P1);
  // find oscillating points for infinite population
  if( osc_points(P0, P1, P2, P3) ){     // if oscillation occurs
    {                                   // compute distance between finite population to oscillating points
      int a, b;  
      //finite population simulation
      for(i = 0; i < G; i++){           // evolve through G generations
	for(j = 0; j < N; j++){         // reproduce N offsprings      
	  a = rnd(N); b = rnd(N);
	  reproduce(a, b, j);           // randomly two parents chosen; will be proportional to proportion
	}
	merge_sort(Pop[0], N); 
	// calculate distance to oscillating points and write to file
	dst1 = dist_n(P2);               // distance to 1st oscillating point
	dst2 = dist_n(P3);               // distance to 2nd oscillating point
	d1[i] = dst1;
	d2[i] = dst2;
	// set new generation as parent generation for next generation
	tmp_ptr = Pop[0];
	Pop[0] = Pop[1];
	Pop[1] = tmp_ptr;		    
      }
    }
  }     
  deinit();        
  cleanup();
  
  sprintf(fname, "b%lug%lun%lu_osc.dat", L, G, N);
  if(!(fp = fopen(fname, "w"))){
    printf("%s could not be opened!! Error!!\n", fname);
    exit(2);
  }
   // write distances to file
   for(n = 0; n < G; n++){
    fprintf(fp, "%d  ", n);
    fprintf(fp, "%" PREC "lf  %" PREC "lf\n", d1[n], d2[n]);
   }
  fclose(fp);
  free(d1); free(d2);
  
  FILE *gp = popen ("gnuplot -persistent", "w"); // open gnuplot in persistent mode
  plot(gp, 0, fname, 3, "oscillation", "G", "d", 0, "" );
  fflush(gp);
  pclose(gp);
  
  return 0;
}
예제 #16
0
void LayerNet::gen_init (
   TrainingSet *tptr ,        // Training set to use
   struct LearnParams *lptr   // User's general learning parameters
   )
{
   int i, istart, individual, best_individual, generation, n_cross ;
   int first_child, parent1, parent2, improved, crosspt, nchoices, *choices ;
   int initpop, popsize, gens, climb, nvars, chromsize, split, ind ;
   float pcross, pmutate, error, besterror, *errors, *fitness, worst ;
   float fquit, favor_best, fitfac, maxerr, minerr, avgerr, overinit ;
   SingularValueDecomp *sptr ;
   struct GenInitParams *gptr ;  // User's genetic initialization parameters
   char *pool1, *pool2, *oldpop, *newpop, *popptr, *temppop, *best ;
   char msg[80] ;

   gptr = lptr->gp ;

   popsize = gptr->pool ;
   gens = gptr->gens ;
   climb = gptr->climb ;
   overinit = gptr->overinit ;
   pcross = gptr->pcross ;
   pmutate = gptr->pmutate ;

   fquit = lptr->quit_err ;

   favor_best = 3.1 ;
   fitfac = -20.0 ;


/*
--------------------------------------------------------------------------------

   Do all scratch memory allocation.

--------------------------------------------------------------------------------
*/

/*
   Allocate the singular value decomposition object for REGRESS.
*/

   if (nhid2 == 0)         // One hidden layer
      nvars = nhid1 + 1 ;
   else                    // Two hidden layers
      nvars = nhid2 + 1 ;

   MEMTEXT ( "GEN_INIT: new SingularValueDecomp" ) ;
   sptr = new SingularValueDecomp ( tptr->ntrain , nvars , 1 ) ;

   if ((sptr == NULL)  || ! sptr->ok) {
      memory_message("for genetic initialization. Try ANNEAL NOREGRESS.");
      neterr = 1.0 ;    // Flag failure to LayerNet::learn which called us
      if (sptr != NULL)
         delete sptr ;
      return ;
      }

   chromsize = nhid1 * (nin+1) ;        // Length of an individual's chromosome
   if (nhid2)                           // is the number of hidden weights
      chromsize += nhid2 * (nhid1+1) ;

   errors = fitness = NULL ;
   choices = NULL ;
   pool1 = pool2 = NULL ;
   MEMTEXT ( "GEN_INIT: errors, fitness, choices, best, pool1,pool2");
   if (((errors = (float*) MALLOC ( popsize * sizeof(float))) == NULL)
    || ((fitness = (float*) MALLOC ( popsize * sizeof(float))) == NULL)
    || ((best = (char*) MALLOC( chromsize )) == NULL)
    || ((choices = (int*) MALLOC ( popsize * sizeof(int))) == NULL)
    || ((pool1 = (char*) MALLOC( popsize * chromsize )) == NULL)
    || ((pool2 = (char*) MALLOC( popsize * chromsize )) == NULL)) {
      if (errors != NULL)
         FREE ( errors ) ;
      if (fitness != NULL)
         FREE ( fitness ) ;
      if (choices != NULL)
         FREE ( choices ) ;
      if (pool1 != NULL)
         FREE ( pool1 ) ;
      if (pool2 != NULL)
         FREE ( pool2 ) ;
      delete sptr ;
      memory_message("for genetic initialization.  Try ANNEAL NOREGRESS." ) ;
      neterr = 1.0 ;  // Flag failure to LayerNet::learn which called us
      return ;
      }

/*
   Generate initial population pool.

   We also preserve the best weights across all generations,
   as this is what we will ultimately return to the user.
   Its mean square error is besterror.
*/

   besterror = 1.e30 ;     // For saving best (across all individuals and gens)
   maxerr = avgerr = 0.0 ; // For progress display only
   best_individual = 0 ;   // Safety only
   initpop = popsize * overinit ; // Overinitialization of initial population
   progress_message ( "\nGenerating initial population" ) ;

   for (ind=0 ; ind<initpop ; ind++) { // Try overinitialization times

      if (ind<popsize)                 // If still in pop size limit
         individual = ind ;            // just use next avail space
      else {                           // Else we search entire pop
         worst = -1. ;                 // for the worst member
         for (i=0 ; i<popsize ; i++) { // which we will then replace
            if (errors[i] > worst) {
               worst = errors[i] ;
               individual = i ;
               }
            }
         avgerr -= worst ;             // Exclude discards from average
         }

      popptr = pool1 + individual * chromsize ; // Build init pop in pool1
      rand_ind ( popptr , chromsize ) ;         // Randomly generate individual
      decode ( popptr , nin , nhid1 , nhid2 ,   // Convert genotype (chromosome)
               hid1_coefs , hid2_coefs );       // to phenotype (weights)
      error = regress ( tptr , sptr ) ;         // Evaluate network error
      errors[individual] = error ;              // and keep all errors

      if (error < besterror) {                  // Keep track of best
         besterror = error ;                    // as it is returned to user
         best_individual = individual ;         // This is its index in pool1
         }

      if (error > maxerr)                       // Max and average error are
         maxerr = error ;                       // for progress display only
      avgerr += error ;

      if (error <= fquit)
         break ;

      progress_message ( "." ) ;
      }

   sprintf (msg , "\nInitial pop:    Min err=%7.4lf   Max=%7.4lf   Avg=%7.4lf",
	    100. * besterror, 100. * maxerr, 100.0 * avgerr / (float) popsize);
   progress_message ( msg ) ;


/*
   The initial population has been built in pool1.
   Copy its best member to 'best' in case it never gets beat (unlikely
   but possible!).
   Also, we will need best if the climb option is true.
*/

   popptr = pool1 + best_individual * chromsize ; // Point to best
   memcpy ( best , popptr , chromsize ) ;         // and save it

/*
   This is the main generation loop.  There are two areas for population pool
   storage: pool1 and pool2.  At any given time, oldpop will be set to one of
   them, and newpop to the other.  This avoids a lot of copying.
*/

   oldpop = pool1 ;       // This is the initial population
   newpop = pool2 ;       // The next generation is created here

   for (generation=0 ; generation<gens ; generation++) {

      if (error <= fquit) // We may have satisfied this in init pop
         break ;          // So we test at start of generation loop

      error_to_fitness ( popsize , favor_best , fitfac , errors , fitness ) ;

      fitness_to_choices ( popsize , fitness , choices ) ;

      nchoices = popsize ;         // Will count down as choices array emptied
      n_cross = pcross * popsize ; // Number crossing over
      first_child = 1 ;            // Generating first of parent's 2 children?
      improved = 0 ;               // Flags if we beat best

      if (climb) {                 // If we are to hill climb
         memcpy ( newpop , best , chromsize ) ; // start with best
         errors[0] = besterror ;   // Record its error
         istart = 1 ;              // and start children past it
         }
      else
         istart = 0 ;

/*
   Generate the children
*/

      maxerr = avgerr = 0.0 ;   // For progress display only
      minerr = 1.0 ;            // Ditto

      for (individual=istart ; individual<popsize ; individual++) {

         popptr = newpop + individual * chromsize ; // Will put this child here

         if (first_child)  // If this is the first of 2 children, pick parents
            pick_parents ( &nchoices , choices , &parent1 , &parent2 ) ;

         if (n_cross-- > 0)    // Do crossovers first
            reproduce ( oldpop + parent1 * chromsize , oldpop + parent2 * chromsize ,
                        first_child , chromsize , popptr , &crosspt , &split ) ;
         else if (first_child) // No more crossovers, so just copy parent
            memcpy ( popptr , oldpop + parent1 * chromsize , chromsize ) ;
         else
            memcpy ( popptr , oldpop + parent2 * chromsize , chromsize );

         if (pmutate > 0.0)
            mutate ( popptr , chromsize , pmutate ) ;

         decode ( popptr , nin , nhid1 , nhid2 , hid1_coefs , hid2_coefs ) ;
         error = regress ( tptr , sptr ) ; // Evaluate child's error
         errors[individual] = error ;      // and keep each

         if (error < besterror) {          // Keep track of best
            besterror = error ;            // It will be returned to user
            best_individual = individual ; // This is its index in newpop
            improved = 1 ;                 // Flag so we copy it later
            }

         if (error > maxerr)               // Min, max and average error
            maxerr = error ;               // for progress display only
         if (error < minerr)
            minerr = error ;
         avgerr += error ;

         if (error <= fquit)
            break ;

         first_child = ! first_child ;
         } // For all genes in population

/*
   We finished generating all children.  If we improved (one of these
   children beat the best so far) then copy that child to the best.
   Swap oldpop and newpop for the next generation.
*/

      if (improved) {
         popptr = newpop + best_individual * chromsize ; // Point to best
         memcpy ( best , popptr , chromsize ) ;          // and save it
         }

      temppop = oldpop ;   // Switch old and new pops for next generation
      oldpop = newpop ;
      newpop = temppop ;

      sprintf(msg, "\nGeneration %3d: Min err=%7.4lf   Max=%7.4lf   Avg=%7.4lf",
              generation+1, 100. * minerr, 100. * maxerr,
	      100.0 * avgerr / (float) popsize ) ;
      progress_message ( msg ) ;
      }

/*
   We are all done.
*/

   decode ( best , nin , nhid1 , nhid2 , hid1_coefs , hid2_coefs ) ;
   besterror = regress ( tptr , sptr ) ;              // Evaluate network error

   MEMTEXT ( "GEN_INIT: errors, fitness, choices, best, pool1,pool2");
   FREE ( errors ) ;
   FREE ( fitness ) ;
   FREE ( choices ) ;
   FREE ( best ) ;
   FREE ( pool1 ) ;
   FREE ( pool2 ) ;
   MEMTEXT ( "GEN_INIT: delete sptr" ) ;
   delete sptr ;
}
예제 #17
0
double genetic (
      double (*func)( int n , double *x ) ,  // Function to be minimized
      int ngens ,        // Number of complete generations
      int popsize ,      // Number of individuals in population
      int climb ,        // Do we hill climb via elitism?
      double stddev ,    // Standard deviation for initial population
      double pcross ,    // Probability of crossover (.6-.9 typical)
      double pmutate ,   // Probability of mutation (.0001 to .001 typical)
      double favor_best ,// Factor for favoring best over average (2-3 is good)
      double fitfac ,    // Factor for converting fval to raw fitness (-20 good)
      double fquit ,     // Quit if function reduced to this amount
      int nvars ,        // Number of variables in x
      double *x ,        // Set to starting estimate when called; returns best
      double *best,      // Work vector nvars long
      int *choices ,     // Work vector popsize long
      double *fvals ,    // Work vector popsize long
      double *fitness ,  // Work vector popsize long
      double *pool1,     // Work vector nvars * popsize long
      double *pool2 )    // Work vector nvars * popsize long
{
   int istart, individual, best_individual, generation, n_cross ;
   int first_child, parent1, parent2, improved, crosspt, nchoices ;
   double fval, bestfval, *oldpop, *newpop, *popptr, *temppop ;

/*
   Generate initial population pool.

   We also preserve the best point across all generations, as this is what
   we will ultimately return to the user.  Its objective function value is
   bestfval.
*/

   bestfval = 1.e30 ;     // For saving best (across all individuals)
   best_individual = 0 ;  // Safety only

   for (individual=0 ; individual<popsize ; individual++) {

      popptr = pool1 + individual * nvars ;   // Build population in pool1
      shake ( nvars , x , popptr , stddev ) ; // Randomly perturb about init x
      fval = (*func) ( nvars , popptr ) ;     // Evaluate function there
      fvals[individual] = fval ;              // and keep function value of each

      if (fval < bestfval) {                  // Keep track of best
         bestfval = fval ;                    // as it will be returned to user
         best_individual = individual ;       // This is its index in pool1
         }

      if (fval <= fquit)
         break ;
      }

/*
   The initial population has been built in pool1.
   Copy its best member to 'best' in case it never gets beat (unlikely
   but possible!).
*/

   popptr = pool1 + best_individual * nvars ;           // Point to best
   memcpy ( best , popptr , nvars * sizeof(double) ) ;  // and save it

/*
   This is the main generation loop.  There are two areas for population pool
   storage: pool1 and pool2.  At any given time, oldpop will be set to one of
   them, and newpop to the other.  This avoids a lot of copying.
*/

   oldpop = pool1 ;   // This is the initial population
   newpop = pool2 ;   // The next generation is created here

   for (generation=0 ; generation<ngens ; generation++) {

      if (fval <= fquit)   // We may have satisfied this in initial population
         break ;           // So we test at start of generation loop

      fval_to_fitness ( popsize , favor_best , fitfac , fvals , fitness ) ;

      fitness_to_choices ( popsize , fitness , choices ) ;

      nchoices = popsize ;         // Will count down as choices array emptied
      n_cross = pcross * popsize ; // Number crossing over
      first_child = 1 ;            // Generating first of parent's 2 children?
      improved = 0 ;               // Flags if we beat best

      if (climb) {                  // If we are to hill climb
         memcpy ( newpop , best , nvars * sizeof(double) ) ; // start with best
         fvals[0] = bestfval ;      // Record its error
         istart = 1 ;               // and start children past it
         }
      else
         istart = 0 ;

/*
   Generate the children
*/

      for (individual=istart ; individual<popsize ; individual++) {

         popptr = newpop + individual * nvars ; // Will put this child here

         if (first_child)  // If this is the first of 2 children, pick parents
            pick_parents ( &nchoices , choices , &parent1 , &parent2 ) ;

         if (n_cross-- > 0)    // Do crossovers first
            reproduce ( oldpop + parent1 * nvars , oldpop + parent2 * nvars ,
                        first_child , nvars , popptr , &crosspt ) ;
         else if (first_child) // No more crossovers, so just copy parent
            memcpy( popptr , oldpop + parent1 * nvars , nvars * sizeof(double));
         else
            memcpy( popptr , oldpop + parent2 * nvars , nvars * sizeof(double));

         if (pmutate > 0.0)
            mutate ( popptr , nvars , stddev , pmutate ) ;

         fval = (*func) ( nvars , popptr ) ; // Evaluate function for this child
         fvals[individual] = fval ;          // and keep function value of each

         if (fval < bestfval) {              // Keep track of best
            bestfval = fval ;                // It will be returned to user
            best_individual = individual ;   // This is its index in newpop
            improved = 1 ;                   // Flag so we copy it later
            }

         if (fval <= fquit)
            break ;

         first_child = ! first_child ;
         } // For all genes in population

/*
   We finished generating all children.  If we improved (one of these
   children beat the best so far) then copy that child to the best.
   Swap oldpop and newpop for the next generation.
*/

      if (improved) {
         popptr = newpop + best_individual * nvars ;          // Point to best
         memcpy ( best , popptr , nvars * sizeof(double) ) ;  // and save it
         }

      temppop = oldpop ;   // Switch old and new pops for next generation
      oldpop = newpop ;
      newpop = temppop ;
      }

/*
   We are all done.  Copy the best to x, as that is how we return it.
*/

   memcpy ( x , best , nvars * sizeof(double) ) ;  // Return best
   return bestfval ;
}
예제 #18
0
int main(int argc, char **argv)
{
    gsl_rng_env_setup();

    T = gsl_rng_default;
    r = gsl_rng_alloc (T);
    gsl_rng_set(r, time(NULL));

    Graph *g = new Graph();
	g->addVertex(Vertex(1, "v1", 0, 0, 0, 1.0, 1.0, 1.0));
	g->addVertex(Vertex(2, "v2", 0, 0, 0, 1.0, 0.2, 0.2));
	g->addVertex(Vertex(3, "v3", 0, 0, 0, 0.2, 1.0, 0.2));
	g->addVertex(Vertex(4, "v4", 0, 0, 0, 0.2, 0.2, 1.0));

	g->addEdge(1, 2);
	g->addEdge(1, 3);
	g->addEdge(3, 4);

	ptr population(new std::vector<Graph>(4, *g));
	/*
	std::cout << "Population" << std::endl;
	printgraph(population);

	ptr reproduced = reproduce(population);
	std::cout << "Reproduced" << std::endl;
	printgraph(reproduced);

	ptr offsprings = genetic(reproduced);
	std::cout << "Offsprings" << std::endl;
	printgraph(offsprings);

	population = succession(population, offsprings);
	std::cout << "After one iteration" << std::endl;
	printgraph(population);
	*/

	int iterationcount = 0;
	double bestv = best(population);
	double bestvold = bestv * 2;

	std::cout << "best " << bestv << "; bestvold " << bestvold << std::endl;
	while (fabs(bestvold - bestv)/bestvold > 0.00000001)
	{
		++iterationcount;
		ptr offsprings = genetic(reproduce(population));
		population = succession(population, offsprings);
		bestvold = bestv;
		bestv = best(population);
	}

	std::cout << "Possible result found after " << iterationcount << "iterations: " << std::endl;
	printgraph(population);

	const Graph *bestgraph = bestg(population);
	for (Graph::vertices_const_iterator i = bestgraph->vertices.begin(); i != bestgraph->vertices.end(); ++i)
	{
		const Vertex &v = i->second;
		std::cout << "\"" << v.name << "\"";
		std::cout << "\t@" << v.x << " " << v.y << " " << v.z;
		std::cout << "\tcolor" << v.r << " " << v.g << " " << v.b;
		std::cout << "\tfrozen light size 1.0" << std::endl;
	}

    gsl_rng_free (r);
	return 0;
}
예제 #19
0
파일: Petri.cpp 프로젝트: jchildren/petri
int main()
{
	
	// initialise
	const unsigned int kGridSize = 25;

	const unsigned int kPopulationMax = 30;
	const unsigned int kFoodMax = 50;

	const unsigned int kReproduceEnergy = 120;

	const unsigned int kCellStartEnergy = 100;
	const unsigned int kMaxFoodEnergy = 100;

	Dish petri(kGridSize);

	unsigned int total_population = 15;
	unsigned int total_food = 30;

	std::vector<Cell> population;

	for (unsigned int i = 0; i < total_population; i++) {
		population.push_back(Cell(kGridSize, kCellStartEnergy));
	}

	std::list<Food> supply;

	for (unsigned int i = 0; i < total_food; i++) {
		supply.push_back(Food(kGridSize, kMaxFoodEnergy));
	}

	bool exit = false;
	unsigned int w = 1;

	while (w < 50) {

		/*
		// Process step
		*/
		for (auto cell = population.begin(); cell != population.end(); ++cell) {
			if (cell->alive() == true) {
				// move
				cell->move(kGridSize);

				for (auto food = supply.begin(); food != supply.end(); ++food) {
					if (cell->location() == food->location()) {
						total_food = supply.size();
						cell->consume_food(*food);
						food = supply.erase(food);
					}
				}

				for (auto target = population.begin(); target != population.end(); ++target) {
					switch (can_consume_cell(*cell, *target))
					{
					case false:
						continue;
					case true:
						target = population.erase(target);
						break;
					default:
						break;
					} 
				}
				

				// reproduce
				if ((total_population < kPopulationMax) && (cell->reproduce())) {
					population.push_back(Cell(kGridSize, cell->energy() / 2));
					cell->set_energy(cell->energy() / 2);

					total_population = population.size();
				}



				// death
				if (cell->energy() <= 0) {
					cell->set_alive(false);
				}
			}
		}

		if (total_food < kFoodMax) {
			supply.push_back(Food(kGridSize, kMaxFoodEnergy));

			total_food = supply.size();
		}

		/*
		// Input step
		*/

		// poll user input

		/*
		// Display step
		*/

		// display grid

		// TODO: Optimise this horrible loop
		for (unsigned int i = 0; i < kGridSize; i++) {
			for (unsigned int j = 0; j < kGridSize; j++) { 
				bool occupied = false;
				position display_location;
				display_location.x = i;
				display_location.y = j;
				for (Cell cell : population) {
					if (cell.location() == display_location) {
						if (cell.alive() == true) {
							std::cout << cell.energy();
						}
						else {
							std::cout << "-";
						}
						occupied = true;
					}
				}
				for (Food food : supply) {
					if (food.location() == display_location) {
						std::cout << ".";
						occupied = true;
					}
				}
				if (occupied == false) {
					std::cout << " ";
				}
				else {
					occupied = false;
				}

			}
			std::cout << "\n";
		}
		
		for (unsigned int i = 0; i < kGridSize; i++) {
			std::cout << "=";
		}
		std::cout << "\n" << total_population;

		std::cout.flush();
		Sleep(1500);

		w++;
	}

	population.clear();
	supply.clear();
	
	return 0;
}
예제 #20
0
void run(struct block * b){
    if(!b->die && (b->energy <= 0 || b->nutrients <= 0 || b->pos > INSTRUCTIONS - 1)){
        die(b);
        return;
    }
    energymean += b->energy;
    if(!b->die){
        switch(b->program[b->pos]){
            case 0:
                if(b->lastRep > 0) break;
                b->pos = (b->pos + 1) % INSTRUCTIONS;
                reproduce(b);
                break;
            case 1:
                getEnegy(b);
                break;
            case 2:
                getNutrients(b);
                break;
            case 3:
                break;
                b->pos = (b->pos + 1) % INSTRUCTIONS;
                switch(b->program[b->pos]){
                    case 0:
                          move(b, 1, 0);
                          b->energy -= 5;
                          break; 
                    case 1:
                          move(b, 1, 0);
                          b->energy -= 5;
                          break;
                    case 2:
                          b->energy -= 5;
                          break; 
                    case 3:
                          move(b, -1, 0);
                          b->energy -= 5;
                          break;
                    case 4:
                          move(b, -1, 0);
                          b->energy -= 5;
                          break; 
                    case 5:
                          move(b, -1, -1);
                          b->energy -= 2;
                          break;
                    case 6:
                          move(b, 0, -1);
                          b->energy += 1;
                          break; 
                    case 7:
                          move(b, 1, -1);
                          b->energy -= 2;
                          break;
                }
                if(b->y > Y_SIZE - 1) kill(b);
                break;
            case 4:
                atack(b);
                break;
            case 5: //Logic Operations
                b->pos = (b->pos + 1) % INSTRUCTIONS;
                switch(b->program[b->pos]){
                        case 0:
                                ++b->ptr;
                                if(b->ptr >= INSTRUCTIONS) die(b);
                                break;
                        case 1:
                                --b->ptr;
                                if(b->ptr < 0) die(b);
                                break;
                        case 2:
                                ++b->memory[b->ptr];
                                break;
                        case 3:
                                --b->memory[b->ptr];
                                if(b->memory[b->ptr] < 0) die(b);
                                break;
                        case 4:
                                if(b->loops >= 19) break;
                                b->loops_adr[b->loops].progPos = b->pos + 1;
                                b->loops_adr[b->loops++].memAdr = b->ptr;
                                break;
                        case 5:
                                if(b->loops > 0 && b->memory[b->loops_adr[b->loops - 1].memAdr]){
                                        b->pos = b->loops_adr[b->loops - 1].progPos;
                                }else if(b->loops > 0){
                                        --b->loops;
                                }else{
                                        die(b);
                                }
                                break;
                }
                break;
            case 6:
                die(b);
                break;
                
        }
    }else{
        switch(b->program[b->pos]){
            case 1:
                getEnegy(b);
                break;
            case 2:
                getNutrients(b);
                break;
        }
    }
    if(b->energy < 10){
        kill(b);
    }
    b->pos = (b->pos + 1) % INSTRUCTIONS;
    ++b->age;
    --b->lastRep;
    b->energy -= b->age / 800.0;
    b->nutrients -= b->age / 800.0;
}