crossovers.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Crossover implementations for discrete solutions kind
  2. """
  3. # main imports
  4. import random
  5. import sys
  6. # module imports
  7. from macop.operators.base import Crossover
  8. class SimpleCrossover(Crossover):
  9. """Crossover implementation which generated new solution by splitting at mean size best solution and current solution
  10. Attributes:
  11. kind: {Algorithm} -- specify the kind of operator
  12. Example:
  13. >>> # operators import
  14. >>> from macop.operators.discrete.crossovers import SimpleCrossover
  15. >>> from macop.operators.discrete.mutators import SimpleMutation
  16. >>> # policy import
  17. >>> from macop.policies.reinforcement import UCBPolicy
  18. >>> # solution and algorithm
  19. >>> from macop.solutions.discrete import BinarySolution
  20. >>> from macop.algorithms.mono import IteratedLocalSearch
  21. >>> from macop.algorithms.mono import HillClimberFirstImprovment
  22. >>> # evaluator import
  23. >>> from macop.evaluators.discrete.mono import KnapsackEvaluator
  24. >>> # evaluator initialization (worths objects passed into data)
  25. >>> worths = [ random.randint(0, 20) for i in range(10) ]
  26. >>> evaluator = KnapsackEvaluator(data={'worths': worths})
  27. >>> # validator specification (based on weights of each objects)
  28. >>> weights = [ random.randint(20, 30) for i in range(10) ]
  29. >>> validator = lambda solution: True if sum([weights[i] for i, value in enumerate(solution._data) if value == 1]) < 200 else False
  30. >>> # initializer function with lambda function
  31. >>> initializer = lambda x=10: BinarySolution.random(x, validator)
  32. >>> # operators list with crossover and mutation
  33. >>> simple_crossover = SimpleCrossover()
  34. >>> simple_mutation = SimpleMutation()
  35. >>> operators = [simple_crossover, simple_mutation]
  36. >>> policy = UCBPolicy(operators)
  37. >>> local_search = HillClimberFirstImprovment(initializer, evaluator, operators, policy, validator, maximise=True, verbose=False)
  38. >>> algo = IteratedLocalSearch(initializer, evaluator, operators, policy, validator, localSearch=local_search, maximise=True, verbose=False)
  39. >>> # using best solution, simple crossover is applied
  40. >>> best_solution = algo.run(100)
  41. >>> list(best_solution._data)
  42. [1, 1, 0, 1, 0, 1, 1, 1, 0, 1]
  43. >>> new_solution_1 = initializer()
  44. >>> new_solution_2 = initializer()
  45. >>> offspring_solution = simple_crossover.apply(new_solution_1, new_solution_2)
  46. >>> list(offspring_solution._data)
  47. [0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
  48. """
  49. def apply(self, solution1, solution2=None):
  50. """Create new solution based on best solution found and solution passed as parameter
  51. Args:
  52. solution1: {Solution} -- the first solution to use for generating new solution
  53. solution2: {Solution} -- the second solution to use for generating new solution
  54. Returns:
  55. {Solution} -- new generated solution
  56. """
  57. size = solution1._size
  58. # copy data of solution
  59. firstData = solution1._data.copy()
  60. # copy of solution2 as output solution
  61. copy_solution = solution2.clone()
  62. splitIndex = int(size / 2)
  63. if random.uniform(0, 1) > 0.5:
  64. copy_solution._data[splitIndex:] = firstData[splitIndex:]
  65. else:
  66. copy_solution._data[:splitIndex] = firstData[:splitIndex]
  67. return copy_solution
  68. class RandomSplitCrossover(Crossover):
  69. """Crossover implementation which generated new solution by randomly splitting best solution and current solution
  70. Attributes:
  71. kind: {KindOperator} -- specify the kind of operator
  72. Example:
  73. >>> # operators import
  74. >>> from macop.operators.discrete.crossovers import RandomSplitCrossover
  75. >>> from macop.operators.discrete.mutators import SimpleMutation
  76. >>> # policy import
  77. >>> from macop.policies.reinforcement import UCBPolicy
  78. >>> # solution and algorithm
  79. >>> from macop.solutions.discrete import BinarySolution
  80. >>> from macop.algorithms.mono import IteratedLocalSearch
  81. >>> from macop.algorithms.mono import HillClimberFirstImprovment
  82. >>> # evaluator import
  83. >>> from macop.evaluators.discrete.mono import KnapsackEvaluator
  84. >>> # evaluator initialization (worths objects passed into data)
  85. >>> worths = [ random.randint(0, 20) for i in range(10) ]
  86. >>> evaluator = KnapsackEvaluator(data={'worths': worths})
  87. >>> # validator specification (based on weights of each objects)
  88. >>> weights = [ random.randint(20, 30) for i in range(10) ]
  89. >>> validator = lambda solution: True if sum([weights[i] for i, value in enumerate(solution._data) if value == 1]) < 200 else False
  90. >>> # initializer function with lambda function
  91. >>> initializer = lambda x=10: BinarySolution.random(x, validator)
  92. >>> # operators list with crossover and mutation
  93. >>> random_split_crossover = RandomSplitCrossover()
  94. >>> simple_mutation = SimpleMutation()
  95. >>> operators = [random_split_crossover, simple_mutation]
  96. >>> policy = UCBPolicy(operators)
  97. >>> local_search = HillClimberFirstImprovment(initializer, evaluator, operators, policy, validator, maximise=True, verbose=False)
  98. >>> algo = IteratedLocalSearch(initializer, evaluator, operators, policy, validator, localSearch=local_search, maximise=True, verbose=False)
  99. >>> # using best solution, simple crossover is applied
  100. >>> best_solution = algo.run(100)
  101. >>> list(best_solution._data)
  102. [1, 1, 1, 0, 1, 0, 1, 1, 1, 0]
  103. >>> new_solution_1 = initializer()
  104. >>> new_solution_2 = initializer()
  105. >>> offspring_solution = random_split_crossover.apply(new_solution_1, new_solution_2)
  106. >>> list(offspring_solution._data)
  107. [0, 0, 0, 1, 1, 0, 0, 1, 0, 0]
  108. """
  109. def apply(self, solution1, solution2=None):
  110. """Create new solution based on best solution found and solution passed as parameter
  111. Args:
  112. solution1: {Solution} -- the first solution to use for generating new solution
  113. solution2: {Solution} -- the second solution to use for generating new solution
  114. Returns:
  115. {Solution} -- new generated solution
  116. """
  117. size = solution1._size
  118. # copy data of solution
  119. firstData = solution1._data.copy()
  120. # copy of solution2 as output solution
  121. copy_solution = solution2.clone()
  122. splitIndex = random.randint(0, size)
  123. if random.uniform(0, 1) > 0.5:
  124. copy_solution._data[splitIndex:] = firstData[splitIndex:]
  125. else:
  126. copy_solution._data[:splitIndex] = firstData[:splitIndex]
  127. return copy_solution