RandomSplitCrossover.py 1.6 KB

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