SimpleCrossover.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import pkgutil
  7. # module imports
  8. from .Crossover import Crossover
  9. from ...utils.modules import load_class
  10. # import all available solutions
  11. # for loader, module_name, is_pkg in pkgutil.walk_packages(
  12. # path=[
  13. # str(pathlib.Path(__file__).parent.absolute()) + '/../../solutions'
  14. # ],
  15. # prefix='macop.solutions.'):
  16. # _module = loader.find_module(module_name).load_module(module_name)
  17. # globals()[module_name] = _module
  18. class SimpleCrossover(Crossover):
  19. """Crossover implementation which generated new solution by splitting at mean size best solution and current solution
  20. Attributes:
  21. kind: {Algorithm} -- specify the kind of operator
  22. """
  23. def apply(self, solution):
  24. """Create new solution based on best solution found and solution passed as parameter
  25. Args:
  26. solution: {Solution} -- the solution to use for generating new solution
  27. Returns:
  28. {Solution} -- new generated solution
  29. """
  30. size = solution._size
  31. # copy data of solution
  32. firstData = solution._data.copy()
  33. # get best solution from current algorithm
  34. secondData = self._algo._bestSolution._data.copy()
  35. splitIndex = int(size / 2)
  36. if random.uniform(0, 1) > 0.5:
  37. firstData[splitIndex:(size - 1)] = firstData[splitIndex:(size - 1)]
  38. currentData = firstData
  39. else:
  40. secondData[splitIndex:(size - 1)] = firstData[splitIndex:(size -
  41. 1)]
  42. currentData = secondData
  43. # create solution of same kind with new data
  44. class_name = type(solution).__name__
  45. # dynamically load solution class if unknown
  46. if class_name not in sys.modules:
  47. load_class(class_name, globals())
  48. return getattr(globals()['macop.solutions.' + class_name],
  49. class_name)(currentData, size)