コード例 #1
0
ファイル: gp.cpp プロジェクト: NFGream/embeddedGPU
void next_gen()
{
	char *parent1, *parent2;
	char new_gen[POP_SIZE][MAX_IND_LEN];
	int cntr = 0;

	for(int j=0; j<POP_SIZE; j++)
		for(int k=0; k<MAX_IND_LEN; k++)
			new_gen[j][k] = '*';

	for(int i=0; i<(int)POP_SIZE * CROSSOVER_RATE; i++)
	{
		parent1 = pop[tournament(2)];
		parent2 = pop[tournament(2)];
		cross_over(parent1, parent2, new_gen[cntr++]);
	}
	for(int i=0; i<(int)POP_SIZE * MUTATION_RATE; i++)
	{
		parent1 = pop[tournament(2)];
		mutate(parent1, new_gen[cntr++]);
	}
	for(int i=0; i<(int)POP_SIZE * REPRODUCT_RATE; i++)
	{
		parent1 = pop[tournament(2)];
		reproduct(parent1, new_gen[cntr++]);
	}
	for (int i=0; i<POP_SIZE; i++)
		for (int j=0; j<MAX_IND_LEN; j++)
			pop[i][j] = new_gen[i][j];
}
コード例 #2
0
ファイル: ga_alg.cpp プロジェクト: vcbin/stupidalgorithm
		// generate breeding pool with binary tournament
		void dgea_alg::tour_breed(const population& pop, population& new_pop)
		{
			int *a1, *a2;
			size_t i;
			individual parent1, parent2;
			size_t pop_size=m_ppara->get_pop_size();

			a1=new int[pop_size];
			a2=new int[pop_size];
			for(i=0; i<pop_size; ++i)
			{
				a1[i]=a2[i]=i;
			}
			random_shuffle(a1, a1+pop_size);
			random_shuffle(a2, a2+pop_size);

			for(i=0; i<pop_size; i += 4)
			{
				parent1=tournament(pop[a1[i]], pop[a1[i+1]]);
				parent2=tournament(pop[a1[i+2]], pop[a1[i+3]]);
				crossover(parent1, parent2, new_pop[i], new_pop[i+1]);
				parent1=tournament(pop[a1[i]], pop[a1[i+1]]);
				parent2=tournament(pop[a1[i+2]], pop[a1[i+3]]);
				crossover(parent1, parent2, new_pop[i+2], new_pop[i+3]);
			}

			delete[] a1;
			delete[] a2;

			return;
		}// end function selection
コード例 #3
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
void ClubController::removeIndex(int index)
{
    if(index < 0 || index >= tournament()->clubs().size())
        return;

    emit removedDataObj(tournament()->clubs().at(index));
    tournament()->clubs().removeAt(index);
}
コード例 #4
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
int ClubController::size() const
{
    if(!tournament())
    {
        return 0;
    }

    return tournament()->clubs().size();
}
コード例 #5
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
Club* ClubController::addClub(Club &club)
{
    if(!tournament())
        return 0;

    Club *newClub = new Club(club);
    tournament()->clubs().append(newClub);
    emit addedDataObj(newClub);

    return newClub;
}
コード例 #6
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
void ClubController::removeClub(int clubId)
{
    if(!tournament())
        return;

    Club *foundClub = findClub(clubId);
    if(foundClub)
    {
        tournament()->clubs().removeOne(foundClub);
        // May need to delete club which means signature of signal changes
        emit clubRemoved(foundClub);
    }
}
コード例 #7
0
ファイル: population.cpp プロジェクト: isaidhiptohop/ops_2015
Individual * Population::iterate (int iterations) {
    Individual * fittest = getFittest ();
    for (int i = 0; i < iterations; i++)
    {
        if (fittest->getFitness () == 0) {
            return fittest;
        } else {
            pop_stats.average_fitness.push_back (calcAvFitness (individuals, size));
            pop_stats.highest_fitness.push_back (fittest->getFitness ());
            
            Individual * winners = tournament ();
            mutation (winners);
            Individual * children = crossOver (winners);
            merge (winners, children);
            
            delete [] winners;
            delete [] children;
            
            calcFittest ();
            fittest = getFittest ();
        }
    }
    
    return fittest;
}
コード例 #8
0
ファイル: predictor.c プロジェクト: suhas18/240A_Proj1
// Make a prediction for conditional branch instruction at PC 'pc'
// Returning TAKEN indicates a prediction of taken; returning NOTTAKEN
// indicates a prediction of not taken
//
uint8_t
make_prediction(uint32_t pc)
{
    //
    //TODO: Implement prediction scheme
    //
    
    // Make a prediction based on the bpType
    switch (bpType) {
        case STATIC:
            return TAKEN;
            break;
        case GSHARE:
            return gshare(pc);
            break;
        case LOCAL:
        	return local(pc);
        	break;
        case TOURNAMENT:
        	return tournament(pc);
        	break;
        case CUSTOM:
        	return custom(pc);
        	break;
        default:
            break;
    }
    
    // If there is not a compatable bpType then return NOTTAKEN
    return NOTTAKEN;
}
コード例 #9
0
bool GAConjProblemForORGroupConjecture::isConj( int maxIter , int& doneIter )
{
  if( bestFit==NOCONJ )
    return false;

  theIter1 = doneIter;
  theIter2 = 0;

  for( ; bestFit!=0 && theIter1<=maxIter+doneIter ; ++theIter1, ++theIter2, ++lastImprovement ) {
    
    if( theIter1 % 100 == 0 && file ) 
      *file << "Generation " << theIter1 << ", best fitness " << bestFit << endl << endl;

    int imp = lastImprovement;

    int newGenes = reproduction( );
    for( int g=0 ; g<newGenes ; ++g )
      if( tournament( *newGene[g] ) )
	break;

    // if there was an improvement
    if( imp!=lastImprovement && lastImprovement==0 ) 
      maxIter += theIter2;
    
  }

  doneIter = theIter1;
  
  if( bestFit==0 ) return true;
  return false;  
}
コード例 #10
0
bool GAConjProblemForORGroupSolver::isConj( )
{
  if( bestFit==NOCONJ ) {
    if( conjProblem )
      *file << "Given words are not conjugate." << endl;
    else 
      *file << "The word is not trivial." << endl;
    return false;
  }

  theIter1 = 1 ;
  theIter2 = 0;

  for( ; bestFit!=0 ; ++theIter1, ++theIter2, ++lastImprovement ) {
    
    if( theIter1 % 100 == 0 && file ) 
      *file << "Generation " << theIter1 << ", best fitness " << bestFit << endl << endl;

    int newGenes = reproduction( );
    for( int g=0 ; g<newGenes ; ++g )
      if( tournament( *newGene[g] ) )
	break;

    checkImprovementTime( );
  }
  
  if( conjProblem )
    *file << "Given words are conjugate." << endl;
  else
    *file << "The given word is trivial." << endl;

  return true;
}
コード例 #11
0
ファイル: test.cpp プロジェクト: chenjunming/Test
int main()
{
	init();       //初始化 
	tournament(N);//求解
	print();      //打印结果
	endprogram(); //回收内存
	return 0;
}
コード例 #12
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
Club* ClubController::findClub(int id)
{
    Club* club = 0;

    if(!tournament())
        return club;

    for(int x = 0; x < tournament()->clubs().size() && !club; x++)
    {
        Club* temp = tournament()->clubs()[x];
        if(temp->id() == id)
        {
            club = temp;
        }
    }
    return club;
}
コード例 #13
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
void ClubController::add(int parentId)
{
    Q_UNUSED(parentId);

    if(!tournament())
        return;

    createClub();
}
コード例 #14
0
ファイル: tourselect.c プロジェクト: chiky123ser/nsga2
/* Routine for tournament selection, it creates a new_pop from old_pop by performing tournament selection and the crossover */
void selection (NSGA2Type *nsga2Params,  population *old_pop, population *new_pop)
{

    int *a1, *a2;
    int temp;
    int i;
    int rand;
    individual *parent1, *parent2;
    
    a1 = (int *)malloc(nsga2Params->popsize*sizeof(int));
    a2 = (int *)malloc(nsga2Params->popsize*sizeof(int));
    for (i=0; i<nsga2Params->popsize; i++)
    {
        a1[i] = a2[i] = i;
    }
    for (i=0; i<nsga2Params->popsize; i++)
    {
        rand = rnd (i, nsga2Params->popsize-1);
        temp = a1[rand];
        a1[rand] = a1[i];
        a1[i] = temp;
        rand = rnd (i, nsga2Params->popsize-1);
        temp = a2[rand];
        a2[rand] = a2[i];
        a2[i] = temp;
    }
    for (i=0; i<nsga2Params->popsize; i+=4)
    {
        parent1 = tournament (nsga2Params, &old_pop->ind[a1[i]], &old_pop->ind[a1[i+1]]);
        parent2 = tournament (nsga2Params, &old_pop->ind[a1[i+2]], &old_pop->ind[a1[i+3]]);
        crossover (nsga2Params, parent1, parent2, &new_pop->ind[i], &new_pop->ind[i+1]);
        parent1 = tournament (nsga2Params, &old_pop->ind[a2[i]], &old_pop->ind[a2[i+1]]);
        parent2 = tournament (nsga2Params, &old_pop->ind[a2[i+2]], &old_pop->ind[a2[i+3]]);
        crossover (nsga2Params, parent1, parent2, &new_pop->ind[i+2], &new_pop->ind[i+3]);
    }
    free (a1);
    free (a2);

     
    return;

}
コード例 #15
0
ファイル: test.cpp プロジェクト: chenjunming/Test
void tournament(int m)
{
	if (m == 1)
	{
		A[0][0] = 1;
		return;
	}
	else if (isodd(m))        //如果m为奇数,则m+1是偶数
	{
		tournament(m + 1);     //按照偶数个选手来求解
		replaceVirtual(m + 1); //然后把第m+1号虚选手置成0
		return;
	}
	else                     //m是偶数,
	{
		tournament(m / 2);     //则先安排第1组的m/2人比赛
		makecopy(m);         //然后根据算法,构造左下、右下、右上、右下的矩阵
	}
	return;
}
コード例 #16
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
int ClubController::findNextId()
{
    int nextId = 0;
    if(tournament())
    {
        foreach (Club* club, tournament()->clubs())
        {

            nextId = std::max(nextId, club->id());
        }
    }
コード例 #17
0
ファイル: tiny.c プロジェクト: Johnicholas/Hello-Github
int main()  
{
  int gen, indivs, offspring, parent1,  i, j;
  float *fitness = (float *) calloc( POPSIZE, sizeof(float));
  char **pop;
  scanf( "%ld%hd%hd", &seed, &varnumber, &fitnesscases);
  seed = seed ? (long) time( NULL ): seed;
  srand48(seed);
  if (varnumber > MAX_INPUTS || fitnesscases >= MAX_EXAMPLES ) 
    perror("var/example #");
  for (i = 0; i < fitnesscases; i ++ )
    for (j = 0; j <= varnumber; j++)
      scanf("%g",&(targets[i][j]));
  pop = create_random_pop(POPSIZE, DEPTH, fitness );
  printf("SEED=%ld\nMAXLEN=%d\nPSIZE=%d\nDEPTH=%d\nXOPROB=%g\nPMUT=%g\nGENS=%d\nTSIZE=%d",
 seed, MAX_LEN, POPSIZE, DEPTH, CROSSOVER_PROB, PMUT_PER_NODE, GENERATIONS, TSIZE );
  stats( fitness, pop, 0 );
  for ( gen = 1; gen < GENERATIONS; gen ++ )
    {
      if (  fitness[best] > -1e-5f ) 
	{
	  printf("\nOK\n");
	  exit( 0 );
	}
      for ( indivs = 0; indivs < POPSIZE; indivs ++ )
	{
	  parent1 = tournament( fitness, TSIZE,1 );
	  offspring = tournament( fitness, TSIZE,0 );
	  free( pop[offspring] );
	  pop[offspring] = drand48() > CROSSOVER_PROB ?
	    crossover( pop[parent1],pop[tournament( fitness, TSIZE,1 )] ) :
	    mutation( pop[parent1], PMUT_PER_NODE );
	  fitness[offspring] = fitness_function( pop[offspring] );
	}
      stats( fitness, pop, gen );
    }
  printf("\nNO\n");
  exit(1);
}
コード例 #18
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
Club *ClubController::findClubByName(QString name)
{
    if(!tournament())
        return 0;

    int firstSpace = name.indexOf(' ');
    if(firstSpace != -1)
    {
//        qDebug() << "Truncating (" << name << ")";
        name.truncate(firstSpace);
//        qDebug() << "Truncated Name is: (" << name << ")";
    }

    foreach(Club *club, tournament()->clubs())
    {
        if(club->clubName().startsWith(name, Qt::CaseInsensitive))
        {
            return club;
        }
    }

    return 0;
}
コード例 #19
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
void ClubController::updateClub(Club& club)
{
    if(!tournament())
        return;

    Club* foundClub = findClub(club.id());
    // Remove the old one and insert the new one?
    if(!foundClub)
    {
        return;
    }

    *foundClub = club;

    emit clubUpdated(foundClub);
}
コード例 #20
0
ファイル: allinone.cpp プロジェクト: isaidhiptohop/ops_2015
Individual<N> * Population<N>::iterate (int iterations) {
    for (int i = 0; i < iterations; i++) {
        Individual<N> * fittest = getFittest ();
        if (fittest) {
            return fittest;
        }
        else {
//            print ();
            if (OUTPUT) {
                std::cout << std::endl 
                          << "WHOLE POPULATION:" << std::endl;
            }
            getStats (individuals, size);
//            if (OUTPUT) print ();

            if (OUTPUT) std::cout << "WINNERS:" << std::endl;

            Individual<N> * winners = tournament ();

            getStats (winners, size/2);
//            if (OUTPUT) print (winners);

            mutation (winners);

            if (OUTPUT) std::cout << "WINNERS AFTER MUTATION:" << std::endl;
            getStats (winners, size/2);
//            if (OUTPUT) print (winners);
            
            if (OUTPUT) std::cout << "CHILDREN:" << std::endl;

            Individual<N> * children = crossOver (winners);

            getStats (children, size/2);
//            if (OUTPUT) print (children);
            
            merge (winners, children);

            return fittest;
        }
    }
    
    return nullptr;
}
コード例 #21
0
bool Population<N>::iterate (int iterations) {
    for (int i = 0; i < iterations; i++) {
        Individual<N> * fittest = getFittest ();
        if (fittest) {
            fittest->print ();
            return true;
        }
        else {
            print ();
            Individual<N> * winners = tournament ();
            mutation (winners);
            Individual<N> * children = crossOver (winners);
            merge (winners, children);
            return false;
        }
    }
    
    return false;
}
コード例 #22
0
 PopulationSPtr
 operator()(PopulationSPtr parent_pop)
 {
     std::vector<IndividualSPtr> a1, a2;
     for (int i = 0; i < parent_pop->populationSize(); ++i)
     {
         a1.push_back((*parent_pop)[i]);
         a2.push_back((*parent_pop)[i]);
     }
     
     std::shuffle(a2.begin(), a2.end(), random_number_gen);
     
     //Possible for a1[i] and a2[i] to be same indiviudal.
     PopulationSPtr child_pop(new Population);
     for (int i = 0; i < parent_pop->populationSize(); ++i)
     {
         child_pop->push_back(IndividualSPtr( new Individual(*(tournament(a1[i], a2[i])))));
     }
     
     return (child_pop);
 }
コード例 #23
0
ファイル: move.c プロジェクト: mplaton1/IPP
Move constructMoveCommand(int x, int y, Move result, board Game) {

    Piece piece = pieceOnPosition(Game, result->xFrom, result->yFrom);
    result->xTo = x;
    result->yTo = y;
    result->isPieceCreated = NULL;

    if (isPositionFree(Game, x, y)) {
        result->isPieceRemoved = NULL;
    }
    else {
        Piece piece1 = pieceOnPosition(Game, x, y);
        Piece winner = tournament(piece, piece1);
        result->isPieceRemoved = (winner != piece) ? piece : piece1;
        if (winner == NULL) {
            result->isPieceRemoved = piece1;
        }
    }

    return result;
}
コード例 #24
0
ファイル: epsmoea.c プロジェクト: koparasy/genetic_algorithms
int main (int argc, char **argv)
{
    int i;
    int index, index1, index2;
    FILE *fpt1;
    FILE *fpt2;
    FILE *fpt3;
    FILE *fpt4;
    FILE *fpt5;
    individual *ea;
    individual *parent1, *parent2, *child1, *child2;
    ind_list *elite, *cur;
    if (argc<2)
    {
        printf("\n Usage ./main random_seed \n");
        exit(1);
    }
    seed = (double)atof(argv[1]);
    if (seed<=0.0 || seed>=1.0)
    {
        printf("\n Entered seed value is wrong, seed value must be in (0,1) \n");
        exit(1);
    }
    fpt1 = fopen("initial_pop.out","w");
    fpt2 = fopen("final_pop.out","w");
    fpt3 = fopen("final_archive.out","w");
    fpt4 = fopen("all_archive.out","w");
    fpt5 = fopen("params.out","w");
    fprintf(fpt1,"# This file contains the data of initial population\n");
    fprintf(fpt2,"# This file contains the data of final population\n");
    fprintf(fpt3,"# This file contains the best obtained solution(s)\n");
    fprintf(fpt4,"# This file contains the data of archive for all generations\n");
    fprintf(fpt5,"# This file contains information about inputs as read by the program\n");
    printf("\n Enter the problem relevant and algorithm relevant parameters ... ");
    printf("\n Enter the population size (>1) : ");
    scanf("%d",&popsize);
    if (popsize<2)
    {
        printf("\n population size read is : %d",popsize);
        printf("\n Wrong population size entered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of function evaluations : ");
    scanf("%d",&neval);
    if (neval<popsize)
    {
        printf("\n number of function evaluations read is : %d",neval);
        printf("\n Wrong nuber of evaluations entered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of objectives (>=2): ");
    scanf("%d",&nobj);
    if (nobj<2)
    {
        printf("\n number of objectives entered is : %d",nobj);
        printf("\n Wrong number of objectives entered, hence exiting \n");
        exit (1);
    }
    epsilon = (double *)malloc(nobj*sizeof(double));
    min_obj = (double *)malloc(nobj*sizeof(double));
    for (i=0; i<nobj; i++)
    {
        printf("\n Enter the value of epsilon[%d] : ",i+1);
        scanf("%lf",&epsilon[i]);
        if (epsilon[i]<=0.0)
        {
            printf("\n Entered value of epsilon[%d] is non-positive, hence exiting\n",i+1);
            exit(1);
        }
        printf("\n Enter the value of min_obj[%d] (if not known, enter 0.0) : ",i+1);
        scanf("%lf",&min_obj[i]);
    }
    printf("\n Enter the number of constraints : ");
    scanf("%d",&ncon);
    if (ncon<0)
    {
        printf("\n number of constraints entered is : %d",ncon);
        printf("\n Wrong number of constraints enetered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of real variables : ");
    scanf("%d",&nreal);
    if (nreal<0)
    {
        printf("\n number of real variables entered is : %d",nreal);
        printf("\n Wrong number of variables entered, hence exiting \n");
        exit (1);
    }
    if (nreal != 0)
    {
        min_realvar = (double *)malloc(nreal*sizeof(double));
        max_realvar = (double *)malloc(nreal*sizeof(double));
        for (i=0; i<nreal; i++)
        {
            printf ("\n Enter the lower limit of real variable %d : ",i+1);
            scanf ("%lf",&min_realvar[i]);
            printf ("\n Enter the upper limit of real variable %d : ",i+1);
            scanf ("%lf",&max_realvar[i]);
            if (max_realvar[i] <= min_realvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of real variable %d, hence exiting \n",i+1);
                exit(1);
            }
        }
        printf ("\n Enter the probability of crossover of real variable (0.6-1.0) : ");
        scanf ("%lf",&pcross_real);
        if (pcross_real<0.0 || pcross_real>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_real);
            printf("\n Entered value of probability of crossover of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the probablity of mutation of real variables (1/nreal) : ");
        scanf ("%lf",&pmut_real);
        if (pmut_real<0.0 || pmut_real>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_real);
            printf("\n Entered value of probability of mutation of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the value of distribution index for crossover (5-20): ");
        scanf ("%lf",&eta_c);
        if (eta_c<=0)
        {
            printf("\n The value entered is : %e",eta_c);
            printf("\n Wrong value of distribution index for crossover entered, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the value of distribution index for mutation (5-50): ");
        scanf ("%lf",&eta_m);
        if (eta_m<=0)
        {
            printf("\n The value entered is : %e",eta_m);
            printf("\n Wrong value of distribution index for mutation entered, hence exiting \n");
            exit (1);
        }
    }
    printf("\n Enter the number of binary variables : ");
    scanf("%d",&nbin);
    if (nbin<0)
    {
        printf ("\n number of binary variables entered is : %d",nbin);
        printf ("\n Wrong number of binary variables entered, hence exiting \n");
        exit(1);
    }
    if (nbin != 0)
    {
        nbits = (int *)malloc(nbin*sizeof(int));
        min_binvar = (double *)malloc(nbin*sizeof(double));
        max_binvar = (double *)malloc(nbin*sizeof(double));
        for (i=0; i<nbin; i++)
        {
            printf ("\n Enter the number of bits for binary variable %d : ",i+1);
            scanf ("%d",&nbits[i]);
            if (nbits[i] < 1)
            {
                printf("\n Wrong number of bits for binary variable entered, hence exiting");
                exit(1);
            }
            printf ("\n Enter the lower limit of binary variable %d : ",i+1);
            scanf ("%lf",&min_binvar[i]);
            printf ("\n Enter the upper limit of binary variable %d : ",i+1);
            scanf ("%lf",&max_binvar[i]);
            if (max_binvar[i] <= min_binvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of binary variable entered, hence exiting \n");
                exit(1);
            }
        }
        printf ("\n Enter the probability of crossover of binary variable (0.6-1.0): ");
        scanf ("%lf",&pcross_bin);
        if (pcross_bin<0.0 || pcross_bin>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_bin);
            printf("\n Entered value of probability of crossover of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the probability of mutation of binary variables (1/nbits): ");
        scanf ("%lf",&pmut_bin);
        if (pmut_bin<0.0 || pmut_bin>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_bin);
            printf("\n Entered value of probability  of mutation of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
    }
    if (nreal==0 && nbin==0)
    {
        printf("\n Number of real as well as binary variables, both are zero, hence exiting \n");
        exit(1);
    }
    printf("\n Input data successfully entered, now performing initialization \n");
    fprintf(fpt5,"\n Population size = %d",popsize);
    fprintf(fpt5,"\n Number of function evaluations = %d",neval);
    fprintf(fpt5,"\n Number of objective functions = %d",nobj);
    for (i=0; i<nobj; i++)
    {
        fprintf(fpt5,"\n Epsilon for objective %d = %e",i+1,epsilon[i]);
        fprintf(fpt5,"\n Minimum value of objective %d = %e",i+1,min_obj[i]);
    }
    fprintf(fpt5,"\n Number of constraints = %d",ncon);
    fprintf(fpt5,"\n Number of real variables = %d",nreal);
    if (nreal!=0)
    {
        for (i=0; i<nreal; i++)
        {
            fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
            fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
        fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
        fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
        fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
    }
    fprintf(fpt5,"\n Number of binary variables = %d",nbin);
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
            fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
            fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
        fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
    }
    fprintf(fpt5,"\n Seed for random number generator = %e",seed);
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;
    currenteval = 0;
    elite_size = 0;
    randomize();
    ea = (individual *)malloc(popsize*sizeof(individual));
    array = (int *)malloc(popsize*sizeof(int));
    for (i=0; i<popsize; i++)
    {
        allocate (&ea[i]);
        initialize(&ea[i]);
        decode(&ea[i]);
        eval(&ea[i]);
    }
    report_pop (ea, fpt1);
    elite = (ind_list *)malloc(sizeof(ind_list));
    elite->ind = (individual *)malloc(sizeof(individual));
    allocate (elite->ind);
    elite->parent = NULL;
    elite->child = NULL;
    insert (elite, &ea[0]);
    for (i=1; i<popsize; i++)
    {
        update_elite (elite, &ea[i]);
    }
    child1 = (individual *)malloc(sizeof(individual));
    allocate (child1);
    child2 = (individual *)malloc(sizeof(individual));
    allocate (child2);
    cur = elite;
    while (currenteval<neval)
    {
        index1 = rnd(0, popsize-1);
        index2 = rnd(0, popsize-1);
        parent1 = tournament (&ea[index1], &ea[index2]);
        index = rnd(0, elite_size-1);
        cur = elite->child;
        for (i=1; i<=index; i++)
        {
            cur=cur->child;
        }
        parent2 = cur->ind;
        crossover (parent1, parent2, child1, child2);
        mutation (child1);
        decode (child1);
        eval (child1);
        update_elite (elite, child1);
        update_pop (ea, child1);
        mutation (child2);
        decode (child2);
        eval (child2);
        update_elite (elite, child2);
        update_pop (ea, child2);
        printf("\n Currenteval = %d and Elite_size = %d",currenteval,elite_size); 
		/* Comment following three lines if information at all
		evaluation is not desired, it will speed up execution of the code */
	fprintf(fpt4,"# eval id = %d\n",currenteval);
		report_archive (elite, fpt4);
		fflush(fpt4);
    }
    printf("\n Generations finished, now reporting solutions");
    report_pop (ea, fpt2);
    report_archive (elite, fpt3);
    if (nreal!=0)
    {
        fprintf(fpt5,"\n Number of crossover of real variable = %d",nrealcross);
        fprintf(fpt5,"\n Number of mutation of real variable = %d",nrealmut);
    }
    if (nbin!=0)
    {
        fprintf(fpt5,"\n Number of crossover of binary variable = %d",nbincross);
        fprintf(fpt5,"\n Number of mutation of binary variable = %d",nbinmut);
    }
    fflush(stdout);
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    fclose(fpt1);
    fclose(fpt2);
    fclose(fpt3);
    fclose(fpt4);
    fclose(fpt5);
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    free (epsilon);
    free (min_obj);
    free (array);
    for (i=0; i<popsize; i++)
    {
        deallocate (&ea[i]);
    }
    free (ea);
    cur = elite->child;
    while (cur!=NULL)
    {
        cur = del(cur);
        cur = cur->child;
    }
    deallocate (elite->ind);
    free (elite->ind);
    free (elite);
    printf("\n Routine successfully exited \n");
    return (0);
}
コード例 #25
0
ファイル: GAFeedForwardNN.cpp プロジェクト: zubekj/libcudann
//run the genetic algorithm initialized before with some training parameters:
//training location, training algorithm, desired error, max_epochs, epochs_between_reports
//see "FeedForwardNNTrainer" class for more details
//printtype specifies how much verbose will be the execution (PRINT_ALL,PRINT_MIN,PRINT_OFF)
void GAFeedForwardNN::evolve(const int n, const float * params, const int printtype){

	if(n<5){printf("TOO FEW PARAMETERS FOR TRAINING\n");exit(1);}
	int layers[nhidlayers+2];
	int functs[nhidlayers+2];
	float learningRate;

	float fitnesses[popsize];
	float totfitness=0;
	float bestFitnessEver=0;
	FloatChromosome newpop[popsize];

	layers[0]=trainingSet->getNumOfInputsPerInstance();
	layers[nhidlayers+1]=trainingSet->getNumOfOutputsPerInstance();

	//for each generation
	for(int gen=0;gen<generations;gen++){
		float bestFitnessGeneration=0;
		int bestFitGenIndex=0;
		totfitness=0;

		printf("GENERATION NUMBER:\t%d\n\n",gen);

		//fitness evaluation of each individual
		for(int i=0;i<popsize;i++){

			printf("\nINDIVIDUAL N:\t%d\n",i);

			//decode the chromosome hidden layers sizes
			for(int j=0;j<nhidlayers;j++){
				layers[j+1]=chromosomes[i].getElement(j);
			}
			//decode the chromosome activation functions for each layer
			for(int j=0;j<nhidlayers+2;j++){
				functs[j]=chromosomes[i].getElement(j+nhidlayers);
			}
			//decode the chromosome learning rate
			learningRate=chromosomes[i].getElement(nhidlayers+nhidlayers+2);

			float medium=0;

			FeedForwardNN mseT;

			//do a number of evaluations with different weights and average the results
			for(int n=0;n<numberofevaluations;n++){

				//choose what to print based on user's choice
				int print=PRINT_ALL;
				if(printtype==PRINT_MIN){
					if(n==0)
						print=PRINT_MIN;
					else
						print=PRINT_OFF;
				}
				if(printtype==PRINT_OFF)
					print=PRINT_OFF;

				//decode the chromosome into a real network
				FeedForwardNN net(nhidlayers+2,layers,functs);

				FeedForwardNNTrainer trainer;
				trainer.selectTrainingSet(*trainingSet);
				if(testSet!=NULL){
					trainer.selectTestSet(*testSet);
				}
				trainer.selectNet(net);

				trainer.selectBestMSETestNet(mseT);

				float par[]={params[0],params[1],params[2],params[3],params[4],learningRate,0,SHUFFLE_ON,ERROR_LINEAR};

				//do the training of the net and evaluate is MSE error
				medium+=trainer.train(9,par,print)/float(numberofevaluations);
			}

			//the fitness is computed as the inverse of the MSE
			fitnesses[i]=1.0f/medium;

			printf("FITNESS:\t%.2f\n\n",fitnesses[i]);

			//updates the best individual of the generation
			if(fitnesses[i]>bestFitnessGeneration){bestFitnessGeneration=fitnesses[i];bestFitGenIndex=i;}

			//if this is the best fitness ever it store the network in bestNet
			if(bestNet!=NULL)
			if(fitnesses[i]>bestFitnessEver){*bestNet=mseT;bestFitnessEver=fitnesses[i];}

			totfitness+=fitnesses[i];
		}

		//the best individual is always carried to the next generation
		newpop[0]=chromosomes[bestFitGenIndex];

		//generate the new population
		for(int i=1;i<popsize;i++){
			//selection
			int firstmate=0,secondmate=0;

			//first mate
			switch(selectionalgorithm){
				case ROULETTE_WHEEL:		firstmate=rouletteWheel(popsize,fitnesses);					break;
				case TOURNAMENT_SELECTION:	firstmate=tournament(popsize,fitnesses,popsize/5+1);		break;
				default:					printf("SELECTION ALGORITHM NOT IMPLEMENTED YET\n");exit(1);break;
			}
			//second mate
			do{
				switch(selectionalgorithm){
					case ROULETTE_WHEEL:		secondmate=rouletteWheel(popsize,fitnesses);				break;
					case TOURNAMENT_SELECTION:	secondmate=tournament(popsize,fitnesses,popsize/5+1);		break;
					default:					printf("SELECTION ALGORITHM NOT IMPLEMENTED YET\n");exit(1);break;
				}
			}while(firstmate==secondmate);


			FloatChromosome child;
			//do the crossover
			child=crossover(chromosomes[firstmate],chromosomes[secondmate],pcross);
			//and the mutation
			child=mutation(child,pmut,maxdimhiddenlayers,nhidlayers);
			//and put the child in the new generation
			newpop[i]=child;
		}

		//copy the new generation over the older one, wich is the one we will still use
		for(int i=0;i<popsize;i++){
			chromosomes[i]=newpop[i];
		}
	}

}
コード例 #26
0
ファイル: prog4.c プロジェクト: vteori/CSED101
//3번을 선택하였을 경우
void menu3(char champion[]/*우승팀*/)
{
	FILE *file; //파일 포인터
	int winLost[2][4]/*경기 결과*/, number[4]/*임시저장*/, i, j/*루프용 변수*/;
	char fileName[20]/*파일이름*/, mark = 'A'/*파일이름에서 다른 부분*/, result[] = "_Result.txt"/*파일이름에서 같은 부분*/;
	char sixteen[16][20]/*16강 진출국*/, eight[8][20]/*8강 진출국*/, semi[4][20]/*4강 진출국*/, final[2][20]/*결승 진출국*/;
	//16강 진출국 불러오기
	i = 0;
	while(1){
		//파일이름 만들기
		fileName[0] = mark;
		fileName[1] = '\0';
		strcat(fileName, result);
		//data불러오기
		file = fopen(fileName, "r");
		fscanf(file, "%s", sixteen[i]); //A, C, E, G조 1위
		for(j = 0 ; j < 4 ; j++){
			fscanf(file, "%d", &number[j]);
		}
		fscanf(file, "%s", sixteen[i+2]); //A, C, E, G조 2위
		fclose(file); //파일 닫기

		mark++; //파일 이름 변환
		fileName[0] = mark;
		fileName[1] = '\0';
		strcat(fileName, result);

		file = fopen(fileName, "r");
		fscanf(file, "%s", sixteen[i+3]); //B, D, F, H조 1위
		for(j = 0 ; j < 4 ; j++){
			fscanf(file, "%d", &number[j]);
		}
		fscanf(file, "%s", sixteen[i+1]); //B, D, F, H조 2위
		fclose(file); //파일 닫기

		mark++;
		i += 4;

		if(mark > 72) break;
	}
	//16강
	i = 0;
	j = 0;
	file = fopen("tournament_result.txt", "w"); //파일열기
	fprintf(file, "16강\n");
	while(j < 8){
		//토너먼트 진행 함수 호출
		tournament(sixteen[i], sixteen[i+1], winLost);
		//앞팀이 이겼을 때
		if(winLost[0][0] == 1){
			strcpy(eight[j], sixteen[i]); //8강 진출팀 저장
			fprintf(file, "%20s%-20c%s\n", sixteen[i], '*', sixteen[i+1]); //경기 결과 파일로 출력
		}
		//뒤팀이 이겼을 때
		else{
			strcpy(eight[j], sixteen[i+1]); //8강 진출팀 저장
			fprintf(file, "%20s%20c%s\n", sixteen[i], '*', sixteen[i+1]); 
		}
		i += 2;
		j++;
	}
	fclose(file);
	//8강
	i = 0;
	j = 0;
	file = fopen("tournament_result.txt", "a");
	fprintf(file, "\n8강\n");
	while(j < 4){
		tournament(eight[i], eight[i+1], winLost);
		if(winLost[0][0] == 1){
			strcpy(semi[j], eight[i]); //4강 진출팀 저장
			fprintf(file, "%20s%-20c%s\n", eight[i], '*', eight[i+1]);
		}
		else{
			strcpy(semi[j], eight[i+1]); //4강 진출팀 저장
			fprintf(file, "%20s%20c%s\n", eight[i], '*',  eight[i+1]);
		}
		i += 2;
		j++;
	}
	fclose(file);
	//4강
	i = 0;
	j = 0;
	file = fopen("tournament_result.txt", "a");
	fprintf(file, "\n4강\n");
	while(j < 2){
		tournament(semi[i], semi[i+1], winLost);
		if(winLost[0][0] == 1){
			strcpy(final[j], semi[i]); //결승 진출팀 저장
			fprintf(file, "%20s%-20c%s\n", semi[i], '*', semi[i+1]);
		}
		else{
コード例 #27
0
ファイル: ClubController.cpp プロジェクト: gcdean/JudoMaster
const QList<Club *> *ClubController::clubs() const
{
    if(!tournament())
        return &NOCLUBS;
    return &tournament()->clubs();
}
コード例 #28
0
void Simulation::execute()
{
	// some safety & sanity checks
	if (teams.empty())
	{
		throw "No teams are active. Aborting the tournament.";
	}
	if (rules.empty())
	{
		throw "No rules are active. Aborting the tournament.";
	}

	// 16 threads for one tournament sound impractical
	int realThreadCount = std::min(numberOfThreads, numberOfRuns);

	std::vector<std::thread> threads;
	threads.resize(realThreadCount);
	tournaments.resize(realThreadCount);

	int remainingRuns = numberOfRuns;
	int runsPerThread = numberOfRuns / realThreadCount;

	for (int i = 0; i < realThreadCount; ++i, remainingRuns -= runsPerThread)
	{
		int runsForTournament = std::min(remainingRuns, runsPerThread);
		// make sure that there are no remaining runs that don't get distributed
		// example: 20 runs and 8 threads, runs per thread = 2, only 2*8=16 tournaments would be started
		if (i == realThreadCount - 1)
			runsForTournament = remainingRuns;

		tournaments[i] = Tournament::newOfType(tournamentType, this, runsForTournament);
		tournaments[i]->doSanityChecks(); // allow the tournament some checking prior to the launch
		threads[i] = std::thread(&Tournament::start, tournaments[i]);
	}
	
	// wait for the simulation to finish
	for (auto &thread : threads)
	{
		thread.join();
	}

	// setup rank data
	{ // scope
		std::unique_ptr<Tournament> tournament(Tournament::newOfType(tournamentType, this, 0));
		for (RankData const & rank : tournament->getRankDataAssignment())
			ranks.push_back(rank);
	}

	// and then join the results
	for (Tournament* &tournament : tournaments)
	{
		// first the team data
		for (auto &clusterToMerge : tournament->clusterTeamResults)
		{
			std::map<int, TeamResult> &cluster = clusterTeamResults[clusterToMerge.first];

			for (auto &team : teams)
			{
				if (!cluster.count(team.id))
					cluster.emplace(std::make_pair(team.id, TeamResult(clusterToMerge.second[team.id])));
				else
					cluster[team.id].merge(clusterToMerge.second[team.id]);
			}
		}

		// and then the match cluster statistics
		for (auto &clusterToMerge : tournament->clusterMatchResultStatisticsLists)
		{
			clusterMatchResultStatisticsLists[clusterToMerge.first].merge(clusterToMerge.second);
		}
	}
}
コード例 #29
0
ファイル: selector.cpp プロジェクト: Windsdon/evolutive
int main(int argc, char **argv) {
	srand(time(0));

	int popNum;
	int indCount;

	fstream simdata;
	simdata.open("simdata.txt");
	simdata >> popNum >> indCount;
	simdata.close();

	cout << "População: " << popNum << endl;
	cout << "Numero de individuos: " << indCount << endl;

	stringstream popOutName;

	popOutName << "popstat." << setw(5) << setfill('0') << popNum << ".txt";

	simdata.open("simdata.txt");
	simdata << (popNum + 1) << ' ' << indCount;
	simdata.close();

	vector<guy> pop;
	map<string, guy> popmap;

	ifstream read;
	read.open("stats.txt");

	Robot r(nullptr, nullptr, nullptr);

	map<string, RobotDescriptor*> descs;

	do {
		string id;
		double score;
		int stall;
		double duration;

		read >> id >> score >> stall >> duration;

		if (!id.length()) {
			break;
		}

		guy g;
		g.id = id;
		g.score = score;

		pop.push_back(g);

		popmap.insert(pair<string, guy>(g.id, g));

		RobotDescriptor *descriptor = new RobotDescriptor();

		stringstream fileName;
		fileName << "robots/desc" << id;

		cout << "READING FILE " << fileName.str() << endl;
		ifstream inputFile;
		inputFile.open(fileName.str());
		descriptor->loadFromFile(inputFile, &r);
		inputFile.close();

		descs.insert(pair<string, RobotDescriptor*>(id, descriptor));
	} while (!read.eof());

	sort(pop.begin(), pop.end());

	ofstream popOut;
	popOut.open(popOutName.str());

	map<string, RobotDescriptor*> newPop;

	vector<guy> newpop;
	map<string, guy> mapunique;
	while (newpop.size() != indCount) {
		vector<string> killed;
		vector<string> chosen;
		tournament(pop, 0, pop.size() - 1, SIZE, chosen, killed);

		newpop.push_back(popmap[chosen[0]]);
		mapunique.insert(pair<string, guy>(chosen[0], popmap[chosen[0]]));
	}

	vector<guy> popunique;

	for (map<string, guy>::iterator it = mapunique.begin();
			it != mapunique.end(); ++it) {
		popunique.push_back(it->second);
	}

	sort(newpop.begin(), newpop.end());
	sort(popunique.begin(), popunique.end());

	vector<double> divs;
	vector<double> oldPopScores;
	vector<double> newPopScores;
	vector<double> newPopScoresUnique;

	for (int i = 0; i < 400; i += 10) {
		divs.push_back(i);
	}

	for (int i = 0; i < pop.size(); i++) {
		oldPopScores.push_back(pop[i].score);
	}

	for (int i = 0; i < newpop.size(); i++) {
		newPopScores.push_back(newpop[i].score);
	}

	for (int i = 0; i < popunique.size(); i++) {
		newPopScoresUnique.push_back(popunique[i].score);
	}

	vector<int> oldPopStats = generateHistogram(divs, oldPopScores);
	vector<int> newPopStats = generateHistogram(divs, newPopScores);
	vector<int> newPopStatsUnique = generateHistogram(divs, newPopScoresUnique);

	popOut << newpop.size() << " chosen, " << popunique.size() << " unique\n";
	popOut << "range\told\tnew\tunique\n";

	for (int i = 0; i < divs.size(); i++) {
		popOut << divs[i] << '\t' << oldPopStats[i] << '\t' << newPopStats[i]
				<< '\t' << newPopStatsUnique[i] << '\n';
	}

	for (int i = 0; i < pop.size(); i++) {
		popOut << pop[i].score << "\t" << pop[i].id << '\n';
	}

	for (int j = 0; j < SURVIVAL_RATE * popunique.size(); j++) {
		string id = popunique[j].id;
		popOut << id << " survived\n";
		cout << "choosing " << id << ", score: " << popunique[j].score << endl;
		newPop.insert(pair<string, RobotDescriptor*>(id, descs[id]));
	}

	popOut.close();

	cout << endl;

	if (argc > 1) {
		return 0;
	}

	ofstream output;
	output.open("generated.txt");
	
	int ammountCross = TAXA_CROSS * (indCount - newPop.size());

	for (int i = 0; i < ammountCross; i++) {
		string parent1 = popunique[rand() % (popunique.size())].id;
		string parent2 = popunique[rand() % (popunique.size())].id;
		RobotDescriptor *p1 = descs[parent1];
		RobotDescriptor *p2 = descs[parent2];

		double point = (rand() % 10) / 10.0;

		if (p1->behaviours.size() < 3 || p2->behaviours.size() < 3) {
			continue;
		}

		RobotDescriptor *ind = new RobotDescriptor();

		int cut1 = std::min(std::max(1, (int) (point * p1->behaviours.size())),
				(int) p1->behaviours.size() - 2);
		int cut2 = std::min(std::max(1, (int) (point * p2->behaviours.size())),
				(int) p2->behaviours.size() - 2);

		//@bug Referência ao descritor pai é mantida!
		for (int i = 0; i < cut1; i++) {
			ind->addBehavior(p1->behaviours[i]);
		}
		for (int i = cut2; i < p2->behaviours.size(); i++) {
			ind->addBehavior(p2->behaviours[i]);
		}
	}

	//Mutação!
	int k = 0;
	while (newPop.size() < indCount) {
		string parentID = popunique[rand() % (popunique.size())].id;
		RobotDescriptor *parent = descs[parentID];
		RobotDescriptor *ind = new RobotDescriptor();

		stringstream fileName;
		fileName << "robots/desc" << parentID;
		ifstream inParent;
		inParent.open(fileName.str());
		ind->loadFromFile(inParent, nullptr);
		inParent.close();

		for (int i = 0; i < ind->behaviours.size(); i++) {
			BehaviourOnObstacleDistance *b =
					static_cast<BehaviourOnObstacleDistance*>(ind->behaviours[i]);
			if (rand() % 100 <= 5) {
				b->angle += rand()%5 - 2;
				b->angle = std::min(std::max(b->angle, 360.0), 0.0);
			}
			if (rand() % 100 <= 5) {
				b->distanceMax += (rand() % 20) / 100.0 - 0.1;
			}
			if (rand() % 100 <= 5) {
				b->distanceMin += (rand() % 20) / 100.0 - 0.1;
			}

			for (int j = 0; j < b->actions.size(); j++) {
				Action *a = b->actions[j];

				if (rand() % 100 <= 5) {
					a->duration += (rand() % 20) / 100.0 - 0.1;
				}
				if (rand() % 100 <= 5) {
					a->duration = std::max(0.0, a->duration);
				}

				if (rand() % 100 <= 5) {
					a->value += (rand() % 20) / 100.0 - 0.1;
				}
			}

			if (!(rand() % 100)) {
				Action *a;
				if (rand() % 2) {
					a = new Action(ACTION_LINEAR_VEL, (rand() % 100) / 100.0,
							(rand() % 100) / 100.0);
				} else {
					a = new Action(ACTION_ANGULAR_VEL,
							(rand() % 200) / 100.0 - 1, (rand() % 100) / 100.0);
				}

				b->addAction(a);
			}
		}

		if (!(rand() % 100)) {
			double minDist = (rand() % 100) / 100.0;
			Behaviour *b = new BehaviourOnObstacleDistance(nullptr,
					rand() % 360, minDist, minDist + (rand() % 400) / 100.0);

			Action *act;
			if (rand() % 2) {
				act = new Action(ACTION_LINEAR_VEL, (rand() % 100) / 100.0,
						(rand() % 100) / 100.0);
			} else {
				act = new Action(ACTION_ANGULAR_VEL, (rand() % 200) / 100.0 - 1,
						(rand() % 100) / 100.0);
			}

			b->addAction(act);
		}

		stringstream generatedID;
		generatedID << setw(5) << setfill('0') << popNum << '.' << setw(5)
				<< setfill('0') << k;

		cout << "New ID: " << generatedID.str() << endl;

		stringstream generatedFile;
		generatedFile << "robots/desc" << generatedID.str();

		cout << "New File: " << generatedFile.str() << endl;

		ofstream saveFile;
		saveFile.open(generatedFile.str());
		ind->saveToFile(saveFile);
		saveFile.close();

		newPop.insert(pair<string, RobotDescriptor*>(generatedID.str(), ind));

		k++;

	}

	for (map<string, RobotDescriptor*>::iterator it = newPop.begin();
			it != newPop.end(); ++it) {
		output << it->first << '\n';
	}

	output.close();

	return 0;
}
コード例 #30
0
ファイル: NSGA2.cpp プロジェクト: charlyisidore/BiCFLPv2013
void  evolution (EfficientSolution & efficient_population, 
		 std::vector <Solution*> &population, 
		 std::vector <Solution*> &offspring_population, 
		 double P_c, 
		 double P_m,
		 Data & data)
{

  unsigned int population_size = population.size();
  unsigned int numberOfFacility = data.getnbFacility();
  unsigned int numberOfCustomers = data.getnbCustomer();
  
  while(offspring_population.size() < population_size)
    {
      // tournament n°1    
      Solution* father1 = population[randAB(0, population_size-1)];
      Solution* father2 = population[randAB(0, population_size-1)];
      Solution* result_of_battle_1 = tournament(father1, father2);
      // tournament n°2
      father1 = population[randAB(0, population_size-1)];
      father2 = population[randAB(0, population_size-1)];
      Solution* result_of_battle_2  = tournament(father1, father2);

      if(result_of_battle_1 != result_of_battle_2){
	// crossover
	double pcc=frandAB(0,1);
	if(pcc <= P_c)
	  {
	    std::vector<Solution*> path = path_relinking(data, result_of_battle_1,result_of_battle_2, efficient_population);
	    crowding(path); // this crowding function calls ranking function
	    sort(path.begin(), path.end(), crowding_solution1_lower_than_solution_2);

	    //note: path contains at least two solutions (solutions used to the path relinking)

	    // mutation
	    double pmc=frandAB(0,1);

	    if(pmc <= P_m)
	      {
		for(unsigned int elem=0;elem<2;elem++){
		  bool correct=true;
		  // mutation of element i
		  int position_mut= randAB(0, numberOfCustomers-1); //the position of the mutation
		  int new_facility = randAB(0,numberOfFacility-1); // ????
		  std::vector<int> tmp1= ((path[elem])->getAffectation());
		  std::vector<int> _affectation= std::vector<int>();
                  for(unsigned int m=0;m< numberOfCustomers; m++){
			_affectation.push_back(tmp1[m]);
		  }
		  int old_facility = _affectation[position_mut];
		  _affectation[position_mut]=new_facility;
		  std::vector<double> tmp2=((path[elem])->getResidualCapacity());
		  std::vector<double> _residue_capacity= std::vector<double>();
                  for(unsigned int m=0;m< numberOfFacility; m++){
			_residue_capacity.push_back(tmp2[m]);
		  }
		  _residue_capacity[new_facility] -= data.getCustomer(position_mut).getDemand();
		  _residue_capacity[old_facility] += data.getCustomer(position_mut).getDemand();
					
		  if(_residue_capacity[new_facility] < 0){
		    correct = false;
		  }
					
		  //does the facility close or note?
		  std::vector<bool> opened_facility;
		  for (unsigned int i=0; i<numberOfFacility; ++i)
		    {
		      if((path[elem])->getY_j()[i] == '1')
			opened_facility.push_back(true);
		      else
			opened_facility.push_back(false);
		    } 
		  opened_facility[new_facility]=true;
		  opened_facility[old_facility]=false;
		  // if there is other custemers deserved by it => then it still open
		  for(unsigned int c=0; c<numberOfCustomers;c++){
		    if(_affectation[c] == old_facility){
		      _affectation[old_facility] = true;
		      break;
		    }
		  }

		  Solution* mutated_element = new Solution(_affectation, 
							   opened_facility, 
							   data,
							   _residue_capacity);
		  // if the visited solution est feasible / then we add it to the path
		  if (mutated_element->isCorrect()){
		    offspring_population.push_back(mutated_element);
		    efficient_population.addSolution(mutated_element);
		  }
		  else{
			delete mutated_element;
		  }
		}
	      }
	  }
      }
    }
}