SimpleCrossover.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Crossover implementation which generated new solution by splitting at mean size best solution and current solution
  2. """
  3. # main imports
  4. import random
  5. import sys
  6. # module imports
  7. from .Crossover import Crossover
  8. from ...solutions.BinarySolution import BinarySolution
  9. from ...solutions.Solution import Solution
  10. class SimpleCrossover(Crossover):
  11. """Crossover implementation which generated new solution by splitting at mean size best solution and current solution
  12. Attributes:
  13. kind: {Algorithm} -- specify the kind of operator
  14. """
  15. def apply(self, solution):
  16. """Create new solution based on best solution found and solution passed as parameter
  17. Args:
  18. _solution: {Solution} -- the solution to use for generating new solution
  19. Returns:
  20. {Solution} -- new generated solution
  21. """
  22. size = solution.size
  23. # copy data of solution
  24. firstData = solution.data.copy()
  25. # get best solution from current algorithm
  26. secondData = self.algo.bestSolution.data.copy()
  27. splitIndex = int(size / 2)
  28. if random.uniform(0, 1) > 0.5:
  29. firstData[splitIndex:(size - 1)] = firstData[splitIndex:(size - 1)]
  30. currentData = firstData
  31. else:
  32. secondData[splitIndex:(size - 1)] = firstData[splitIndex:(size -
  33. 1)]
  34. currentData = secondData
  35. # create solution of same kind with new data
  36. return globals()[type(solution).__name__](currentData, size)