RandomSplitCrossover.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. import pkgutil
  7. # module imports
  8. from .Crossover import Crossover
  9. from ...utils.modules import load_class
  10. class RandomSplitCrossover(Crossover):
  11. """Crossover implementation which generated new solution by randomly splitting best solution and current solution
  12. Attributes:
  13. kind: {KindOperator} -- 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 = random.randint(0, len(secondData))
  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. class_name = type(_solution).__name__
  37. # dynamically load solution class if unknown
  38. if class_name not in sys.modules:
  39. load_class(class_name, globals())
  40. return getattr(globals()['macop.solutions.' + class_name],
  41. class_name)(currentData, size)