コード例 #1
0
ファイル: Genetic.cpp プロジェクト: cyz14/Intro_to_AI
void Genetic::workout(std::ostream & fout) {
  // Answer answer(ncity);

  Answer ** colony = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    colony[i] = new Answer(ncity);
  }
  Answer ** nextGene = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    nextGene[i] = new Answer(ncity);
  }

  int t = 0;
  double bestAnswer = 0.0;
  int bestGeneId = -1;

  initPopulation(colony, SIZE);

  int gene_num = 1000 * ncity;
  while (t < gene_num) { // 结束条件: 遗传代数到达城市数目的1000倍

    bestGeneId = nextGeneration(colony, nextGene);
    bestAnswer = total_cost(*colony[bestGeneId]);
    // print(fout, colony[bestGeneId]);

    // (9)
    for (size_t i = 0; i < SIZE; i++) {
      *colony[i] = *nextGene[i];
    }
    t = t + 1;
  }
  // (10)
  print(fout, colony[bestGeneId]);
  std::cout << bestAnswer << std::endl;
}
コード例 #2
0
ファイル: Genetic.cpp プロジェクト: cyz14/Intro_to_AI
void Genetic::test_crossover() {
  Answer ** colony = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    colony[i] = new Answer(ncity);
  }
  initPopulation(colony, SIZE);

  for (size_t i = 0, j = 1; j < SIZE; i+=2, j+=2) {
    std::cout << "##### Crossover " << i << " #####" << std::endl;
    std::cout << "##### Before " << " #####" << std::endl;
    std::cout << fitvalue(*colony[i]) << ' ';
    colony[i]->print();
    std::cout << fitvalue(*colony[i]) << ' ';
    colony[j]->print();

    crossover(colony[i], colony[j]);

    std::cout << "##### After " << " #####" << std::endl;
    std::cout << fitvalue(*colony[i]) << ' ';
    colony[i]->print();
    std::cout << fitvalue(*colony[i]) << ' ';
    colony[j]->print();
  }

  for (size_t i = 0; i < SIZE; i++) {
    delete colony[i];
  }
  delete [] colony;
}
コード例 #3
0
ファイル: csp.cpp プロジェクト: cmaureir/utfsm2010
int main(int argc, const char *argv[])
{
	// 'true' satisfaccion restricciones duras
	bool type = true;
	// 'true' selecciona mejores
	bool cloneSelType = true;
	// 'true' remplaza los mas malos
	bool replaceType = true;
	// 'true' Se clonan mediante formula
	bool cloneType = true;

	timespec ts, te;

	clock_gettime(CLOCK_REALTIME, &ts);
	population[POP].fitness = 10000;	
	if(!checkFile(argc,argv))
		return 0;

	changeParam(argv);
//	cout << "ClonationFactor: "<<clonationFactor << endl;
//	cout << "ClonationRate: " << clonationRate << endl;
//	cout << "ReplaceRate: " << replaceRate << endl;
	
	inputReading(argv[1]);
	generation = 0;

	initPopulation(type);
	evaluation(population, type);

	while(generation<GENS){
		cleanPops();
		selection(clonationRate, population);
		clonation(tmpPop, cloneType);
		hypermutation();
		evaluation(clonePop, type);
		cloneSelection(clonePop, cloneSelType);
		cloneInsertion();
		newGeneration(replaceRate, replaceType);
		evaluation(population, type);
		generation++;
	}
	
	clock_gettime(CLOCK_REALTIME, &te);

//	printFile(argv[1],population[0].gene,population[0].fitness,(te.tv_sec-ts.tv_sec), (te.tv_nsec-ts.tv_nsec));
//	printFile(population[0].fitness);
	cout << replaceRate << " " << population[0].fitness << " " <<  (te.tv_sec-ts.tv_sec)<<"."<<(te.tv_nsec-ts.tv_nsec) << endl;

	return 0;
}
コード例 #4
0
void GeneticAlgorithm::evolve() {

	std::fstream file("log.txt", std::ios::out);

	file << "generation\t average fit\t best fit\t worst fit "<< std::endl;

	initPopulation();

	for(_generation = 0; _generation < _maxGenerations; ++_generation) {
		nextGeneration();

		file << _generation << "\t" << _averageFit << "\t" << _bestFit << "\t" << _worstFit << std::endl;
	}

	file.close();
}
コード例 #5
0
ファイル: sw_gpu_param_search.c プロジェクト: brahle/swSharp
extern void swGPUParamSearch(Chain* rowChainL, Chain* columnChainL, 
    SWPrefs* swPrefsL) {

    SWResult* swResult = 
        swDataGetResult(swSolveGPU(rowChainL, columnChainL, swPrefsL), 0);

    rowChain = rowChainL;
    columnChain = columnChainL;
    swPrefs = swPrefsL;
    columns = chainGetLength(columnChainL);
    expectedResult = swResultGetScore(swResult);

    srand(time(NULL));

    Cromosome child;

    initPopulation();
    evaluatePopulation();

    int generationIdx;
    int childIdx;

    for (generationIdx = 0; generationIdx < GENERATION_NMR; ++generationIdx) {

        sortCromosomes(population, 0, POPULATION_NMR - 1);

        printf(".............................................\n");
        printf("Generation: %d\n", generationIdx);

        for (childIdx = 0; childIdx < CHILD_NMR; ++childIdx) {

            child = crossover(selection());
            mutation(&child);

            children[childIdx] = child;
        }

        evaluateChildren();

        for (childIdx = 0; childIdx < CHILD_NMR; ++childIdx) {
            population[POPULATION_NMR - childIdx - 1] = children[childIdx];
        }
    }
}
コード例 #6
0
void examTimeTabling(Paper *papers[], int sizePapers, int sizeSession, int generation, int populationNum) {
    int times = 0, bestScore;
    Table *population[populationNum];

    initPopulation( population, papers, populationNum, sizePapers, sizeSession);

    while( times != generation) {
        bestScore = population[0]->fitnessScore;
        printf("%d\n",bestScore);

        mutateTable( population[random(populationNum)] );
        Paper *p = papers[random(sizePapers)];
        crossoverHandler( population, p , populationNum, sizeSession);
        sortInFitnessScore( population, populationNum);

        if( population[0]->fitnessScore < bestScore)
            times = 0;
        else times++;
    }
    printf("\n\n");
    printfTable(population[0]);
}
コード例 #7
0
ファイル: Genetic.cpp プロジェクト: cyz14/Intro_to_AI
void Genetic::test_mutate() {
  Answer ** colony = new Answer*[SIZE];
  for (size_t i = 0; i < SIZE; i++) {
    colony[i] = new Answer(ncity);
  }
  initPopulation(colony, SIZE);
  std::cout << std::setprecision(4) << std::endl;
  for (size_t i = 0; i < SIZE; i++) {
    std::cout << "##### Mutate" << i << " #####" << std::endl;
    std::cout << fitvalue(*colony[i]) << ' ';
    colony[i]->print();

    mutate(colony[i]);

    std::cout << fitvalue(*colony[i]) << ' ';
    colony[i]->print();
    std::cout << "##### Mutate" << i << " #####" << std::endl;
  }
  for (size_t i = 0; i < SIZE; i++) {
    delete colony[i];
  }
  delete [] colony;
}
コード例 #8
0
ファイル: main.cpp プロジェクト: rotty11/TIN2015-67020-P
/**
 * @brief Main program
 * @param argc The number of arguments of the program
 * @param argv Arguments of the program
 * @return Returns nothing if successful or a negative number if incorrect
 */
int main(const int argc, const char **argv) {


	/********** Get the configuration data from the XML file or from the command-line ***********/

	const Config conf(argv, argc);

	// Generic variables
	float dataBase[conf.nInstances * conf.nFeatures];
	float dataBaseTransposed[conf.nInstances * conf.nFeatures];
	int selInstances[conf.nCentroids];
	double referencePoint[conf.nObjectives];
	Individual populationOrig[conf.totalIndividuals];


	/********** Get the data base and its normalization ***********/

	readDataBase(dataBase, &conf);
	normDataBase(dataBase, &conf);
	transposeDataBase(dataBase, dataBaseTransposed, &conf); // Matrix transposed


	/********** Get the initial "conf.nCentroids" centroids ***********/

	getCentroids(selInstances, &conf);


	/********** Set the reference point ***********/

	// The reference point will be (X_1 = 1.0, X_2 = 1.0, .... X_conf.nObjectives = 1.0)
	for (int i = 0; i < conf.nObjectives; ++i) {
		referencePoint[i] = 1.0;
	}


	/********** Initialize the population and the individuals ***********/

	srand((u_int) time(NULL));

	// Population will have the parents and children (left half and right half respectively)
	// This way is better for the performance
	initPopulation(populationOrig, &conf);


	/********** OpenCL init ***********/

	// OpenCL mode
	if (conf.nDevices > 0) {

		CLDevice *devices = createDevices(dataBase, selInstances, dataBaseTransposed, &conf);

		// Benchmark mode (Sequential, heterogeneous and all devices per separate)
		if (conf.benchmarkMode) {

			// Each device per separate
			for (int i = 0; i < conf.nDevices; ++i) {
				agAlgorithm(populationOrig, devices[i].deviceType, &devices[i], NULL, NULL, referencePoint, &conf);
			}

			// Heterogeneous mode if more than 1 device is available
			if (conf.nDevices > 1) {
				agAlgorithm(populationOrig, CL_DEVICE_TYPE_ALL, devices, NULL, NULL, referencePoint, &conf);
			}

			// Sequential mode
			agAlgorithm(populationOrig, CL_DEVICE_TYPE_DEFAULT, NULL, dataBase, selInstances, referencePoint, &conf);
		}

		// Only 1 device (CPU or GPU)
		else if (conf.nDevices == 1) {
			agAlgorithm(populationOrig, devices[0].deviceType, &devices[0], NULL, NULL, referencePoint, &conf);
		}

		// Heterogeneous mode if more than 1 device is available
		else {
			agAlgorithm(populationOrig, CL_DEVICE_TYPE_ALL, devices, NULL, NULL, referencePoint, &conf);
		}


		/********** Resources used are released ***********/

		// OpenCL resources
		delete[] devices;
	}

	// Sequential mode
	else {
		agAlgorithm(populationOrig, CL_DEVICE_TYPE_DEFAULT, NULL, dataBase, selInstances, referencePoint, &conf);
	}

	// Generation of the Gnuplot file for display the Pareto front
	generateGnuplot(referencePoint, &conf);
}
コード例 #9
0
ファイル: main.c プロジェクト: dwinner/CppAppdev
int main()
{
  int generation = 0, i;
  FILE *fp;
  extern float minFitness, maxFitness, avgFitness;
  extern int curCrossovers, curMutations;
  extern int   curPop;

  void printProgram( int, int );

  srand(time(NULL));

  curPop = 0;

  fp = fopen("stats.txt", "w");

  if (fp == NULL) exit(-1);

  initPopulation();
  performFitnessCheck( fp );

  while (generation < MAX_GENERATIONS) {

    curCrossovers = curMutations = 0;

    performSelection();

    /* Switch the populations */
    curPop = (curPop == 0) ? 1 : 0;

    performFitnessCheck( fp );

    if ((generation++ % 100) == 0) {
      printf("Generation %d\n", generation-1);
      printf("\tmaxFitness = %f (%g)\n", maxFitness, MAX_FIT);
      printf("\tavgFitness = %f\n", avgFitness);
      printf("\tminFitness = %f\n", minFitness);
      printf("\tCrossovers = %d\n", curCrossovers);
      printf("\tMutation   = %d\n", curMutations);
      printf("\tpercentage = %f\n", avgFitness / maxFitness);
    }

    if ( generation > (MAX_GENERATIONS * 0.25) ) {
      if ((avgFitness / maxFitness) > 0.98) {
        printf("converged\n");
        break;
      }
    }

    if (maxFitness == MAX_FIT) {
      printf("found solution\n");
      break;
    }

  }

  printf("Generation %d\n", generation-1);
  printf("\tmaxFitness = %f (%g)\n", maxFitness, MAX_FIT);
  printf("\tavgFitness = %f\n", avgFitness);
  printf("\tminFitness = %f\n", minFitness);
  printf("\tCrossovers = %d\n", curCrossovers);
  printf("\tMutation   = %d\n", curMutations);
  printf("\tpercentage = %f\n", avgFitness / maxFitness);

  for (i = 0 ; i < MAX_CHROMS ; i++) {

    if (populations[curPop][i].fitness == maxFitness) {
      int index;
      printf("Program %3d : ", i);

      for (index = 0 ; index < populations[curPop][i].progSize ; index++) {
        printf("%02d ", populations[curPop][i].program[index]);
      }
      printf("\n");
      printf("Fitness %f\n", populations[curPop][i].fitness);
      printf("ProgSize %d\n\n", populations[curPop][i].progSize);

      printProgram(i, curPop);

      break;
    }

  }

  return 0;
}