SimpleCrossover.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. # 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 SimpleCrossover(Crossover):
  15. """Crossover implementation which generated new solution by splitting at mean size best solution and current solution
  16. Attributes:
  17. kind: {Algorithm} -- 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 = int(size / 2)
  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)