Advertisement
Bassone

Genetic Algo Assignment 2

Mar 31st, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <math.h>
  4. using namespace std;
  5.  
  6. struct Chromosome
  7. {
  8.     float fitness = 100000 ;
  9.     vector <float> Genes ; // a0 , a1 , a2 , ...... , an   = Polynomial Degree + 1
  10. };
  11.  
  12. struct Point
  13. {
  14.     float x ;
  15.     float y ;
  16. };
  17.  
  18. int const numIndividuals = 1000 ;
  19. int const numGenerations = 10 ;
  20. int numPoints ;
  21. int numCases ;
  22. int PolyDeg ;
  23. float Total_Fitness ;
  24.  
  25. vector <Point> Points ;
  26.  
  27. vector <Chromosome> Generation ;
  28. vector <Chromosome> nxtGeneration ;
  29.  
  30.  
  31. void read()
  32. {
  33.     freopen("input.txt", "rt", stdin);
  34.     cin >> numCases ;
  35.     for (int c = 0 ; c<numCases ; c++)
  36.    {
  37.        cin >> numPoints >> PolyDeg ;
  38.        Point Temp ;
  39.        for (int j = 0 ; j<numPoints ; j++)
  40.        {
  41.            cin >> Temp.x >> Temp.y ;
  42.            Points.push_back(Temp);
  43.        }
  44.    }
  45.  
  46. }
  47.  
  48.  
  49.  
  50. void Intial_Population()
  51. {
  52.     Generation.resize(numIndividuals);
  53.      for (int i = 0 ; i<numIndividuals ; i++)
  54.         {
  55.  
  56.             Generation[i].Genes.resize(PolyDeg+1) ;
  57.  
  58.             for ( int j = 0 ; j <= PolyDeg ; j++)
  59.              {
  60.  
  61.                float r = -10 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(10-(-10)))); //Generate Random Float Number between -10 to 10
  62.                Generation[i].Genes[j] = r ;
  63.             }
  64.         }
  65. }
  66.  
  67.  
  68.  
  69.  
  70. void CalcFitness ()
  71. {
  72.   float error = 0 ;
  73.   float sum = 0 ;
  74.   float sum2 = 0 ;
  75.   Total_Fitness = 0 ;
  76.  
  77.   for ( int z = 0 ; z < numIndividuals ; z++)
  78.   {
  79.       for ( int i = 0 ; i < numPoints ; i++)
  80.       {
  81.           float yCalc = 0 ;
  82.           float x = Points[i].x ;
  83.  
  84.           for ( int j = 0 ; j <= PolyDeg ; j++)
  85.           {
  86.               yCalc = (float)(yCalc + (Generation[z].Genes[j])* (pow(x,j))) ;
  87.  
  88.  
  89.           }
  90.           sum = (float)((yCalc) - Points[i].y) ;   // Sum = Ycalc - Yactual
  91.           sum2 = (pow(sum,2)); //Sum2 = sum^2
  92.  
  93.       }
  94.       float val = 1 / (float) numPoints;
  95.  
  96.       error = (val*sum2) ;  // Error = 1/n MSE
  97.  
  98.       Generation[z].fitness = error ;
  99.       Total_Fitness += Generation[z].fitness ;
  100.   }
  101. }
  102.  
  103.  
  104. int Roulette ()
  105. {
  106.  
  107.     float r = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/Total_Fitness)); //Generate Random Number Between 0 and Total Case Fitness
  108.     int sum = 0 ;
  109.     for ( int i = 0 ; i < numIndividuals ; ++i)
  110.     {
  111.  
  112.        sum += Generation[i].fitness;
  113.  
  114.        if ( sum > r ) // The First Chromosome to affect the fitness will be returned
  115.        {
  116.            return i ;
  117.        }
  118.     }
  119.     return -1 ;
  120. }
  121.  
  122.  
  123. void Mutate (Chromosome & Chr)
  124. {
  125.     float Upper = 10.0 , Lower = -10.0 ,dUpper , dLower ;
  126.     for (int i = 0; i <Chr.Genes.size(); ++i)
  127.     {
  128.         int m = rand() % 1000;
  129.         if (m < 1)
  130.           {
  131.             dUpper = Upper - Chr.Genes[i] ;
  132.             dLower = Chr.Genes[i] - Lower ;
  133.  
  134.             int r = rand() % 10;
  135.             if (r < 5 )
  136.             {
  137.                float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/dUpper));
  138.                Chr.Genes[i] += r2 ;
  139.             }
  140.             else
  141.             {
  142.                float r3 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/dLower));
  143.                Chr.Genes[i] -= r3 ;
  144.             }
  145.           }
  146.     }
  147.  
  148. }
  149.  
  150.  
  151. void CrossOver (int Cindex1 , int Cindex2)
  152. {
  153.     Chromosome Chr1 = Generation[Cindex1]; //Takes First Chromosome From the population
  154.     Chromosome Chr2 = Generation[Cindex2]; //Takes Second Chromosome From the population
  155.     int r =  rand()%10 ; //Generate Random Number from 0 to 10
  156.  
  157.     if ( r < 6 )
  158.     {
  159.  
  160.     int r = rand()%PolyDeg; //Generate Random Number from 0 to Number of Items
  161.     r++;
  162.     for ( int i = 0 ; i < r ; i++)
  163.         swap(Chr1.Genes[i],Chr2.Genes[i]);
  164.  
  165.     Mutate(Chr1); //Makes Mutation To First Chromosome
  166.     Mutate(Chr2); //Makes Mutation To Second Chromosome
  167.     }
  168.  
  169.     nxtGeneration.push_back(Chr1); //Store The Chromosome in The offspring
  170.     nxtGeneration.push_back(Chr2); //Store The Chromosome in The offspring
  171. }
  172.  
  173.  
  174. void Reproduce()
  175.  {
  176.  
  177.     while (nxtGeneration.size() < numIndividuals) //Until offspring size is equal to number of individuals
  178.         {
  179.         int chromosome_index1 = Roulette(); //choose random chromosome
  180.         int chromosome_index2 = Roulette(); //choose random chromosome
  181.         CrossOver(chromosome_index1, chromosome_index2); //Makes crossover between them
  182.  
  183.         }
  184. }
  185.  
  186.  
  187. int Get_Fit()
  188. {
  189.     int best_fitness = 1000000, index = -1;
  190.     for (int i = 0; i < numIndividuals; ++i)
  191.         {
  192.         if (best_fitness > Generation[i].fitness)
  193.         {
  194.             best_fitness = Generation[i].fitness;
  195.             index = i;
  196.         }
  197.     }
  198.     return index;
  199. }
  200.  
  201.  
  202. void Print ()
  203. {
  204.     int BestFit = Get_Fit();
  205.     float Result = Generation[BestFit].fitness;
  206.  
  207.     for ( int i = 0 ; i<= PolyDeg ; i++)
  208.         cout << Generation[BestFit].Genes[i] << ", ";
  209.  
  210.     cout << endl << "It's Fitness : " << Result << endl << endl ;
  211. }
  212.  
  213.  
  214.  
  215. void Compute ()
  216. {
  217.  
  218.     read(); // First Read The Chromosome from the file
  219.  
  220.     for (int c = 0 ; c < numCases ; c++)
  221.     {
  222.         nxtGeneration.clear(); //To Empty the offspring
  223.  
  224.         Intial_Population(); // Generates The Initial population
  225.  
  226.         int Gen = 0 ;
  227.         while ( Gen < numGenerations) //Continue Until I Reach Maximum Generation Number
  228.         {
  229.             if ( Gen != 0 )
  230.             {
  231.                 Generation = nxtGeneration ; //Replace the old generation chromosomes with the offspring ones
  232.                 nxtGeneration.clear(); //And Empty the offspring
  233.             }
  234.             CalcFitness(); // Calculate fitness of each chromosome
  235.             Gen++ ;
  236.             if ( Gen < numGenerations)
  237.             {
  238.                 Reproduce(); // Makes New Generation
  239.             }
  240.  
  241.  
  242.         }
  243.  
  244.         Print(); // Print This Case Output
  245.     }
  246. }
  247.  
  248.  
  249. int main()
  250. {
  251.  
  252.  
  253.     Compute();
  254.  
  255.  
  256.     return 0;
  257. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement