DryTonz

Genetic algorithm

Oct 24th, 2020 (edited)
1,628
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #This genetic algorithm is kinda silly, but it makes an "imaginary" house where all the materials have its own strength which will translate to fitness but, materials require structure so it requires nails or tape. So the algorithm will try to make a balance of all materials for the best possible score.
  2.  
  3. #Make a script called whatever you want, and use following.
  4. import Population
  5. import time
  6. import math
  7.  
  8. GeneLen = 49
  9. PopulationSize = 25
  10. MutationRate = 0.01
  11.  
  12. Population = Population.Population(PopulationSize, MutationRate, GeneLen)
  13.  
  14. Score = 0
  15. Materials = None
  16.  
  17. t = time.time()
  18.  
  19. for i in range(25):
  20.  
  21.     Population.NaturalSelection()
  22.     Population.NextGen()
  23.     Population.CalcFitness()
  24.  
  25.     Score, Materials = Population.BestIndevidual()
  26.     print( "Avarage:"+str(Population.Avarage),"Generation:"+str(Population.Gen))
  27.  
  28.  
  29. print("")
  30. print("_______________Result________________")
  31. print("Generation:"+str(Population.Gen))
  32. print("Worst Score:"+str(Population.WorstScore))
  33. print("Avarage:"+str(Population.Avarage))
  34. print("Best Score:"+str(Score), "Record:"+str(Population.Record))
  35. print("Time Taken(Seconds):"+str(math.floor(time.time()-t)))
  36. print("_______________DATA________________")
  37. print("Generation Size:"+str(PopulationSize))
  38. print("Mutation Rate(%):"+str(MutationRate*100))
  39. print("Material Slots:"+str(GeneLen))
  40. print("_______________Materials________________")
  41. MaterialsInfo = Materials.Content()
  42. for i in MaterialsInfo:
  43.     print(i+":", MaterialsInfo[i])
  44.  
  45. #Make a new script called DNA and paste following, note all scripts needs to be in the same folder.
  46. import Materials
  47. import random
  48. import math
  49.  
  50. Materials = [Materials.Nail, Materials.SteelNail, Materials.Stone, Materials.Wood, Materials.Paper, Materials.Grass, Materials.Metall, Materials.Tape, Materials.Graphene, Materials.Steel, Materials.Glass, Materials.Carbonfiber, Materials.MagicMix, Materials.Plastic]
  51.  
  52. class DNA:
  53.     def __init__(self, length):
  54.         self.Gene = []
  55.         self.length = length
  56.         for i in range(0, length):
  57.             list.append(self.Gene, Materials[random.randint(0, len(Materials)-1)]())
  58.  
  59.     def Content(self):
  60.         MaterialsCount = {"Wood": 0,
  61.         "Nail": 0,
  62.         "Metall": 0,
  63.         "Stone": 0,
  64.         "Paper": 0,
  65.         "Grass": 0,
  66.         "Tape": 0,
  67.         "Steel": 0,
  68.         "Glass": 0,
  69.         "Carbonfiber": 0,
  70.         "Graphene": 0,
  71.         "MagicMix": 0,
  72.         "Plastic": 0,
  73.         "SteelNail": 0
  74.         }
  75.         for i in self.Gene:
  76.             MaterialsCount[i.__class__.__name__] += 1
  77.         return MaterialsCount
  78.            
  79.     def CalcFitness(self):
  80.         Strength = 0
  81.         Structure = 0
  82.         for i in self.Gene:
  83.             Strength += i.Strength
  84.             Structure += i.Structure
  85.         Durability = Strength*0.8/100
  86.         Score = ((Strength+(Structure*1.5))*Durability)/364#durability
  87.         self.Fitness = Score
  88.  
  89.     def Crossover(self, Partner):
  90.         Cross = math.floor((len(Partner.Gene)-1)/2)
  91.         child = DNA(self.length)
  92.         for i in range(self.length-1):
  93.             if i > Cross:
  94.                 child.Gene[i] = self.Gene[i]
  95.             else:
  96.                 child.Gene[i] = Partner.Gene[i]
  97.         return child
  98.  
  99.     def Mutate(self, MutationRate):
  100.         for i in range(len(self.Gene)-1):
  101.             if random.random() <= MutationRate:
  102.                 self.Gene[i] = Materials[random.randint(0, len(Materials)-1)]()
  103.  
  104.  
  105. #Make a new script called Materials and paste following, the values on these can be customized if you want.
  106.  
  107. class Wood():
  108.     def __init__(self):
  109.         self.Strength = 65
  110.         self.Structure = -30
  111.  
  112. class Stone():
  113.     def __init__(self):
  114.         self.Strength = 175
  115.         self.Structure = -90
  116.    
  117. class Nail():
  118.     def __init__(self):
  119.         self.Strength = 5
  120.         self.Structure = 100
  121.  
  122. class Metall():
  123.     def __init__(self):
  124.         self.Strength = 155
  125.         self.Structure = -65
  126.  
  127. class Grass():
  128.     def __init__(self):
  129.         self.Strength = 8
  130.         self.Structure = -3
  131.    
  132. class Tape():
  133.     def __init__(self):
  134.         self.Strength = 1
  135.         self.Structure = 40
  136.  
  137. class Paper():
  138.     def __init__(self):
  139.         self.Strength = 20
  140.         self.Structure = -10
  141.  
  142. class Glass():
  143.     def __init__(self):
  144.         self.Strength = 35
  145.         self.Structure = -20
  146.    
  147. class Graphene():
  148.     def __init__(self):
  149.         self.Strength = 100
  150.         self.Structure = 5
  151.  
  152. class Carbonfiber():
  153.     def __init__(self):
  154.         self.Strength = 85
  155.         self.Structure = -15
  156.  
  157. class Steel():
  158.     def __init__(self):
  159.         self.Strength = 250
  160.         self.Structure = -110
  161.    
  162. class Plastic():
  163.     def __init__(self):
  164.         self.Strength = 70
  165.         self.Structure = -40
  166.  
  167. class MagicMix():
  168.     def __init__(self):
  169.         self.Strength = 199.99
  170.         self.Structure = -79
  171.  
  172. class SteelNail:
  173.     def __init__(self):
  174.         self.Strength = 15
  175.         self.Structure = 210
  176.  
  177.  
  178. #Make a new script called Population and paste following.
  179.  
  180. import DNA
  181. import math
  182. import random
  183.  
  184. class Population:
  185.     def __init__(self, Size, MR, Length):
  186.         self.MutationRate = MR
  187.         self.Size = Size
  188.         self.Population = []
  189.         self.MatingPool = []
  190.         self.Gen = 0
  191.         self.Length = Length
  192.         self.WorstScore = 0
  193.         self.WorstScore2 = 0
  194.         self.Record = 0
  195.         self.Record2 = None
  196.         for i in range(Size-1):
  197.             self.Population.append(DNA.DNA(self.Length))
  198.         self.CalcFitness()
  199.  
  200.     def CalcFitness(self):
  201.         for i in self.Population:
  202.             i.CalcFitness()
  203.    
  204.     def NaturalSelection(self):
  205.         self.MatingPool = []
  206.         self.MaxFitness = 0
  207.         totallScore = 0
  208.         for i in self.Population:
  209.             if i.Fitness > self.MaxFitness:
  210.                 MaxFitness = i.Fitness
  211.             totallScore += i.Fitness
  212.         avarage = totallScore/len(self.Population)
  213.        
  214.         for i in self.Population:
  215.             normalized = (i.Fitness-0.1)/(MaxFitness-0.1)
  216.             x = math.floor(normalized * 100)
  217.             if i.Fitness > avarage:
  218.                 for n in range(0, x):
  219.                     self.MatingPool.append(i)
  220.        
  221.     def NextGen(self):
  222.         for i in range(0, len(self.Population)-1):
  223.             x = self.MatingPool[random.randint(0, len(self.MatingPool)-1)]
  224.             y = self.MatingPool[random.randint(0, len(self.MatingPool)-1)]
  225.             child = x.Crossover(y)
  226.             child.Mutate(self.MutationRate)
  227.             self.Population[i] = child
  228.         self.Gen += 1
  229.    
  230.     def BestIndevidual(self):
  231.         Best = 0
  232.         Best2 = None
  233.         TotallScore = 0
  234.         for i in self.Population:
  235.             TotallScore += i.Fitness
  236.             if self.WorstScore == 0:
  237.                 self.WorstScore = i.Fitness
  238.                 self.WorstScore2 = i
  239.             elif self.WorstScore > i.Fitness:
  240.                 self.WorstScore = i.Fitness
  241.                 self.WorstScore2 = i
  242.             if i.Fitness > Best:
  243.                 Best = i.Fitness
  244.                 Best2 = i
  245.         self.Avarage = TotallScore/len(self.Population)
  246.         if Best > self.Record:
  247.             self.Record = Best
  248.             self.Record2 = Best2
  249.         return Best, Best2
  250.  
  251.  
RAW Paste Data