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. # import all available solutions
  10. for loader, module_name, is_pkg in pkgutil.walk_packages(
  11. path=['macop/solutions'], prefix='macop.solutions.'):
  12. _module = loader.find_module(module_name).load_module(module_name)
  13. globals()[module_name] = _module
  14. class RandomSplitCrossover(Crossover):
  15. """Crossover implementation which generated new solution by randomly splitting best solution and current solution
  16. Attributes:
  17. kind: {KindOperator} -- specify the kind of operator
  18. """
  19. def apply(self, _solution):
  20. """Create new solution based on best solution found and solution passed as parameter
  21. Args:
  22. _solution: {Solution} -- the solution to use for generating new solution
  23. Returns:
  24. {Solution} -- new generated solution
  25. """
  26. size = _solution.size
  27. # copy data of solution
  28. firstData = _solution.data.copy()
  29. # get best solution from current algorithm
  30. secondData = self.algo.bestSolution.data.copy()
  31. splitIndex = random.randint(0, len(secondData))
  32. if random.uniform(0, 1) > 0.5:
  33. firstData[splitIndex:(size - 1)] = firstData[splitIndex:(size - 1)]
  34. currentData = firstData
  35. else:
  36. secondData[splitIndex:(size - 1)] = firstData[splitIndex:(size -
  37. 1)]
  38. currentData = secondData
  39. # create solution of same kind with new data
  40. class_name = type(_solution).__name__
  41. return getattr(globals()['macop.solutions.' + class_name],
  42. class_name)(currentData, size)