std::vector<std::vector<int>> TwoPointCrossover::Reproduce(std::vector<int>& father, std::vector<int>& mother)
{
	int firstPoint = Math::RandomExclusive(father.size());
	int secondPoint = firstPoint + Math::RandomExclusive(father.size() - firstPoint);

	std::vector<std::vector<int>> result(2);

	result[0] = Crossover(father, mother, firstPoint, secondPoint);
	result[1] = Crossover(mother, father, firstPoint, secondPoint);

	return result;
}
void Population::Evolve(size_t elitism_count) {
	std::vector<Individual> evolved_pop(pop_.size());
	std::vector<size_t> elites = Elitism(elitism_count);
	
	/* Choosing elite individuals uses raw fitness */
	for (size_t j = 0; j < elitism_count; ++j) {
		evolved_pop[j] = pop_[elites[j]];
	}

	for (size_t j = elitism_count; j < pop_.size(); ++j) {
		size_t p1 = SelectIndividual();
		size_t p2;
		do {
			p2 = SelectIndividual();
		} while (p2 == p1);

		Individual parent1(pop_[p1]);
		Individual parent2(pop_[p2]);
		Crossover(&parent1, &parent2);

		evolved_pop[j] = parent1;
		evolved_pop[j].Mutate(mutation_rate_);
	}
	this->pop_ = evolved_pop;
	CalculateFitness();
}
// Epoch Method
void GeneticAlgorithm::Epoch() {
	// Update the fitness scores
	UpdateFitnessScores();
	// Create a new population
	int iNewOffspring = 0;
	// Create a placeholder for the offspring
	vector<Genome> vOffspringGenomes;
	// Loop through the babies
	while (iNewOffspring < mPopulationSize) {
		// Select 2 parents
		Genome vMother = Selection();
		Genome vFather = Selection();
		// Offspring placeholders
		Genome vOffspringAlpha, vOffspringBeta;
		// Crossover
		Crossover(vMother.vBits, vFather.vBits, vOffspringAlpha.vBits, vOffspringBeta.vBits);
		// Mutate
		Mutate(vOffspringAlpha.vBits);
		Mutate(vOffspringBeta.vBits);
		// Add the offspring to the new population
		vOffspringGenomes.push_back(vOffspringAlpha);
		vOffspringGenomes.push_back(vOffspringBeta);
		// Increment the offspring
		iNewOffspring += 2;
	}
	// Copy the offspring back into the initial population
	mGenomes = vOffspringGenomes;
	// Increment the generations
	++mGeneration;
}
Exemple #4
0
void EnumKare::Epoch()
{
	UpdataFitnessScores();

	int NewBabies = 0;

	vector<SGenome> vecBabyGenomes;

	while (NewBabies < m_iPopSize)
	{
		SGenome mum = RouletteWheelSelection();
		SGenome dad = RouletteWheelSelection();

		SGenome baby1, baby2;
		Crossover(mum.vecBits, dad.vecBits, baby1.vecBits, baby2.vecBits);

		Mutate(baby1.vecBits);
		Mutate(baby2.vecBits);

		vecBabyGenomes.push_back(baby1);
		vecBabyGenomes.push_back(baby2);

		NewBabies += 2;

	}

	m_vecGenomes = vecBabyGenomes;

	++m_iGeneration;
}
Exemple #5
0
void GAStep(){
    Chromosome *elite = SelectBest();
    Chromosome clonA;
    Chromosome clonB;
    Chromosome *ap = NULL;

    // Elitism
    elite->Clone(&clonA);
    InsertPobB(&clonA);

    // harem
    int fraction = int(HAREM * sizePopulationA);
    for(int i = 0; i < fraction; i += 2){
        elite->Clone(&clonA);
        SelectTournament()->Clone(&clonB);
        Crossover(&clonA, &clonB);
        clonA.Mutate();
        clonB.Mutate();

        clonA.Fitness() = Distance(&clonA);
        clonB.Fitness() = Distance(&clonB);

        InsertPobB(&clonA);
        InsertPobB(&clonB);
    }

    // Fill
    while((sizePopulationA - sizePopulationB) > 0){
        ap = SelectTournament();
        ap->Clone(&clonA);
        ap = SelectTournament();
        ap->Clone(&clonB);

        Crossover(&clonA, &clonB);
        clonA.Mutate();
        clonB.Mutate();
        clonA.Fitness() = Distance(&clonA);

        clonB.Fitness() = Distance(&clonB);

        if(clonA.Fitness() < clonB.Fitness())
            InsertPobB(&clonA);
        else
            InsertPobB(&clonB);
    }
    UpdatePopulation();
}
void GA_BuildTower::Run()
{
  for (int i = 0; i < generation_cnt; ++i) {
    Select();
    Crossover();
    Mutate();
    CalFitness();
    Elitist();
  }
}
Exemple #7
0
///////////////////////////////  INTERFACE  ////////////////////////////////
void GeneticClass::Interface(){
	lc = 10000;             
	int algorithmIteration = 30;
	float crossoverRatio = 0.9;
	int mutationIteration = 1000;

	int score = 0, parent1, parent2;

	DrawingPopulation();
	Rating();
	cout << "Rodzice: " << bestScoreInAll << endl;
	checksRepeatsInSet();

	////////////// SELEKCJA I KRZYZOWANIE I MUTACJA///////////////////////////////
	for (int z = 0; z<algorithmIteration; z++){
		int P = -1;		                            // licznik nowej populacji
		vector<bool> crossed(lc,false);
		int crossoverIterations = (lc - 2) * crossoverRatio;
		#pragma omp parallel for
		for (P = -1; P < crossoverIterations; P += 2)
		{
			parent1 = TournamentSelection(10);
			do
				parent2 = TournamentSelection(10);
			while (parent1 == parent2);
			crossed[parent1] = true;
			crossed[parent2] = true;
			Crossover(parent1, parent2, children[P + 1], children[P + 2]);
		}

		for (int i = 0 ; i < lc; i++) {					//Dopisuje do children osobniki ktore nie braly udzialu w krzyzowaniu
			if (crossoverIterations != lc) {
				if (crossed[i] == false) {
					children[crossoverIterations++] = chromosom[i];
				}
			}
			else {
				break;
			}
		}

		chromosom.swap(children);						
		
		for (int i = 0; i<mutationIteration; i++){
			int target = TournamentSelection(100);
			Mutation(chromosom[target]);			//	przy zakomentowanym krzyzowaniu wpisalem tu chromosom zamiast children 
		}

		checksRepeatsInSet();
	
		score = Rating();
		cout << "Populacja_" << z << " = " << score << endl;
	}
	showBest();
}
//-----------------------------------Epoch()-----------------------------
//
//	takes a population of chromosones and runs the algorithm through one
//	 cycle.
//	Returns a new population of chromosones.
//
//-----------------------------------------------------------------------
vector<SGenome> CGenAlg::Epoch(vector<SGenome> &old_pop)
{
	//assign the given population to the classes population
  m_vecPop = old_pop;

  //reset the appropriate variables
  Reset();

  //sort the population (for scaling and elitism)
  sort(m_vecPop.begin(), m_vecPop.end());

  //calculate best, worst, average and total fitness
	CalculateBestWorstAvTot();
  
  //create a temporary vector to store new chromosones
	vector <SGenome> vecNewPop;

	//Now to add a little elitism we shall add in some copies of the
	//fittest genomes. Make sure we add an EVEN number or the roulette
  //wheel sampling will crash
	if (!(CParams::iNumCopiesElite * CParams::iNumElite % 2))
	{
		GrabNBest(CParams::iNumElite, CParams::iNumCopiesElite, vecNewPop);
	}
	

	//now we enter the GA loop
	
	//repeat until a new population is generated
	while (vecNewPop.size() < m_iPopSize)
	{
		//grab two chromosones
		SGenome mum = GetChromoRoulette();
		SGenome dad = GetChromoRoulette();

		//create some offspring via crossover
		vector<double>		baby1, baby2;

		Crossover(mum.vecWeights, dad.vecWeights, baby1, baby2);

		//now we mutate
		Mutate(baby1);
		Mutate(baby2);

		//now copy into vecNewPop population
		vecNewPop.push_back(SGenome(baby1, 0));
		vecNewPop.push_back(SGenome(baby2, 0));
	}

	//finished so assign new pop back into m_vecPop
	m_vecPop = vecNewPop;

	return m_vecPop;
}
Exemple #9
0
void ApplyCrossover(int i, int j)
{
    int *Pi, *Pj, k;

    Pi = Population[i];
    Pj = Population[j];
    for (k = 1; k <= Dimension; k++) {
        NodeSet[Pi[k - 1]].Suc = &NodeSet[Pi[k]];
        NodeSet[Pj[k - 1]].Next = &NodeSet[Pj[k]];
    }
    if (TraceLevel >= 1)
        printff("Crossover(%d,%d)\n", i + 1, j + 1);
    /* Apply the crossover operator */
    Crossover();
}
Exemple #10
0
void
Algorithm<T>::Init(int pCountOfIndividuals, 
									 int pCountOfChromosomes,
						       const std::vector<T>& pAllPossibleIndividuals,
						       TaskDefinition<T>* pTask)
{
	if (!m_isInitialized) {
		assert (pAllPossibleIndividuals.size() != 0);
		assert (m_countOfIndividuals <= pAllPossibleIndividuals.size());
		m_countOfIndividuals = pCountOfIndividuals;
		m_countOfChromosomes = pCountOfChromosomes;
		m_allPossibleIndividuals = pAllPossibleIndividuals;
        m_task = pTask;
		
		// 1. Randomly initialize population.
		RandomInitPopulation();

		while (true) {
			// 2. Calculate fitness values.
			CalculateObjectiveFunction();

			// 3. Calculate fitness value. 
			CalculateFitnessValue();

			// 4. Calculate fitness probability.
			CalculateFitnessProbability();

			// 5. Calculate cumulative probability.
			CalculateCumulativeProbability();

			// 6. Selection
			Selection();

			// 7. Extract Parents
			ExtractParents();

			// 8. Crossover
			Crossover();

			// 9. Mutation
			Mutation();

		}
		m_isInitialized = true;
	} else {
		std::cout << "Algorithm is already initialized." << std::endl;
	}
}
Exemple #11
0
//--------------------------------Epoch---------------------------------
//
//	This is the workhorse of the GA. It first updates the fitness
//	scores of the population then creates a new population of
//	genomes using the Selection, Croosover and Mutation operators
//	we have discussed
//----------------------------------------------------------------------
void Cga::Epoch()
{
	//Now to create a new population
	int NewBabies = 0;

  CalculateTotalFitness();

	//create some storage for the baby genomes 
	vector<SGenome> vecBabyGenomes;

  //Now to add a little elitism we shall add in some copies of the
	//fittest genomes
	  
	//make sure we add an EVEN number or the roulette wheel
	//sampling will crash
	if (!(NUM_COPIES_ELITE  * NUM_ELITE % 2))
	{
		GrabNBest(NUM_ELITE, NUM_COPIES_ELITE, vecBabyGenomes);
	}

	while (vecBabyGenomes.size() < m_iPopSize)
	{
		//select 2 parents
		SGenome mum = RouletteWheelSelection();
		SGenome dad = RouletteWheelSelection();

		//operator - crossover
		SGenome baby1, baby2;
		Crossover(mum.vecBits, dad.vecBits, baby1.vecBits, baby2.vecBits);

		//operator - mutate
		Mutate(baby1.vecBits);
		Mutate(baby2.vecBits);

		//add to new population
		vecBabyGenomes.push_back(baby1);
		vecBabyGenomes.push_back(baby2);

		NewBabies += 2;
	}

	//copy babies back into starter population
	m_vecGenomes = vecBabyGenomes;

	//increment the generation counter
	++m_iGeneration;
}
void CreatureEvolver::Generation()
{
	assert(m_fitnesses.size() == m_populationSize);

	// Get elites
	std::vector<CreatureGenes> eliteGenes;
	std::vector<unsigned int> chumpIndices;

	FindElites(eliteGenes);
	RemoveChumps(chumpIndices);
	GetTotalFitness();

	// Obtain their genes from the neuron data
	CreatureGenes* pGene1, * pGene2;

	//float halfNumFitnesses = static_cast<float>(m_fitnesses.size()) / 2.0f;

	while(m_fitnesses.size() >= 2)
	{
		// Choose the two members to procreate by index
		unsigned int index1 = RouletteSelection();
		unsigned int index2 = RouletteSelection();

		pGene1 = m_genotypePopulation[index1];
		pGene2 = m_genotypePopulation[index2];

		// Determine whether should crossover
		if(Randf() < m_crossoverRate) // if(Randf() * halfNumFitnesses < m_crossoverRate)
			Crossover(pGene1, pGene2);

		//halfNumFitnesses -= 1.0f;

		// Mutate both chromosomes
		Mutate(pGene1);
		Mutate(pGene2);
	}

	// Replace chumps with elites
	for(unsigned int i = 0; i < m_numElites; i++)
	{
#ifdef MUTATE_ELITES
		Mutate(&eliteGenes[i]);
#endif
		(*m_genotypePopulation[chumpIndices[i]]) = eliteGenes[i];
	}
}
Exemple #13
0
//! Reproduce candidates to create the next generation.
void CNE::Reproduce()
{
  // Sort fitness values. Smaller fitness value means better performance.
  index = arma::sort_index(fitnessValues);

  // First parent.
  size_t mom;

  // Second parent.
  size_t dad;

  for (size_t i = numElite; i < populationSize - 1; i++)
  {
    // Select 2 different parents from elite group randomly [0, numElite).
    mom = mlpack::math::RandInt(0, numElite);
    dad = mlpack::math::RandInt(0, numElite);

    // Making sure both parents are not the same.
    if (mom == dad)
    {
      if (dad != numElite - 1)
      {
        dad++;
      }
      else
      {
        dad--;
      }
    }

    // Parents generate 2 children replacing the dropped-out candidates.
    // Also finding the index of these candidates in the population matrix.
    Crossover(index[mom], index[dad], index[i], index[i + 1]);
  }

  // Mutating the weights with small noise values.
  // This is done to bring change in the next generation.
  Mutate();
}
//--------------------------------Epoch---------------------------------
//
//	This is the workhorse of the GA. It first updates the fitness
//	scores of the population then creates a new population of
//	genomes using the Selection, Croosover and Mutation operators
//	we have discussed
//----------------------------------------------------------------------
void CgaBob::Epoch()
{
	
	UpdateFitnessScores();
    
	//Now to create a new population
	int NewBabies = 0;
    
	//create some storage for the baby genomes 
	vector<SGenome> vecBabyGenomes;
    
	while (NewBabies < m_iPopSize)
	{
		//select 2 parents
		SGenome mum = RouletteWheelSelection();
		SGenome dad = RouletteWheelSelection();
        
		//operator - crossover
		SGenome baby1, baby2;
		Crossover(mum.vecBits, dad.vecBits, baby1.vecBits, baby2.vecBits);
        
		//operator - mutate
		Mutate(baby1.vecBits);
		Mutate(baby2.vecBits);
        
		//add to new population
		vecBabyGenomes.push_back(baby1);
		vecBabyGenomes.push_back(baby2);
        
		NewBabies += 2;
	}
    
	//copy babies back into starter population
	m_vecGenomes = vecBabyGenomes;
    
	//increment the generation counter
	++m_iGeneration;
}
Exemple #15
0
//------------------------Epoch-------------------------------
//
//	creates a new population of genomes using the selection,
//	mutation and crossover operators
//------------------------------------------------------------
void CgaTSP::Epoch()
{

	//first we reset variables and calculate the fitness of each genome
	Reset();
	
	CalculatePopulationsFitness();

	//if we have found a solution exit
	if ((m_dShortestRoute <= m_pMap->BestPossibleRoute()))
	{
		m_bStarted = false;
		
		return;
	}	

  //perform the appropriate fitness scaling
  FitnessScaleSwitch();

  //if sigma is zero (either set in sigma scaling or in CalculateBestWorstAv
  //then the population are identical and we should stop the run
  if (m_dSigma == 0)
  {
    m_bStarted = false;

    return;
  }
	
	//create a temporary vector for the new population
	vector<SGenome> vecNewPop;
	
  if (m_bElitism)
  {
	  //Now to add a little elitism we shall add in some copies of the
	  //fittest genomes
	  const int CopiesToAdd = 2;
	  const int NBest		  = 4;
	  
	  //make sure we add an EVEN number or the roulette wheel
	  //sampling will crash
	  if (!(CopiesToAdd * NBest % 2))
	  {
		  GrabNBest(NBest, CopiesToAdd, vecNewPop);
	  }
  }

  //SUS selection selects the entire population all at once so we have to
  //handle the epoch slightly differently if SUS is chosen
  if(m_SelectionType != SUS)
  {
	  //now create the remainder of the population
	  while (vecNewPop.size() != m_iPopSize)
	  {
	  
		  SGenome mum, dad;
    
      //switch on selection method
      switch(m_SelectionType)
      {
      case ROULETTE:
  
        //grab two parents dependent on the selection method
		    mum = RouletteWheelSelection();
		    dad = RouletteWheelSelection();

        break;

      case TOURNAMENT:

        mum = TournamentSelection(NUM_TO_COMPARE);
	      dad = TournamentSelection(NUM_TO_COMPARE);

        break;

      case ALT_TOURNAMENT:
 
        mum = AlternativeTournamentSelection();
	      dad = AlternativeTournamentSelection();

        break;
      }

		  //create 2 children
		  SGenome baby1, baby2;
		  
		  //Breed them
      Crossover(mum.vecCities,
                dad.vecCities,
                baby1.vecCities,
                baby2.vecCities,
                m_CrossoverType);

		  //and mutate them
		  Mutate(baby1.vecCities, m_MutationType);
		  Mutate(baby2.vecCities, m_MutationType);

		  //add them to new population
		  vecNewPop.push_back(baby1);
		  vecNewPop.push_back(baby2);
	  }
  }

  //SUS selection
  else
  {
    //select all the individuals
    vector<SGenome> vecSampledPop;

    SUSSelection(vecSampledPop);

    //step through the newly sampled population and apply crossover
    //and mutation operators
    for (int gen=0; gen<vecSampledPop.size(); gen+=2)
    {
      SGenome baby1, baby2;
      
      Crossover(vecSampledPop[gen].vecCities,
                vecSampledPop[gen+1].vecCities,
                baby1.vecCities,
                baby2.vecCities,
                m_CrossoverType);

      Mutate(baby1.vecCities, m_MutationType);
      Mutate(baby2.vecCities, m_MutationType);

      vecNewPop.push_back(baby1);
      vecNewPop.push_back(baby2);      

    }
   
  }

	//copy into next generation
	m_vecPopulation = vecNewPop;

	//increment generation counter
	++m_iGeneration;
}
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;
}
Exemple #17
0
Generate()
{
	static int rsflag = 1;	/* flag cleared after restart		*/

	STRUCTURE *temp;	/* for swapping population pointers	*/
	register int i;		/* for marking structures		*/

	if (Traceflag)
		printf("                    Gen %d\n",Gen);
	Trace("Generate entered");

	/* create a new population */

	if (Restartflag && rsflag)
	{
		/* this is a restart so read checkpoint file */
		Restart();
		rsflag = 0;	/* disable local restart flag. */
		Converge();
	}

	else if (Gen == 0)
		/* this is a fresh experiment */
	{
		Initialize();	/* form an initial population */
		Spin++;	
	}

	else
		/* form a new population from */
		/* the old one via genetic operators */
	{
		Select();
		Mutate();
		Crossover();
		if (Eliteflag)
			Elitist();
		if (Allflag)	/* mark structures for evaluation */
			for (i=0; i<Popsize; i++) New[i].Needs_evaluation = 1;
		Spin++;
	}

	/* evaluate the newly formed population */
	Evaluate();

	/* gather performance statistics */
	Measure();

	/* check termination condition for this experiment	*/
	Doneflag = Done();

	/* checkpoint if appropriate */
	if (Num_dumps && Dump_freq && Gen % Dump_freq == 0)
	{
		if (Num_dumps > 1)
		{
			sprintf(Dumpfile, "dump.%d", Curr_dump);
			Curr_dump = (Curr_dump + 1) % Num_dumps;
			Checkpoint(Dumpfile);
		}
		Checkpoint(Ckptfile);
	}
	else
	{
		if (Doneflag)
		{
			if (Lastflag)
				Checkpoint(Ckptfile);
			else
				if (Savesize)
					Printbest();
		}
	}


	/* swap pointers for next generation */
	temp = Old;
	Old = New;
	New = temp;

	/* update generation counter */
	Gen++;

	Trace("Generate completed");
}
bool GeneticAlgorithm::CreateTimetable(int stop, float infeasibilitiesWeight, float didacticDissatisfactionWeight, 
									   float organizationalDissatisfactionWeight, int mutationGenSize, float crossoverProbability)
{
	finished = false;

	if(!CheckData())
	{
		std::cout << "Bledne dane wejsciowe!" << std::endl;
		return false;
	}

	float min = std::numeric_limits<float>::max();
	char *** solution = new char **[teachers_count];
	for (int i = 0; i < teachers_count; i++)
	{
		solution[i] = new char*[days];
		for (int j = 0; j < days; j++)
		{
			solution[i][j] = new char[hours_per_day];
		}
	}
	int it = 0;
	int seed = time(NULL);
	while(it < stop)
	{
		std::cout << "New population cycle " << it << std::endl;
		srand(seed++);
		int iteration = 0;
		Initialize();
		for(int i = 0; i < population_size; ++i)
		{
			Filter(timetables[i]);
		}
		for(; it < stop; ++it)
		{
			std::cout << it << std::endl;
			float *initial_fitness = CalculateObjectiveFunction(timetables, population_size, infeasibilitiesWeight, didacticDissatisfactionWeight, 
				organizationalDissatisfactionWeight);
			std::vector<char***> new_population = Reproduction(initial_fitness);

			Crossover(new_population, crossoverProbability, infeasibilitiesWeight, 
				didacticDissatisfactionWeight, organizationalDissatisfactionWeight);

			float *new_fitness = CalculateObjectiveFunction(new_population.data(), new_population.size(), infeasibilitiesWeight, didacticDissatisfactionWeight, 
				organizationalDissatisfactionWeight);
			Succession(initial_fitness, new_fitness, new_population);

			delete [] initial_fitness;
			delete [] new_fitness;

			for (int individual = 0; individual < population_size; individual++)
			{
				ApplyMutationOfOrder(individual,mutationGenSize);
				ApplyDayMutation(individual);
				Filter(timetables[individual]);
			}
			float * results = CalculateObjectiveFunction(timetables, population_size, infeasibilitiesWeight, didacticDissatisfactionWeight, 
				organizationalDissatisfactionWeight);
			int idx = -1;
			for (int i = 0; i < population_size; i++)
			{
				if(results[i] < min)
				{
					min = results[i];
					idx = i;
				}
			}
			if(idx > -1)
			{
				for (int i = 0; i < teachers_count; i++)
				{
					for (int j = 0; j < days; j++)
					{
						for (int k = 0; k < hours_per_day; k++)
						{
							solution[i][j][k] = timetables[idx][i][j][k];
						}
					}
				}
				std::cout << "Actual minimum: " << min << std::endl;
				iteration = 0;
			}
			else
				iteration++;
			if(iteration > max_iterations)
				break;
		}
	}

	std::ofstream result;
	result.open("result.pout");
	std::cout << "Final minimum: " << std::endl << min << std::endl;
	std::cout << "Final solution:" << std::endl;
	PrintTimetable(solution, std::cout);
	PrintTimetable(solution, result);
	// put minimum data into file
	result << "Minimum: " << min;
	result.close();

	finished = true;

	return true;
}
int main(int argc, char *argv[])
{
	srand(time(NULL));
	double populationSize = atoi(argv[1]);
	float target = (float)atoi(argv[2]);
	printf("Running with:\n    Population Size = %.0f\n    Bit Length = %d\n", populationSize, BITLENGTH);
	
	long int i = 0;
	int j = 0;
	struct subject *sheep = (struct subject*)malloc(sizeof(struct subject) * populationSize);
	
	gettimeofday(&start, NULL);
	
	//make the Adam&Eve generation
	for(i = 0; i < populationSize; i++)
	{
		if(debug == 0)
		{
			printf("subject %d bits = ", i);
		}
		for(j = 0; j < BITLENGTH; j++)
		{
			sheep[i].bits[j] = rand() %2;
			if(debug == 0)
			{
				printf("%d", sheep[i].bits[j]);
			}
		}
		sheep[i].fitness = 0.0f;
		if(debug == 0)
		{
			printf(" with fitness %f\n", sheep[i].fitness);
		}
	}
	
	int howLongThisShitTook = 0;
	
	int solutionFound = 0;	//0 if false, 1 if true
	
	struct subject *fuckSpawn = (struct subject*)malloc(sizeof(struct subject) * populationSize);
	
	while(solutionFound != 1)
	{
		float totalFitness = 0.0f;
		
		for(i = 0; i < populationSize; i++)
		{
			sheep[i].fitness = AssignFitness(sheep[i].bits, target);
			if(debug == 0)
			{
				printf("\n subject %d with fitness %f\n", i, sheep[i].fitness);
			}
			totalFitness += sheep[i].fitness;
			if(debug == 0)
			{
				printf(" Total Fitness%f\n", totalFitness);
			}
		}
	
		for(i = 0; i < populationSize; i++)
		{
			if(sheep[i].fitness == 999.0f)
			{
				printf("It's been found. It took %d generations to find\n", howLongThisShitTook);
				solutionFound = 1;
				break;
			}
		}
		
		long fuckSpawnPopulationSize = 0;
		
		int fuckSpawn1Bits[BITLENGTH];
		int fuckSpawn2Bits[BITLENGTH];
		if(solutionFound != 1)
		{
			printf("Creating New Generation\n");
			while(fuckSpawnPopulationSize < populationSize)
			{
				MakeMeABaby(totalFitness, populationSize, sheep, fuckSpawn1Bits);
				MakeMeABaby(totalFitness, populationSize, sheep, fuckSpawn2Bits);
				
				Crossover(fuckSpawn1Bits, fuckSpawn2Bits);
				
				Mutate(fuckSpawn1Bits);
				Mutate(fuckSpawn2Bits);
			
				for(i = 0; i < BITLENGTH; i++)
				{
					fuckSpawn[fuckSpawnPopulationSize].bits[i] = fuckSpawn1Bits[i];
					fuckSpawn[fuckSpawnPopulationSize + 1].bits[i] = fuckSpawn2Bits[i];
				}
				
				if(debug == 0)
				{
					printf("fuckspawn%d: ", fuckSpawnPopulationSize);
					for(i = 0; i < BITLENGTH; i++)
					{
						printf("%d", fuckSpawn[fuckSpawnPopulationSize].bits[i]);
					}
					printf("\nfuckspawn%d: ",fuckSpawnPopulationSize + 1);
					for(i = 0; i < BITLENGTH; i++)
					{
						printf("%d", fuckSpawn[fuckSpawnPopulationSize + 1].bits[i]);
					}
					printf("\n");
				}
				fuckSpawn[fuckSpawnPopulationSize].fitness = 0.0f;
				fuckSpawn[fuckSpawnPopulationSize + 1].fitness = 0.0f;
				fuckSpawnPopulationSize += 2;
			}
			
			for(i = 0; i < populationSize; i++)
			{
				sheep[i] = fuckSpawn[i];
			}
			
			howLongThisShitTook++;
			printf("New Generation done! Now on Generation %d\n", howLongThisShitTook);
		}
		
		if(howLongThisShitTook > MAXGENERATIONS)
		{
			printf("Did not find a solution in maximum allowable runs\n");
			solutionFound = 1;
		}
	}
	
	gettimeofday(&end, NULL);
	int timeran = (((end.tv_sec - start.tv_sec) * 1000000) +(end.tv_usec - start.tv_usec));
	printf("Completed in %d Nano Seconds\n", timeran);
	
	return 0;
}
Exemple #20
0
void GeneticAlgorithm(){

    int maxIter = 100;
    int i,j,k;
    int group[GROUP_SIZE][COUNT_FUNC];
    int oldParameter[COUNT_FUNC];
    int maxIndex;
    double sum,max,min,tmp;
    int count_record = 0;
    char output[300];

    /*初始族群*/
    InitGroup(group);



    for ( i = 0 ; i < maxIter ; i++){
        Eliminate(group);
        Crossover(group);
        Mutation(group);

        sum = 0;
        max = -1;
        min = 20;
        maxIndex = 0;
        #pragma omp parallel for
        for ( j = 0 ; j < GROUP_SIZE ; j++){
            tmp= Evalue( group[j]);

            if ( tmp > 10){
                fout = fopen("parameter.txt", "a");
                sprintf(output,"Parameter = ");
                for ( k = 0 ; k < COUNT_FUNC ; k++){
                    sprintf(output,"%s %5d",output, group[j][k]);
                }
                sprintf(output,"%s, Score = %lf\n",output,tmp);
                fprintf(fout,"%s",output);
                fclose(fout);
            }

            sum += tmp;

            if ( tmp > max ){
                max= tmp;
                maxIndex = j;
            }
            if ( tmp < min )
                min = tmp;
        }
        if ( i % 10 == 0)
            Record(group);
        printf("Level(%d) = %.2lf, %.2lf, %.2lf\n", i,max,sum/GROUP_SIZE,min);
        if ( max >= 10.5 && PlayGame(group[maxIndex]) >= 10.9)
            break;
    }

    printf("==Result==\n");
    for ( i = 0 ; i < COUNT_FUNC ; i++){
        printf(", %d", group[maxIndex][i]);
    }
    putchar('\n');

}
Exemple #21
0
void TestPeakSearch
    (
    HINSTANCE inst,
    HWND      wdw,
    strstream & buffer
    )
    {
    buffer << "Function Optimization (Peak Search)\r\n"
              "-----------------------------------\r\n";

    // create configuration and verify it
    GAOptConfig gaoc(inst,wdw);

    if (!gaoc.GetValidity())
        {
        buffer << "Cancelled\r\n";
        return;
        }

    // display parameters for this run
    buffer << "\r\n   Equation: ";

    switch (gaoc.GetEquation())
        {
        case 0:
            buffer << "f6(x,y) = x²+2y²-0.3cos(3px)-0.4cos(4py)+0.7";
            break;
        case 1:
            buffer << "f7(x,y) = x²+2y²-0.3[cos(3px)cos(4py)]+0.3";
            break;
        case 2:
            buffer << "f8(x,y) = x²+2y²-0.3[cos(3px)+cos(4py)]+0.3";
            break;
        case 3:
            buffer << "f(x,y) = 1/((x+0.5)²+2(y-0.5)²-0.3cos(3px)-0.4cos(4py)+0.8)";
        }

    buffer << "\r\n  Pop. Size: " << gaoc.GetPopSize();
    buffer << "\r\n  Test Size: " << gaoc.GetTestSize();
    buffer << "\r\n  Rep. Freq: " << gaoc.GetReptFreq();
    buffer << "\r\nSig. Digits: " << gaoc.GetSigDigits();
    buffer << "\r\n      X Min: " << gaoc.GetXMin();
    buffer << "\r\n      X Max: " << gaoc.GetXMax();
    buffer << "\r\n      Y Min: " << gaoc.GetYMin();
    buffer << "\r\n      Y Max: " << gaoc.GetYMax();
    buffer << "\r\nCrossover %: " << gaoc.GetCrossRate() * 100.0F;
    buffer << "\r\n    Cross X: " << gaoc.GetCrossX();
    buffer << "\r\n    Cross Y: " << gaoc.GetCrossY();
    buffer << "\r\n    Cross B: " << gaoc.GetCrossB();
    buffer << "\r\n Mutation %: " << gaoc.GetMuteRate() * 100.0F;
    buffer << "\r\n   Wt. Sign: " << gaoc.GetWtSign();
    buffer << "\r\n   Wt. Expt: " << gaoc.GetWtExp();
    buffer << "\r\n   Wt. Mant: " << gaoc.GetWtMant();
    buffer << "\r\n   Mutate X: " << gaoc.GetMutateX();
    buffer << "\r\n   Mutate Y: " << gaoc.GetMutateY();
    buffer << "\r\nMutate Loop: " << gaoc.GetMuteLoop();
    buffer << "\r\n    Elitism: " << gaoc.GetElitist();
    buffer << "\r\nFit Scaling: " << gaoc.GetFitScale();
    buffer << "\r\n  Fit Algor: ";

    switch(gaoc.GetFitAlgor())
        {
        case FSA_EXPON:
            buffer << "Exponential";
            break;
        case FSA_WINDOW:
            buffer << "Windowing";
            break;
        case FSA_LINEAR:
            buffer << "Linear Normalization";
            buffer << "\r\nFS Lin Base: " << gaoc.GetFitLinBase();
            buffer << "\r\nFS Lin  Dec: " << gaoc.GetFitLinDec();
            buffer << "\r\nFS Lin  Min: " << gaoc.GetFitLinMin();
        }

    buffer << "\r\n\r\n";

    // store dimensions of test
    const size_t POP_SZ  = gaoc.GetPopSize();
    const size_t GEN_SZ  = gaoc.GetTestSize();
    const size_t EQ_ID   = gaoc.GetEquation();
    const size_t SIG_DIG = gaoc.GetSigDigits();

    buffer << setprecision(SIG_DIG) << dec;

    // create random deviate and mutation objects
    RandDev devgen;
    FloatMutagen fmute(gaoc.GetWtSign(),gaoc.GetWtExp(),gaoc.GetWtMant());

    // allocate population and fitness arrays
    double * x = new double [POP_SZ];

    if (x == NULL)
        {
        buffer << "Memory allocation failed\r\n";
        return;
        }

    double * xnew = new double [POP_SZ];

    if (xnew == NULL)
        {
        buffer << "Memory allocation failed\r\n";
        return;
        }

    double * y = new double [POP_SZ];

    if (y == NULL)
        {
        buffer << "Memory allocation failed\r\n";
        return;
        }

    double * ynew = new double [POP_SZ];

    if (ynew == NULL)
        {
        buffer << "Memory allocation failed\r\n";
        return;
        }

    double * fit = new double [POP_SZ];

    if (fit == NULL)
        {
        buffer << "Memory allocation failed\r\n";
        return;
        }

    double * ptrf = fit - 1;
    double * ptrx =  x  - 1;
    double * ptry =  y  - 1;

    // various variables
    double best, lowf, fitn, vf, vx, vy;
    size_t i, j, inc, g, ibest, p1, p2;
    char buf[64];

    // calculate ranges
    const double rangex = gaoc.GetXMax() - gaoc.GetXMin();
    const double rangey = gaoc.GetYMax() - gaoc.GetYMin();

    // generate initial X values
    for (i = 0; i < POP_SZ; ++i)
        {
        x[i] = SigDig(rangex * devgen() + gaoc.GetXMin(),SIG_DIG);
        y[i] = SigDig(rangey * devgen() + gaoc.GetYMin(),SIG_DIG);
        }

    // do the generations
    for (g = 0; g < GEN_SZ; ++g)
        {
        // display progress in app header
        wsprintf(buf,"Forge (loop: %u of %u)",g,GEN_SZ);
        SetWindowText(wdw,buf);

        // calculate fitness for x values
        best  = DBL_MIN;
        lowf  = DBL_MAX;
        ibest = 0;

        for (i = 0; i < POP_SZ; ++i)
            {
            switch (EQ_ID)
                {
                case 0:
                    fit[i] = 1.0 - FitnessF6(x[i],y[i]);
                    break;
                case 1:
                    fit[i] = 1.0 - FitnessF7(x[i],y[i]);
                    break;
                case 2:
                    fit[i] = 1.0 - FitnessF8(x[i],y[i]);
                    break;
                case 3:
                    fit[i] = FitnessCust(x[i],y[i]);
                }

            fit[i] = SigDig(fit[i],SIG_DIG);

            // track best fitness
            if (fit[i] > best)
                {
                best  = fit[i];
                ibest = i;
                }

            // track lowest fitness
            if (fit[i] < lowf)
                lowf = fit[i];
            }

        // display best solution so far
        if ((g % gaoc.GetReptFreq()) == 0)
            {
            buffer << setw(4) << g << ": (" << x[ibest]
                   << "," << y[ibest] << ") fit = "
                   << best << "\r\n";
            }

        // sort by fitness if linear normalization
        if (FSA_LINEAR == gaoc.GetFitAlgor())
            {
            // shell sort three arrays in order of fitness
            fitn = gaoc.GetFitLinBase();

            for (inc = 1; inc <= POP_SZ / 9; inc = 3 * inc + 1) ;

            for ( ; inc > 0; inc /= 3)
                {
                for (i = inc + 1; i <= POP_SZ; i += inc)
                    {
                    vf = ptrf[i];
                    vx = ptrx[i];
                    vy = ptry[i];

                    j  = i;

                    while ((j > inc) && (ptrf[j - inc] < vf))
                        {
                        ptrf[j] = ptrf[j - inc];
                        ptrx[j] = ptrx[j - inc];
                        ptry[j] = ptry[j - inc];

                        j -= inc;
                        }

                    ptrf[j] = vf;
                    ptrx[j] = vx;
                    ptry[j] = vy;
                    }
                }
            }

        for (i = 0; i < POP_SZ; ++i)
            {
            // fitness scaling
            if (gaoc.GetFitScale())
                {
                switch (gaoc.GetFitAlgor())
                    {
                    case FSA_EXPON:
                        fit[i] = sqr(fit[i] + 1.0);
                        break;
                    case FSA_WINDOW:
                        fit[i] -= lowf;
                        break;
                    case FSA_LINEAR:
                        {
                        fit[i] = fitn;

                        if (fitn > gaoc.GetFitLinMin())
                            {
                            fitn -= gaoc.GetFitLinDec();

                            if (fitn < gaoc.GetFitLinMin())
                                fitn = gaoc.GetFitLinMin();
                            }
                        }
                    }
                }
            }

        // create roulette wheel for reproduction selection
        RouletteWheel<double> * sel;
        sel = new RouletteWheel<double> (POP_SZ,fit);

        if (sel == NULL)
            {
            buffer << "Failed to allocate roulette wheel\r\n";
            return;
            }

        // if elitist, include best from orig. population
        if (gaoc.GetElitist())
            {
            if (FSA_LINEAR == gaoc.GetFitAlgor())
                {
                xnew[0] = x[0];
                ynew[0] = y[0];
                }
            else
                {
                xnew[0] = x[ibest];
                ynew[0] = y[ibest];
                }

            i = 1;
            }
        else
            i = 0;

        // create new population of x's
        for ( ; i < POP_SZ; ++i)
            {
            // create a new x
            p1 = sel->GetIndex();

            if (gaoc.GetCrossX()
            &&  (devgen() <= gaoc.GetCrossRate()))
                {
                p2 = sel->GetIndex();
                xnew[i] = Crossover(x[p1],x[p2]);
                }
            else
                xnew[i] = x[p1];

            // create a new y
            if (gaoc.GetCrossB())
                p1 = sel->GetIndex();

            if (gaoc.GetCrossY()
            &&  (devgen() <= gaoc.GetCrossRate()))
                {
                p2 = sel->GetIndex();
                ynew[i] = Crossover(y[p1],y[p2]);
                }
            else
                ynew[i] = y[p1];

            // mutate X
            if (gaoc.GetMutateX())
                {
                if (gaoc.GetMuteLoop())
                    {
                    while (devgen() <= gaoc.GetMuteRate())
                        xnew[i] = fmute.Mutate(xnew[i]);
                    }
                else
                    {
                    if (devgen() <= gaoc.GetMuteRate())
                        xnew[i] = fmute.Mutate(xnew[i]);
                    }
                }

            // mutate Y
            if (gaoc.GetMutateY())
                {
                if (gaoc.GetMuteLoop())
                    {
                    while (devgen() <= gaoc.GetMuteRate())
                        ynew[i] = fmute.Mutate(ynew[i]);
                    }
                else
                    {
                    if (devgen() <= gaoc.GetMuteRate())
                        ynew[i] = fmute.Mutate(ynew[i]);
                    }
                }

            // make sure x & y fit ranges
            if (xnew[i] > gaoc.GetXMax())
                xnew[i] = gaoc.GetXMax();

            if (xnew[i] < gaoc.GetXMin())
                xnew[i] = gaoc.GetXMin();

            if (ynew[i] > gaoc.GetYMax())
                ynew[i] = gaoc.GetYMax();

            if (ynew[i] < gaoc.GetYMin())
                ynew[i] = gaoc.GetYMin();

            // truncate digits
            xnew[i] = SigDig(xnew[i],SIG_DIG);
            ynew[i] = SigDig(ynew[i],SIG_DIG);
            }

        // remove roulette wheel
        delete sel;

        // copy new population
        memcpy(x,xnew,POP_SZ * sizeof(double));
        memcpy(y,ynew,POP_SZ * sizeof(double));
        }

    // delete buffers
    delete [] fit;
    delete [] ynew;
    delete [] y;
    delete [] xnew;
    delete [] x;

    // restore app window name
    SetWindowText(wdw,"Forge");
    }
void CMPGA::NextGen() {
   ++m_unCurrentGeneration;
   Selection();
   Crossover();
   Mutation();
}
Exemple #23
0
//------------------------------------- Epoch ----------------------------
//
//  This function performs one epoch of the genetic algorithm and returns 
//  a vector of pointers to the new phenotypes
//------------------------------------------------------------------------
vector<CNeuralNet*> Cga::Epoch(const vector<double> &FitnessScores)
{
  //first check to make sure we have the correct amount of fitness scores
  if (FitnessScores.size() != m_vecGenomes.size())
  {
    MessageBox(NULL,"Cga::Epoch(scores/ genomes mismatch)!","Error", MB_OK);
  }

  //reset appropriate values and kill off the existing phenotypes and
  //any poorly performing species
  ResetAndKill();

  //update the genomes with the fitnesses scored in the last run
  for (int gen=0; gen<m_vecGenomes.size(); ++gen)
  {
    m_vecGenomes[gen].SetFitness(FitnessScores[gen]);
  }

  //sort genomes and keep a record of the best performers
  SortAndRecord();

  //separate the population into species of similar topology, adjust
  //fitnesses and calculate spawn levels
  SpeciateAndCalculateSpawnLevels();

  //this will hold the new population of genomes
  vector<CGenome> NewPop;

  //request the offspring from each species. The number of children to 
  //spawn is a double which we need to convert to an int. 
  int NumSpawnedSoFar = 0;

  CGenome baby;

  //now to iterate through each species selecting offspring to be mated and 
  //mutated	
  for (int spc=0; spc<m_vecSpecies.size(); ++spc)
  {
    //because of the number to spawn from each species is a double
    //rounded up or down to an integer it is possible to get an overflow
    //of genomes spawned. This statement just makes sure that doesn't
    //happen
    if (NumSpawnedSoFar < CParams::iNumSweepers)
    {
      //this is the amount of offspring this species is required to
      // spawn. Rounded simply rounds the double up or down.
      int NumToSpawn = Rounded(m_vecSpecies[spc].NumToSpawn());

      bool bChosenBestYet = false;

      while (NumToSpawn--)
      {
        //first grab the best performing genome from this species and transfer
        //to the new population without mutation. This provides per species
        //elitism
        if (!bChosenBestYet)
        {         
          baby = m_vecSpecies[spc].Leader();

          bChosenBestYet = true;
        }

        else
        {
          //if the number of individuals in this species is only one
          //then we can only perform mutation
          if (m_vecSpecies[spc].NumMembers() == 1)
          {         
            //spawn a child
            baby = m_vecSpecies[spc].Spawn();
          }

          //if greater than one we can use the crossover operator
          else
          {
            //spawn1
            CGenome g1 = m_vecSpecies[spc].Spawn();

            if (RandFloat() < CParams::dCrossoverRate)
            {

              //spawn2, make sure it's not the same as g1
              CGenome g2 = m_vecSpecies[spc].Spawn();

              //number of attempts at finding a different genome
              int NumAttempts = 5;

              while ( (g1.ID() == g2.ID()) && (NumAttempts--) )
              {  
                g2 = m_vecSpecies[spc].Spawn();
              }

              if (g1.ID() != g2.ID())
              {
                baby = Crossover(g1, g2);
              }
            }

            else
            {
              baby = g1;
            }
          }

          
          ++m_iNextGenomeID;

          baby.SetID(m_iNextGenomeID);

          //now we have a spawned child lets mutate it! First there is the
          //chance a neuron may be added
          if (baby.NumNeurons() < CParams::iMaxPermittedNeurons)
          {      
            baby.AddNeuron(CParams::dChanceAddNode,
                           *m_pInnovation,
                           CParams::iNumTrysToFindOldLink);
          }

          //now there's the chance a link may be added
          baby.AddLink(CParams::dChanceAddLink,
                       CParams::dChanceAddRecurrentLink,
                       *m_pInnovation,
                       CParams::iNumTrysToFindLoopedLink,
                       CParams::iNumAddLinkAttempts);

          //mutate the weights
          baby.MutateWeights(CParams::dMutationRate,
                             CParams::dProbabilityWeightReplaced,
                             CParams::dMaxWeightPerturbation);

          baby.MutateActivationResponse(CParams::dActivationMutationRate,
                                        CParams::dMaxActivationPerturbation);
        }

        //sort the babies genes by their innovation numbers
        baby.SortGenes();

        //add to new pop
        NewPop.push_back(baby);

        ++NumSpawnedSoFar;

        if (NumSpawnedSoFar == CParams::iNumSweepers)
        {        
          NumToSpawn = 0;
        }

      }//end while
       
    }//end if
     
  }//next species


  //if there is an underflow due to the rounding error and the amount
  //of offspring falls short of the population size additional children
  //need to be created and added to the new population. This is achieved
  //simply, by using tournament selection over the entire population.
  if (NumSpawnedSoFar < CParams::iNumSweepers)
  {

    //calculate amount of additional children required
    int Rqd = CParams::iNumSweepers - NumSpawnedSoFar;

    //grab them
    while (Rqd--)
    {
      NewPop.push_back(TournamentSelection(m_iPopSize/5));
    }
  }

  //replace the current population with the new one
  m_vecGenomes = NewPop;

  //create the new phenotypes
  vector<CNeuralNet*> new_phenotypes;

  for (gen=0; gen<m_vecGenomes.size(); ++gen)
  {
    //calculate max network depth
    int depth = CalculateNetDepth(m_vecGenomes[gen]);
    
    CNeuralNet* phenotype = m_vecGenomes[gen].CreatePhenotype(depth);

    new_phenotypes.push_back(phenotype);
  }

  //increase generation counter
  ++m_iGeneration;

  return new_phenotypes;
}
int main(int argc , char *argv[]){
	/* Variable */
	char filename[64];
	int my_rank;
	double startTime=0.0 , totalTime=0.0;
	int max_generation,switching_num;
	float crossover_rate,mutation_rate;
	int **Local_population;
	//int *pop_weight = malloc(max_pop*sizeof(int));
	int i,j,k;
	/* Initialize MPI */
	MPI_Init(&argc,&argv);
	/* Set MPI  */
	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
	MPI_Comm_size(MPI_COMM_WORLD,&comm_sz);
	/* Start time (rank = 0)*/
	if(my_rank == 0){
		startTime = MPI_Wtime();
		/* Read from the file */
	}
	/* Read from the parameter file */
   	 char *para_file = argv[1];
   	 FILE *fpara = fopen(para_file,"r");
   	 /* Format : max generation , Crossover rate , Mutation rate , Switching number => for every process !*/
   	 fscanf(fpara , "%d %f %f %d %d %s" , &max_generation , &crossover_rate , &mutation_rate , &switching_num ,&max_pop , filename);
   	 int *pop_weight = malloc(max_pop*sizeof(int));
   	 FILE *fp = fopen(filename , "r");
   	 //printf("Max : %d ; cross rate : %f ; mutation rate : %f ; switching_num : %d \n", max_generation , crossover_rate , mutation_rate , switching_num);
	/* Read in the size of matrix => Get "city number" */
	city_number = (filename[strlen(filename)-7] - 48) + 10*(filename[strlen(filename)-8]-48);
    	path_cost = allocate_dimension(city_number,city_number);
    	/* Read in the matrix */
    	for(i=0;i<city_number;i++){
        	for(j=0;j<city_number;j++){
        		fscanf(fp , "%5d" , &path_cost[i][j]);
        	}
   	}
   	// Initialize
   	for(i = 0 ; i < comm_sz ; i++){
   		if(my_rank == i){
	   	 /* Build Population , taking sample from a line of data , number 20~50 sequences (define on the top)*/ 
	   	Local_population = random_population_generation(i,max_pop,city_number);
	   	 /* Setting Every  Weight of each sequence of array*/
	   	weight_calculation(Local_population,pop_weight);
		}
   	 }
	// check result => OK ; check every population is different => OK
	// check for every weight of population sequence => OK
   	 if(my_rank == 0){
   	 	for(j=0;j<max_pop;j++){
   	 		for(k=0;k<city_number;k++){
   	 			printf("%d " , Local_population[j][k]);
   	 		}
   	 		printf("\n");
   	 	}
   	}
   	//int **sendswitching = allocate_dimension(switching_num , city_number);
	//int **recvswitching = allocate_dimension(switching_num , city_number);
   	 /* Get the generation count */
   	for(i = 0 ; i < max_generation ; i++){
   		/* Recompute the pop_weight */
   	 	weight_calculation(Local_population,pop_weight);
	   	// Calculate "Crossover"
	   	Crossover(Local_population,pop_weight,crossover_rate);
		// Calculate "Mutation"
		Mutation(Local_population,mutation_rate);
		// Calculate "switching_num" and add to population
		// Select the "max_pop" number and make it to next generation population
		// MPI_SEND , MPI_RECV
		Switch_Select(my_rank,Local_population,switching_num);
   	 }
   	 if(my_rank == 0){
   	 	printf("\n");
   	 	for(j=0;j<max_pop;j++){
   	 		for(k=0;k<city_number;k++){
   	 			printf("%d " , Local_population[j][k]);
   	 		}
   	 		printf("\n");
   	 	}
   	 }
   	 // Choosing the best result of each process
   	 //if(my_rank == 0){
   	 weight_calculation(Local_population,pop_weight); 
   	 int minimal = 20000 , result;
   	 for(i = 0; i < max_pop ; i++){
   	 	if(minimal > pop_weight[i]){
 			minimal = pop_weight[i];
 	 		result = i;
   		}
   	 }
   	printf("My rank %d The Best answer is %d\n",my_rank, minimal);
   	printf("\n");
   	
   	int *compare = malloc(city_number*sizeof(int));
   	 // And choosing the best result among every process's best result , ALL Send to my_rank = 0
   	 if(my_rank != 0){
   	 	MPI_Send(Local_population[result] , city_number , MPI_INT , 0 , my_rank , MPI_COMM_WORLD);
   	 }
   	 if(my_rank == 0){
   	 	for(i = 1;i<comm_sz;i++){
   	 		MPI_Recv(compare,city_number , MPI_INT , i , i , MPI_COMM_WORLD,MPI_STATUS_IGNORE);
   	 		int weight=0;
   	 		for(j = 0; j <city_number-1 ; j++){
   	 			weight += path_cost[compare[j]][compare[j+1]];
   	 		}
   	 		if(minimal > weight){
   	 			minimal = weight;
   	 		}
   	 	}
   	 	printf("The Best answer among process is %d\n",minimal);
   	 }
   	 
   	 /* End time (rank = 0) */
   	 if(my_rank == 0){
   	 	totalTime = MPI_Wtime() - startTime;
   	 	printf("Total Time is %f \n" , totalTime);
   	 }
   	 /* Terminate MPI */
   	MPI_Finalize();
    	return 0;
}
/**
* C-routine to reach a floatvalue using a genetic model<br>
* bugs: none found<br>
* @param target floatvalue that serves as a target<br>
* @param maxiter maximum number of itterations<br>
*/
int SolveNumber(float target, int maxiter){
    while (maxiter > 0){
    //storage for our population of chromosomes.
    bytechromosome Population[POP_SIZE];
	  //first create a random population, all with zero fitness.
	  for (int i=0; i<POP_SIZE; i++){
		  Population[i].setbits(GetRandomBits(CHROMO_LENGTH));
		  Population[i].setfitness(0.0f);
	  }
	  int GenerationsRequiredToFindASolution = 0;
	  //we will set this flag if a solution has been found
	  bool bFound = false;
	  //enter the main GA loop
	  while(!bFound){
		  //this is used during roulette wheel sampling
		  float TotalFitness = 0.0f;
		  // test and update the fitness of every chromosome in the population
		  for (int i=0; i<POP_SIZE; i++){
			  Population[i].setfitness(AssignFitness(Population[i].getbits(), (int)target));
			  TotalFitness += Population[i].getfitness();
		  }
		  // check to see if we have found any solutions (fitness will be 999)
		  for (int i=0; i<POP_SIZE; i++){
			  if (Population[i].getfitness() == 999.0f){
          printf("Solution found in %d generations!\n",GenerationsRequiredToFindASolution);
				  PrintChromo(Population[i].getbits());
				  bFound = true;
          break;
			  }
		  }
		  // create a new population by selecting two parents at a time and creating offspring
      // by applying crossover and mutation. Do this until the desired number of offspring
      // have been created.
		  //define some temporary storage for the new population we are about to create
		  bytechromosome temp[POP_SIZE];
		  int cPop = 0;
		  //loop until we have created POP_SIZE new chromosomes
		  while (cPop < POP_SIZE){
			  // we are going to create the new population by grabbing members of the old population
			  // two at a time via roulette wheel selection.
			  string offspring1 = Roulette((int)TotalFitness, Population);
			  string offspring2 = Roulette((int)TotalFitness, Population);
        //add crossover dependent on the crossover rate
        Crossover(offspring1, offspring2);
			  //now mutate dependent on the mutation rate
			  Mutate(offspring1);
			  Mutate(offspring2);
			  //add these offspring to the new population. (assigning zero as their fitness scores)
			  temp[cPop++] = bytechromosome(offspring1, 0.0f);
			  temp[cPop++] = bytechromosome(offspring2, 0.0f);
		  }//end loop
		  //copy temp population into main population array
		  for (int i=0; i<POP_SIZE; i++){
			  Population[i] = temp[i];
      }
		  GenerationsRequiredToFindASolution++;
		  if (GenerationsRequiredToFindASolution > MAX_ALLOWABLE_GENERATIONS){
			  printf("No solutions found this run!\n");
			  bFound = true;
		  }
	  }
    printf("\n");
    maxiter--;
  }//end while
  return 0;
}