Advertisement
Guest User

Untitled

a guest
Jan 25th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.06 KB | None | 0 0
  1. class   GenAlgo :  """
  2.   Class for commmon genetic algo operations
  3.   """
  4.    @staticmethod
  5.  def   mutation (chromosome, mutation_rate= 50 ) :  """
  6.       Changes one bit of chromosome with mutation_rate
  7.       probability
  8.       :param chromosome: chromosome to mutate
  9.       :param mutation_rate probability of mutation from 0 to 100
  10.       :return: mutated chromosome
  11. """
  12. n = len(chromosome)
  13. prob = rnd.randint( 0 ,  100 )  if  prob > mutation_rate:
  14. index = rnd.randint( 0 , n -  1 ) chrom = list(chromosome)
  15.  if  chrom[index] ==  '0' :
  16. chrom[index] =  '1'  else :
  17. chrom[index] =  '0'  return   '' .join(chrom)
  18.  return  chromosome
  19.    @staticmethod
  20.  def   roulette_wheel_weights (weights):   """
  21.       Calculates lst of probabilities for given cliques
  22.       :param weights: weights of candidates
  23.       :return: list of probabilities for candidates
  24.       """
  25. total =  0
  26.  for  p =
  27. w  in  weights:
  28. total += w
  29. [w / total  for  w  in  weights] i  in  range( 1 , len(p)):
  30. p[i] += p[i -  1]
  31.  for   return  p
  32.  24
  33.  @staticmethod
  34.  def   chose_parent (weights) :  """
  35.    Return random parent's number according to given probabilities
  36.    :param weights: list of probabilities
  37.    """
  38.     n = len(weights)
  39. r = rnd.random()  for  i  in  range(n):
  40.  if  weights[i] > r:  return  i
  41. @staticmethod
  42.  def   multipoint_crossover (parent1, parent2, n) :  """
  43.    Performs n-part crossover operation on two binary string.
  44.    :param parent1: first binary string
  45.    :param parent2: second binary string
  46.    :param n: number of parts to split on
  47.    :return: pair of crossovered string
  48.    """
  49.     chrom_len = len(parent1)
  50.     points = []
  51.  while  len(points) < n:
  52. cur = rnd.randint( 1,  chrom_len)  if  cur  not  i  n  points:
  53.             points.append(cur)
  54. points = sorted(points) prev =  0
  55. swap =  True
  56. p1 = list(parent1) p2 = list(parent2)  for  p  in  points:
  57.  if  swap:
  58.  for  j  in  range(prev, p):
  59.                 swp = p1[j]
  60.                 p1[j] = p2[j]
  61.                 p2[j] = swp
  62. swap =  not  swap prev = p
  63.  25
  64.   return   '' .join(p1),  '' .join(p2)
  65.    @staticmethod
  66.  def   replace_clique_fit (child1, child2, parent1, parent2, population) :  """
  67.       Replace operator. Chose best child and try to replace parents of
  68. worst
  69.       beast in population
  70.       :param child1: first child
  71.       :param child2: second child
  72.       :param parent1: first parent
  73.       :param parent2: second parent
  74.       :param population: whole population
  75.       :param adj_list: adjast list of graph
  76.       :param weights: weights of population
  77.       :return: 1 if operation susccessfull, 0 otherwise
  78. """
  79.        child_fit1 = fit_just_nodes(child1)
  80.        child_fit2 = fit_just_nodes(child2)
  81.  return  GenAlgo.replace_with_fit(child1, child2, parent1, parent2, population, child_fit1, child_fit2)
  82.    @staticmethod
  83.  def   replace_with_fit (child1, child2, parent1, parent2, population, child_fit1, child_fit2) :
  84.  """
  85. See replace_clique_fit
  86. """
  87. n = len(population)
  88.  if  child_fit1 > child_fit2:
  89.            best_fit = child_fit1
  90. best_chrom = child1  else :
  91.            best_fit = child_fit2
  92.            best_chrom = child2
  93.  if  best_fit > population[parent1][ 1 ]: population[parent1] = (best_chrom, best_fit)
  94.  elif  best_fit > population[parent2][ 1 ]: population[parent1] = (best_chrom, best_fit)
  95.  26
  96.   elif  best_fit > population[n -  1 ][ 1 ]: population[parent1] = (best_chrom, best_fit)
  97.  else : return   1  return   0
  98.    @staticmethod
  99.  def   find_solution (adj_list, simple_generator,
  100. fit_func, local_optimization, gen_count= 10 , stop_count= 15 , populations=None, crossover_n= 5 ) :
  101. n = len(adj_list) population = []
  102.  # generate start population total_fitness =  0
  103.  for  i  in  range(gen_count):
  104.            simple_cq = utils.list_to_chromosom(simple_generator(), n)
  105.            population.append((simple_cq, fit_func(simple_cq)))
  106.            total_fitness += fit_func(simple_cq)
  107. reps = stop_count  # number of stagnant repeats reps_count =  0  #  number of operations
  108.  while   True :
  109.  if  populations  is   not   None :
  110. populations.append(copy.copy(population)) reps_count +=  1
  111. fitness = []
  112.  for  i  in  range(gen_count):
  113. fitness.append(population[i][ 1 ])
  114. p = GenAlgo.roulette_wheel_weights(fitness) parent1 = GenAlgo.chose_parent(p)
  115. parent2 = GenAlgo.chose_parent(p)
  116.  while  parent1 == parent2:
  117.                parent2 = GenAlgo.chose_parent(p)
  118. children = GenAlgo.multipoint_crossover(population[parent1][ 0 ], population[parent2][ 0 ], crossover_n)
  119. mut1 = GenAlgo.mutation(children[ 0 ])
  120. 27
  121. mut2 = GenAlgo.mutation(children[ 1 ]) children = (mut1, mut2)
  122. children = local_optimization(children, n)
  123. fit1 = fit_func(children[ 0 ])
  124. fit2 = fit_func(children[ 1 ]) GenAlgo.replace_with_fit(children[ 0 ], children[ 1 ], parent1,
  125. parent2, population, fit1, fit2)
  126. new_fitness =  0
  127.  for  i  in  population:
  128. new_fitness += i[ 1 ]
  129.  if  new_fitness == total_fitness:
  130. reps -=  1 total_fitness = new_fitness  if  reps ==  0 :
  131.  break
  132. best = (population[ 0 ][ 0]  , population[ 0 ][ 1 ])  for  beast  in  population:
  133.  if  beast[ 1 ] > best[1   ]: best = beast
  134.  return  best, reps_count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement