Ejemplo n.º 1
0
Fitness FitnessNoiseSource::noisify(
	Fitness cleanFitness,
	std::function<double(double)> noisemaker
) {
	std::vector<FitnessPair> components = cleanFitness.getComponents();
	for (unsigned int i = 0; i < components.size(); i++)
		components[i] = std::make_tuple(
			noisemaker(std::get<0>(components[i])),
			std::get<1>(components[i])
		);
	return Fitness(components);
}
//protected
//pure-virtual from FlightPlanner
void GreedyFlightPlanner::doIteration()
{
    if (_frontier.isEmpty())
    {
        UAVOrientation lastOrientation;
        Position lastPos = _bestPathThisIteration.last();
        if (this->bestFlightSoFar().size() >= 2)
            lastOrientation.setRadians(_lastOrientation);
        QSharedPointer<GreedyPlanningNode> iterTopNode(new GreedyPlanningNode(lastPos,
                                                                              lastOrientation,
                                                                              0,
                                                                              GREED_DEPTH));
        iterTopNode->setFlighPath(this->bestFlightSoFar());
        _frontier.enqueue(iterTopNode);
    }

    _bestFitnessThisIteration = Fitness(0, 0);
    _bestPathThisIteration.clear();

    while (!_frontier.isEmpty())
    {
        QSharedPointer<GreedyPlanningNode> top = _frontier.dequeue();

        //Check out the performance of the top's flight
        const QList<Position>& flightPath = top->flightPath();

        Fitness score = this->problem()->calculateFlightPerformance(flightPath);


        if (score >= this->bestFitnessSoFar())
        {
            this->setBestFitnessSoFar(score);
            this->setBestFlightSoFar(flightPath);
            _lastOrientation = top->orientation().radians();
        }

        if (score >= _bestFitnessThisIteration)
        {
            _bestFitnessThisIteration = score;
            _bestPathThisIteration = flightPath;
        }

        QVector<QSharedPointer<GreedyPlanningNode> > children = top->visit();
        foreach(QSharedPointer<GreedyPlanningNode> child, children)
        {
            child->setParent(top);
            _frontier.enqueue(child);
        }
    }
Ejemplo n.º 3
0
// ---------------------------------------------------------------------------
// Setup each individuals test case
// This is an example of how one can perform the executions and fitness tests
// 'manually' without the framework automatically assigning fitness.
GPFitness EvaluateIndividual( GPEnvironment& environment, int individual_index )
{
	dog_x	= 0;
	dog_y	= 0;

	stick_x	= rand() % 21 - 10;
	stick_y	= rand() % 21 - 10;

	const int kTurns = 30;
	for( int i = 0; i < kTurns; ++i )
	{
		// each dog will get a kTurns in which to try retrieve the stick
		// and we just want to execute the individual - dont call the fitness
		// function yet!
		environment.ExecuteIndividual< void >( individual_index );
	}

	return Fitness( environment, individual_index );
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
	MPI_Init(&argc, &argv);

	int POPSIZE = atoi(argv[1]);	
	int GENERATION = atoi(argv[2]);
	int NUM_GAMES = atoi(argv[3]);
	float CROSSOVER = atof(argv[4]);
	float MUTATION = atof(argv[5]);
	int i,j,k,q,s,b2d,count;
	int world_rank,world_size;
	unsigned int temp[2], temp2[2];
	float RANDOM2 = drand48();

	srand48(time(NULL));
	pop *player = NULL;
	pop p[2];

	MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
	MPI_Comm_size(MPI_COMM_WORLD, &world_size);
	
/*------------------------MPI_STRUCT----------------------------------*/
	MPI_Datatype mpi_pop;
	MPI_Datatype types[3] = {MPI_UNSIGNED,MPI_UNSIGNED,MPI_UNSIGNED};
	int block[3] = {4,1,1};
	MPI_Aint offset[3] = {offsetof(pop,history),offsetof(pop,fitness),offsetof(pop,move)};
	MPI_Type_create_struct(3,block,offset,types,&mpi_pop);
	MPI_Type_commit(&mpi_pop);

	if (world_rank == 0)
	{
		if (world_size > POPSIZE/4)
		{
			printf("Too many processes for Population Size.\n Please input an even Population Size.\n");
			MPI_Abort(MPI_COMM_WORLD, 1);
		}
	}

/*---------------Allocate the memory for the players------------------*/
	
	if (world_rank == 0)
	{	
		player = malloc(POPSIZE*sizeof(pop));
		for (i=0; i<POPSIZE; i++)
		{
			for(j=0; j<4; j++)
			{
				player[i].history[j] = lrand48() % 2;
				player[i].fitness = 0;
			}
		}	
		printf("Processor %d has data:\n", world_rank);
		for (i=0; i<POPSIZE; i++)
		{
			for (j=0; j<4; j++)
			{
				printf("%d ", player[i].history[j]);
			}
			printf("\n");
		}
	}
	
	int ARRAY_SIZE = POPSIZE/4;
	pop *sub_arrays = NULL;

	if (world_rank != 0)
	{
		sub_arrays = malloc(ARRAY_SIZE*sizeof(pop));
	}

/*-----------------------RUN THE ALGORITHM---------------------------*/	

	for (k=0; k<GENERATION; k++)
	{
		MPI_Scatter(player, ARRAY_SIZE, mpi_pop, sub_arrays, ARRAY_SIZE, mpi_pop, 0, MPI_COMM_WORLD);

		if (world_rank != 0)
		{
			for (i=0; i<ARRAY_SIZE; i++)
			{
				for (j=ARRAY_SIZE; j>=0; j--)
				{
					p[0] = player[i];	
					p[1] = player[j];		
				
					for(q=0; q<NUM_GAMES; q++)
					{
						b2d = ((p[0].history[0]*8) + (p[0].history[1]*4) + (p[0].history[2]*2) + p[0].history[3]);
						b2d = ((p[1].history[0]*8) + (p[1].history[1]*4) + (p[1].history[2]*2) + p[1].history[3]);
									
						Strategy(p[0], b2d);
						Strategy(p[1], b2d);
						Fitness(p);

						for (s=4; s>0; s--)
						{
							p[0].history[s] = p[0].history[s-1];
							p[1].history[s] = p[1].history[s-1];
						} 	
						p[0].history[0] = p[0].move;
						p[1].history[0] = p[1].move;
					}

					player[i] = p[0];
					player[j] = p[1];
				}
			}
		}

		MPI_Barrier(MPI_COMM_WORLD);
		MPI_Gather(sub_arrays, ARRAY_SIZE, mpi_pop, player, ARRAY_SIZE, mpi_pop, 0, MPI_COMM_WORLD);	

/*-----------------------Perform Selection-----------------------------*/		
	
		if (world_rank == 0)
		{
			for(count=0; count<2; count++)
			{
				int sumFitness = 0;
				for (i=0; i<POPSIZE; i++)
				{
					sumFitness += p[i].fitness;
					int RANDOM = lrand48() % sumFitness;
					if (sumFitness >= RANDOM)
					{
						p[count] =  player[i];
					}
				}
			}
/*------------------------Crossover-------------------------------------*/

			if (RANDOM2 < CROSSOVER)
			{
				temp [0] = p[0].history[2];
				temp [1] = p[0].history[3];
				temp2[0] = p[1].history[2];
				temp2[1] = p[1].history[3];
				p[0].history[2] = temp2[0];
				p[0].history[3] = temp2[1];
				p[1].history[2] = temp[ 0];
				p[1].history[3] = temp[ 1];
			}

/*---------------------Mutate Players------------------------------------*/


			if (RANDOM2 < MUTATION)
			{
				int mp = lrand48() % 4;
				for (count=0; count<2; count++)
				{
					if (p[count].history[mp] == 0) 
					{	
						p[count].history[mp] = 1;
					}
					else
					{ 
						p[count].history[mp] = 0;
					}
				}
			}
			
			player[lrand48() % POPSIZE] = p[0];
			player[lrand48() % POPSIZE] = p[1];
		}

		printf("Processor %d has data:\n", world_rank);
		for (i=0; i<POPSIZE; i++)
		{
			for (j=0; j<4; j++)
			{
				printf("%d ", player[i].history[j]);
			}
			printf("\n");
		}
	}

	for(i=0; i<POPSIZE; i++)
	{
		for (j=0; j<4; j++)
		{
			printf("%d", player[i].history[j]);
		}
		printf("\n");
		printf("Fitness: %d\n", player[i].fitness);
	}
	if (world_rank == 0)
		free(player);
	if (world_rank != 0)
		free(sub_arrays);

	MPI_Finalize();
	return 0;

}
Ejemplo n.º 5
0
//======================================================Programa Principal=====================================================================//
int main(){
  int ciclo, i, j, n, aux, exp, selecao, inicio, comp, fim, MT, melhor, melhor1, corrida,melhorCiclo;
  double Populacao[TAMPOP][TAMCADEIA], ProxGer[TAMPOP][TAMCADEIA], PopReal[TAMPOP][QTDVAR];
  double min[QTDVAR], max[QTDVAR], Apt[TAMPOP], f1[TAMCADEIA], f2[TAMCADEIA], solucao[TAMCADEIA];
  double soma, aleatorio, x1, x2,fit;

/*Atribuindo valores passados ao programa para as variáveis*/
//Gerando números aleatórios
//Utiliza o relógio do computador
//   srand((unsigned)time(NULL));

//Especifica qual semente será utilizada para gerar os números aleatórios
   unsigned semente = 1;
   srand(semente);

//Permite ao usiário digitar uma semente para gerar os números aleatórios
//   unsigned semente;
//   printf("Entre com a semente: ");
//   scanf ("%u", &semente);
//   srand(semente);

//--------------------------------------------------------Intervalo de busca das funções-------------------------------------------------------//
   min[0] = -5.12; //Valor minimo do intervalo de busca de x1.
   max[0] =  5.12; //Valor maximo do intervalo de busca de x1.
   min[1] = -5.12; //Valor minimo do intervalo de busca de x2.
   max[1] =  5.12; //Valor maximo do intervalo de busca de x1.
//---------------------------------------------------------------------Fim---------------------------------------------------------------------//

   FILE *arquivo,*arq;
   arquivo=fopen("GA.txt","w"); //Abrindo o arquivo para gravar os resultados
   arq=fopen("GAresult.txt","a");

printf("*\n");
   clock_t tInicio, tFim, tDecorrido; //Calculando o tempo de execução do programa
   tInicio=clock();
  fit=0.0; //pega o valor da função objetivo inicial para fins de comparação
   for(corrida = 1; corrida <= TOTCOR; corrida++){ //Numero de corridas realizadas pelo programa

//---------------------------------------------------------Gerando a populacao inicial---------------------------------------------------------//
//   printf("Populacao Inicial:\n");
   for(i = 0; i < TAMPOP; i++){ //Gerando os elementos da matriz de cromossomos.
      for(j = 0; j < TAMCADEIA; j++){
         Populacao[i][j] = (double)(0 + rand() % 2); //Números aleatórios entre [0, 1]
//         printf("%.f ", Populacao[i][j]);
      }
//      printf("\n");
   } //Fim (Gerando os elementos da matriz de cromossomos).
//--------------------------------------------------------------------Fim----------------------------------------------------------------------//

//----------------------------------------------------Transformando a populacao binaria em real------------------------------------------------//
   PopulacaoReal(Populacao, PopReal, min, max); //Gerando a nova matriz com numeros reais.
//Imprimindo a populacao na base decimal.
//   printf("\nPopulacao Real:\n");
//   for(i = 0; i < TAMPOP; i++){
//      for(j = 0; j < QTDVAR; j++){
//         printf("%7.4f ", PopReal[i][j]);
//      }
//      printf("\n");
//   } //Fim (Gerando os elementos da matriz de cromossomos).
//--------------------------------------------------------------------Fim----------------------------------------------------------------------//

//----------------------------------------------Calculando a aptidao de cada cadeia de cromossomo----------------------------------------------//
   for(i = 0; i < TAMPOP; i++){ //Calcula a aptidao de cada cadeia de cromossomos.
      Apt[i] = Fitness(PopReal[i][0], PopReal[i][1]);
   }
   AptAdm(Apt); //Admencionaliza as Aptidoes.
//----------------------------------------------------------------Fim--------------------------------------------------------------------------//

//-----------------------------------------------------Calculando o melhor cromossomo----------------------------------------------------------//
   melhor = Best(Apt);
   melhor1 = melhor;
   for(i = 0; i < TAMCADEIA; i++){
      solucao[i]=Populacao[melhor1][i]; //Solução na forma binária.
   }
   x1 = PopReal[melhor1][0]; //Guarda a melhor solução do primeiro cromossomo em formato real.
   x2 = PopReal[melhor1][1]; //Guarda a melhor solução do segundo cromossomo em formato real.
   /*MEU COMENTÁRIO NAS DUAS LINHAS SEGUINTES
   fprintf(arquivo,"Melhor da Populacao Inicial:\n");
   fprintf(arquivo,"%10.6f %10.6f %10.6f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento.
//   printf("\nMelhor solucao da Populacao Inicial:\n");*/
//   printf("%7.4f %7.4f %7.4f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento.

//----------------------------------------------------------------Fim--------------------------------------------------------------------------//

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Evolucoes+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
//Ciclo de evolução da técnica: evolução, crossover e mutação
 /* COMENTEI  fprintf(arquivo,"\nEvolucoes:\n"); */
//   printf("\nCromossomos selecionados:\n");
   ciclo = 1;

   while(ciclo <= NUMEVOL){
      for(j = 0; j < TAMCADEIA; j++){
         ProxGer[0][j] = solucao[j]; //Pego minha melhor solução da População
      }
      for(i = 1; i < TAMPOP; i++){
         selecao = Roleta(Apt);
         for(j = 0; j < TAMCADEIA; j++){
            ProxGer[i][j] = Populacao[selecao][j]; //Cromossomo selecionado na População.
         }
      }

//----------------------------------------------------------------Reproduzir-------------------------------------------------------------------//
    for(i = 0; i < TAMPOP; i += 2){ //Realiza o crossover (crusamento) dos cromossomos selecionados 2 a 2.
       aleatorio = ((double)rand() / (double)RAND_MAX); //Numero aleatorio entre [0, 1].
       if(aleatorio <= TXCO){ //Inicio do crossover.
          inicio = rand() % (TAMCADEIA - 1); //Ponto de inicio do crossover.
          comp = ((TAMCADEIA - 1) - inicio); //Comprimento do crossover.
          fim = (rand() % (comp)) + inicio; //Ponto de termino do crossover.
          for(j = 0; j < TAMCADEIA; j++){ //Inicializando os vetores dos cromossomos filhos.
             f1[j] = -1.0; //Filho 1.
             f2[j] = -1.0; //Filho 2.
          } //Fim (Inicializando os vetores dos cromossomos filhos).
          for(j = inicio; j <= fim; j++){ //Gerando da parte interna dos cromossomos filhos.
             f1[j] = ProxGer[i][j]; //Filho 1 recebe os genes do Pai 1.
             f2[j] = ProxGer[i + 1][j]; //Filho 2 recebe os genes do Pai 2.
          } //Fim (Gerando da parte interna dos cromossomos filhos).
          for(j = 0; j < TAMCADEIA; j++){ //Gerando os extremos dos cromossomos filhos.
             if((f1[j] == -1) && (f2[j] == -1)){
                f1[j] = ProxGer[i + 1][j]; //Filho 1 recebe os genes do Pai 2.
                f2[j] = ProxGer[i][j]; //Filho 2 recebe os genes do Pai 1.
             }
          } //Fim (Gerando os extremos dos cromossomos filhos).
          MT = rand() % (TAMCADEIA); //Definindo o elemento do cromossomo f1 a sofrer mutacao.
          f1[MT] = Mutacao(f1[MT]); //Realizando a mutacao no filho 1.
          MT = rand() % (TAMCADEIA); //Definindo o elemento do cromossomo f1 a sofrer mutacao.
          f2[MT] = Mutacao(f2[MT]); //Realizando a mutacao  no filho 2.
          for(j = 0; j < TAMCADEIA; j++){
             Populacao[i][j] = f1[j]; //A nova populacao recebe o filho 1.
             Populacao[i + 1][j] = f2[j]; //A nova populacao recebe o filho 2.
          }
       } //Fim (Inicio do crossover).
       else{ //Definindo a nova Populacao de cromossomos caso nao ocorra o crossover.
          for(j = 0; j < TAMCADEIA; j++){ //A matriz Populacao recebe a matriz ProxGeracao.
             Populacao[i][j] = ProxGer[i][j];
             Populacao[i + 1][j] = ProxGer[i + 1][j];
          } //Fim (A matriz Populacao recebe a matriz ProxGeracao).
       } //Fim (Definindo a nova Populacao de cromossomos caso nao ocorra o crossover).
    } //Fim (Realiza o crossover dos cromossomos selecionados 2 a 2).
//-------------------------------------------------------------Fim da reproducao---------------------------------------------------------------//

//---------------------------------------------------Transformando a populacao binaria em real-------------------------------------------------//
   PopulacaoReal(Populacao, PopReal, min, max); //Gerando a nova matriz com numeros reais.
//-------------------------------------------------------------------Fim-----------------------------------------------------------------------//

//-----------------------------------------------------------Calculando a aptidao--------------------------------------------------------------//
   for(i = 0; i < TAMPOP; i++){ //Calcula a aptidao de cada cadeia de cromossomos.
      Apt[i] = Fitness(PopReal[i][0], PopReal[i][1]);
   }
   AptAdm(Apt); //Admencionaliza as Aptidoes.
//-------------------------------------------------------------------Fim-----------------------------------------------------------------------//

//---------------------------------------------------------Calculando o melhor cromossomo------------------------------------------------------//
    melhor = Best(Apt);
    if(Fitness(PopReal[melhor][0], PopReal[melhor][1]) < Fitness(x1, x2)){ //Avalia se a melhor solução da geração é melhor
       melhor1 = melhor;                                                   //que a guardadae a atualiza caso isso ocorra.
       for(i = 0; i < TAMCADEIA; i++){
          solucao[i] = Populacao[melhor1][i];
       }
       x1 = PopReal[melhor1][0];
       x2 = PopReal[melhor1][1];
    }
    fprintf(arquivo,"%10.6f %10.6f %10.6f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento.
    /*Guardar a última iteração em que ocorreu mudança em x1 ou x2*/
    if (fit!=Fitness(x1,x2)){
      //printf("%.6f\t%6f\n",fit,Fitness(x1,x2));
      fit=Fitness(x1,x2);
      melhorCiclo=ciclo;
      tFim = clock(); //Finalizando e imprimindo o tempo de gasto para executar o programa
    }

    //fprintf(arquivo,"%10.6f\n", Fitness(x1, x2)); //Imprime a melhor solução até o momento.
//-------------------------------------------------------------------Fim-----------------------------------------------------------------------//

    ciclo++;
    }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Fim das Evolucoes++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

//Imprimindo o resultado final.
    //fprintf(arquivo,"\nResultado Final:\n");
    /*MEU COMENTÁRIO NA PRÓXIMA LINHA
    fprintf(arquivo,"%10.6f %10.6f %10.6f %5d\n", x1, x2, Fitness(x1, x2),melhorCiclo);
    */
}//-----------------------------------------------------Fim do Numero de corridas--------------------------------------------------------------//

//tFim = clock(); //Finalizando e imprimindo o tempo de gasto para executar o programa
/*imprimir para padrao do relatório TAMPOP TAM_CROMOSSOMO TAM_CADEIA N_EVOLUÇAO TAXA_CROSS TAXA_MUT X1 X2 FUNCAO TEMPO*/
fprintf(arq,"%2d %4d %4d %8d %2.3f %2.3f %10.6f %10.6f %10.6f %ld\n", TAMPOP,TAMCROM,TAMCADEIA, melhorCiclo,TXCO,TXMT,x1, x2, fit,tDecorrido = ((tFim - tInicio) / (CLOCKS_PER_SEC/1000)));
//fprintf(arquivo,"\nTempo de execucao: %ld milisegundos.\n",tDecorrido = ((tFim - tInicio) / (CLOCKS_PER_SEC/1000)));
fclose(arquivo); //Fechando o arquivo onde os dados foram gravados
fclose(arq);
//getchar();
return (0);
}
Ejemplo n.º 6
0
// Update our rendering scene. Note, that displaying is separated form
// the actual simulation process.
void SceneController::updateScene() {

	if (m_bInternalError)
		// something goes terribly wrong
		return;

	{ // synchronize scene mines objects with back-end ones
		int diff = vecMines.size() - gsMines.size();
		if (diff > 0) {
			for (int i = diff; i; --i)
				gsMines.push_back(gs->addPolygon(objectMine));
		}
		else if (diff < 0) {
			for (int i = diff; i; ++i) {
				delete gsMines.back();
				gsMines.pop_back();
			}
		}
	}

	{ // synchronize scene minesweeper objects with back-end ones
		int diff = vecSweepers.size() - gsSweepers.size();
		if (diff > 0) {
			for (int i = diff; i; --i)
				gsSweepers.push_back(gs->addPolygon(objectSweeper));
		}
		else if (diff < 0) {
		}
	}

	// update mine positions
	for (auto i = vecMines.size(); i; --i) {
		auto object = vecMines[i - 1];
		auto *item = gsMines[i - 1];
		item->setPos(object.x, object.y);
		item->setScale(MainWindow::s.dMineScale);
		item->setPen(gsMinePen);
	}

	// get the fitness score list and sort it in the descending order
	// in order to get the fitness threshold value for elite classification
	QVector<int> fitness;
	for (auto i = vecSweepers.size(); i; --i)
		fitness.push_back(vecSweepers[i - 1].Fitness());
	qSort(fitness.begin(), fitness.end(), qGreater<int>());
	int fitnessThreshold = fitness[MainWindow::s.iNumElite] + 1;

	// update minesweeper positions, rotations and colors
	for (auto i = vecSweepers.size(); i; --i) {
		auto object = vecSweepers[i - 1];
		auto *item = gsSweepers[i - 1];
		item->setPos(object.Position().x, object.Position().y);
		item->setRotation(object.Rotation() * 180 / M_PI);
		item->setScale(MainWindow::s.dSweeperScale);

		// we want the fittest displayed in a different color
		if (object.Fitness() >= fitnessThreshold)
			item->setPen(gsElitePen);
		else
			item->setPen(gsDefaultPen);
	}

	// update info statistics
	QString textGeneration = QString("Generation: %1 [TTL: %2]\n")
		.arg(m_iGenerations).arg(MainWindow::s.iNumTicks - m_iTicks);
	QString textFitness = QString("Fitness: best: %1, avge: %2\n")
		.arg(m_pGA->BestFitness()).arg(m_pGA->AverageFitness());
	QString textElite = QString("Elite threshold: %1\n").arg(fitnessThreshold);
	gsInfo->setText(textGeneration + textFitness + textElite);

}
Ejemplo n.º 7
0
int main()
{
	int icount = 0;  //指示
	int gencount = 0;
	int tim;   //指示TIME
	int res = 0;  //指示RESPONSE
	
	FILE *fp;
	fp = fopen("TimeSequence.txt","r+t");
	while(res < RESPONSE)
	{
		for(gencount = 0; gencount < GENENUM; gencount++)
		{
			for (tim = 0; tim < TIME; tim++)
		    {
				fscanf(fp, "%lf", &data[res][gencount][tim]);
		    }
		}
		res = res + 1;
	}
	fclose(fp);

	int flag = 0;
	srand((unsigned)time(NULL));  

	grpGA grp;
	pgrpGA pgrp = &grp;
	grp.generationCount = 0;
	grp.generationMax = 5000;  //遗传算法迭代次数
	grp.probCross = 0.9;     
	grp.probMutat = 0.1;    
	grp.size = SIZEGROUP;  //种群大小

	genGA ind[SIZEGROUP];
	pgenGA pind[SIZEGROUP];

	for(icount = 0; icount < SIZEGROUP; icount++)
	{
		pind[icount] = &ind[icount];
	}
	
	int u = 0;
	for(u = 0; u < GENENUM; u++)
	{
		printf("%d node learn\n", u);
		FILE *fp1;
		fp1 = fopen("Individuals.txt","r+t");
		icount = 0;
		while(icount < SIZEGROUP)
		{
			for (gencount = 0; gencount < GENENUM; gencount++)
			{
				fscanf(fp1, "%d", &populationMirror[icount][gencount]);
			}
			icount = icount + 1;
		}
		fclose(fp1);

		genExpect = 0;
		for(res = 0; res < RESPONSE; res++)
		{
			for(gencount = 0; gencount < GENENUM; gencount++)
			{
				genWigh[res][gencount] = 0;
			}
		}

		for(gencount = 0; gencount < GENENUM; gencount++)
		{
			genTest[gencount] = 0;
			genWighMean[gencount] = 0;
			elite[gencount] = 0;
			eliteWeight[gencount] = 0;
		}
	    
		eliteFitness = 0;

		do
		{
			Initial(pind);

			ErrorCmp(pind, data, populationMirror, genTest, genWigh, genWighMean, genExpect, &u);
			Fitness(pind);
			Optimal(pind, elite, &eliteFitness, populationMirror, genWighMean, eliteWeight);
			
			flag = Termination(pgrp);
			if(flag)
			{
				break;
			}

			BinaryTourment(pind, pgrp, populationMirror);
			Crossover(pind, pgrp, populationMirror);  
			Mutation(pind, pgrp, populationMirror); 
		
		}while(1);

		ResultOutput(pind, elite, pgrp, eliteWeight);
	}
	
	return 0;
}
Ejemplo n.º 8
0
int main (int argc, char* argv[]){

//Primero se debe definir un parser que lee desde la linea de comandos o un archivo
    eoParser parser(argc, argv);
//Se definen los parametros, se leen desde el parser y le asigna el valor
    //Datos necesarios del escenario de prueba
    double _min = parser.createParam((double)(0.0), "ValorMinimo", "Delimitacion area de trabajo",'M',"Parametros Escenario").value();
    double _max = parser.createParam((double)(20.0), "ValorMaximo", "Delimitacion area de trabajo",'S',"Parametros Escenario").value();
    unsigned int NoAnclas = parser.createParam((unsigned int)(10), "Anclas", "Numero de nodos anclas",'A',"Parametros Escenario").value();
    unsigned int nodos = parser.createParam((unsigned int)(100), "Nodos", "Total de nodos",'N',"Parametros Escenario").value();
    double radio = parser.createParam((double)(5), "Radio", "Radio de comunicacion",'R',"Parametros Escenario").value();

    double DisReal[200][200];
    double vecAnclas[NoAnclas*2];

//Configuracion parametros algoritmo
    unsigned int POP_SIZE = parser.createParam((unsigned int)(100), "PopSize", "Tamano de la poblacion",'P',"Parametros Algoritmo").value();
    unsigned int numberGeneration = parser.createParam((unsigned int)(1000), "MaxGen", "Criterio de parada, Numero maximo de generaciones",'G',"Parametros Algoritmo").value();
    unsigned int Nc = parser.createParam((unsigned int)(2), "Nc", "Constante del operador SBX",'C',"Parametros Algoritmo").value();
    double Pcruza = parser.createParam((double)(0.87), "Pcruza", "Probabilidad de cruzamiento SBX",'X',"Parametros Algoritmo").value();
    double Pmutation = parser.createParam((double)(0.85), "Pmutacion", "Probabilidad de mutacion de la encapsulacion de SVN y Swap",'Y',"Parametros Algoritmo").value();
    double Pmutation1 = parser.createParam((double)(0.85), "Pmutacion1", "Probabilidad de mutacion de SVN",'Z',"Parametros Algoritmo").value();
    double Pmutation2 = parser.createParam((double)(0.5), "Pmutacion2", "Probabilidad de mutacion de Swap",'W',"Parametros Algoritmo").value();
    double sizeTorneo = parser.createParam((double)(8), "SizeTorneo", "Tamano del torneo para seleccion de individuos",'L',"Parametros Algoritmo").value();
    double sizeElist = parser.createParam((double)(2), "SizeElist", "Cantidad de individuos que se conservan",'B',"Parametros Algoritmo").value();
    double sizeTorneo1 = parser.createParam((double)(2), "SizeTorneo1", "Tamano del torneo para seleccion de individuos del elitismo",'Q',"Parametros Algoritmo").value();

//Parametros de guardado
    unsigned int setGeneracion = parser.createParam((unsigned int)(100), "setGeneracion", "Cada cuantas generaciones se guarda la poblacion",'T',"Guardar Datos").value();
    unsigned int setTime = parser.createParam((unsigned int)(0), "setTime", "Cada cuantos segundos se guarda la configuracion",'I',"Guardar Datos").value();

//Grafica
    std::string InPut = parser.createParam(std::string("Estadistica.txt"), "Input", "Archivo que contiene el Fitness, Media, DevStand",'o',"Salida - Grafica").value();
    bool graficaGnuplot = parser.createParam((bool)(0), "Gnuplot", "Grafica el Fitness y Media, 0 desactivado y 1 activado",'g',"Salida - Grafica").value();

//Termina la ejecucion al consultar la ayuda
    if (parser.userNeedsHelp())
         {
             parser.printHelp(std::cout);
             exit(1);
         }
//Verifica el ingreso de las probabilidades
    if ( (Pcruza < 0) || (Pcruza > 1) ) throw std::runtime_error("Pcruza Invalido");
    if ( (Pmutation < 0) || (Pmutation > 1) ) throw std::runtime_error("Pmutation encapsulación Invalido");
    if ( (Pmutation1 < 0) || (Pmutation1 > 1) ) throw std::runtime_error("Pmutation de SVN Invalido");
    if ( (Pmutation2 < 0) || (Pmutation2 > 1) ) throw std::runtime_error("Pmutation de Swap Invalido");

//Parametro de tiempo
    struct timeval ti, tf;
    double tiempo;

/**CARGAR EL ESCENARIO**/
//Escenario
    //Lee desde archivo
    escenario *pEscenario = new escenario(nodos, NoAnclas);
    //Matriz de distancia
    for (int i=0; i<nodos ; i++)
        {for (int j=0; j<nodos; j++)DisReal[i][j] = pEscenario->obtenerDisRSSI(i,j);}
    //Posicion Nodos anclas
    for (int i=0 ; i<NoAnclas*2 ; i++)vecAnclas[i] = pEscenario->obtenerAnclas(i);

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

//Define la representación (Individuo)
    Individuo cromosoma;

//Para la inicialización del cromosoma, primero se debe definir como se generaran los genes
//Se utilizara un generador uniforme, (valor min, valor max)
    eoUniformGenerator<double> uGen(_min, _max);

//Crear el inicializador para los cromosomas, llamado random
    IndiInit random(nodos*2,uGen);

//Generar una subclase de la clase de la función de evaluación
    localizacionEvalPenal Fitness;

//Criterio de parada
    eoGenContinue<Individuo> parada(numberGeneration);

//Es otro criterio de parada en el cual se define el minimo de generaciones y cuantas generaciones sin mejoras
    //eoSteadyFitContinue<Individuo> parada(10,2);

/** CRUZA **/

    // Generar los limites para cada gen
    std::vector<double> min_b;
    std::vector<double> max_b;
    for(int i=0; i<nodos*2; i++) {
            min_b.push_back(_min);
            max_b.push_back(_max);
        }
    eoRealVectorBounds bounds(min_b, max_b);

    //Inicializar operador de cruce SBX
    individuoCruza crossover(bounds, Nc);

    //Cargar cantidad nodos anclas al operador
    crossover.setNoAnclas(NoAnclas);

/** MUTACION **/
    //Subclase de mutacion paper IEEE
    individuoMutacion mutationA(NoAnclas,numberGeneration,nodos,_min,_max);

    //Mutacion incluida en EO, permite llegar mas rapido a un fitness de 600
    individuoMutacion0 mutationB;

    //Combina operadores de mutacion con su respectivo peso
    eoPropCombinedMonOp<Individuo> mutation(mutationA,Pmutation1);
    mutation.add(mutationB, Pmutation2);

//Define un objeto de encapsulación (it contains, the crossover, the crossover rate, the mutation and the mutation rate) -> 1 line
    eoSGATransform<Individuo> encapsulacion(crossover, Pcruza, mutation, Pmutation); //0.87

//Define el método de selección, selecciona un individuo por cada torneo (en el parentesis se define el tamaño del torneo)
    eoDetTournamentSelect<Individuo> torneo(sizeTorneo);

//Define un "eoSelectPerc" con el torneo como parametro por defecto (permite seleccionar el mejor individuo)
    eoSelectPerc<Individuo> seleccion(torneo);

//Define una estrategia de reemplazo por cada generación
    //eoGenerationalReplacement<Individuo> reemplazo;

////Otra estrategia de reemplazo con elitismo
    eoElitism<Individuo> reemplazo(sizeElist,false); //antes 0.6

   //Para utilizar eoElitism se define un eoDetTournamentTruncate para seleccionar los individuos para el elitismo
        eoDetTournamentTruncate<Individuo> Trunca(sizeTorneo1);// antes 2

//Define una poblacion de Individuos
    eoPop<Individuo> poblacion;

//Cargar la matriz de distancias, cantidad nodos anclas y total de nodos
    Fitness.guardarDisReal(DisReal, NoAnclas, nodos, radio);

//Cargar posiciones nodos anclas
    Fitness.guardarAnclas(vecAnclas);

//Llena la población y evalua cada cromosoma
    for(int i=0 ; i<POP_SIZE ; i++)
    {
        random(cromosoma);
        Fitness(cromosoma);
        poblacion.push_back(cromosoma);
    }

//Imprime la población
    //poblacion.printOn(std::cout);

//Imprime un salto de linea
    std::cout<< std::endl;

//Contenedor de clases
    eoCheckPoint<Individuo> PuntoChequeo(parada);

//Cargar el valor de la generacion actual al operador de mutación
    //Se inicializa el contador de generaciones
    eoIncrementorParam<unsigned> generationCounter("Gen.");
    //Se carga el contador de generaciones al operador de mutación
    mutationA.setGen(& generationCounter);
    //Se carga el contador de generaciones al objeto eoCheckpoint para contar el número de generaciones
    PuntoChequeo.add(generationCounter);


/** Guardar datos de la población en archivos **/
    //Genera un archivo para guardar parametros
    eoState estado;
    //Guardar todo lo que necesites a la clase hija estado
    estado.registerObject(poblacion);
    //estado.registerObject(parser);
    //Guarda el tiempo de ejecucion desde la primera generacion
    eoTimeCounter time;
    PuntoChequeo.add(time);
    //Define cada cuantas generaciones se guarda la poblacion
    eoCountedStateSaver GuardarEstado(setGeneracion,estado,"generacion");
    //Siempre se debe agregar a la clase hija de eoCheckPoint para que se ejecute en cada generacion
    PuntoChequeo.add(GuardarEstado);

//Guardar algunas estadisticas de la poblacion
    //Muestra el mejor fitness de cada generación
    eoBestFitnessStat<Individuo> Elmejor("Mejor Fitness");
    //La media y stdev
    eoSecondMomentStats<Individuo> SegundoStat;
    //Se agrega al eoCheckPoint
    PuntoChequeo.add(Elmejor);
    PuntoChequeo.add(SegundoStat);
    // Guarda los parametros a un archivo
    eoFileMonitor fileMonitor("stats.xg", " ");
    PuntoChequeo.add(fileMonitor);
    fileMonitor.add(generationCounter); //Numero de generaciones
    fileMonitor.add(time);              //Tiempo total de ejecucion desde la primera generacion
    fileMonitor.add(Elmejor);           //Mejor fitness
    fileMonitor.add(SegundoStat);       //Media y desviacion estandar

///** Grafica **/
//    eoFileMonitor fileMonitor1(InPut, " ");
//    fileMonitor1.add(Elmejor);           //Mejor fitness
//    fileMonitor1.add(SegundoStat);       //Media y desviacion estandar
//    PuntoChequeo.add(fileMonitor1);      //Agrega al checkpoint
//    GnuplotMonitor grafica(InPut,graficaGnuplot);       //Grafica el fitness y la media
//    grafica.setGen(& generationCounter); //Carga la generacion
//    PuntoChequeo.add(grafica);
///**------------------------------------------**/

// Incializa el algoritmo genetico secuencial
    eoEasyEA<Individuo> algoritmo(PuntoChequeo, Fitness, seleccion, encapsulacion, reemplazo, Trunca);

//Tiempo inicial
    gettimeofday(&ti, NULL);

//Corre el algoritmo en la poblacion inicializada
    algoritmo(poblacion);

//Tiempo Final
    gettimeofday(&tf, NULL);

    std::cout << std::endl;

//Imprime el mejor cromosoma
    poblacion.best_element().printOn(std::cout);

    std::cout << std::endl;
    std::cout << std::endl;

//Imprime el tiempo de ejecución del algoritmo
    tiempo = (tf.tv_sec - ti.tv_sec)*1000 + (tf.tv_usec - ti.tv_usec)/1000.0;

    std::cout <<"Tiempo de ejecucion en milisegundos: " << tiempo << std::endl;

    std::cout << std::endl;
//Se grafica el error y todos los nodos
    std::string filename="generacion";
    graphError error(filename, setGeneracion, numberGeneration, nodos, NoAnclas, _max);

  std::cout << std::endl;
  return EXIT_SUCCESS;


}