SimpleCrossover.py 884 B

12345678910111213141516171819202122232425262728293031
  1. # main imports
  2. import random
  3. import sys
  4. # module imports
  5. from .Crossover import Crossover
  6. from ...solutions.BinarySolution import BinarySolution
  7. from ...solutions.Solution import Solution
  8. class SimpleCrossover(Crossover):
  9. def apply(self, solution, secondSolution=None):
  10. size = solution.size
  11. # copy data of solution
  12. firstData = solution.data.copy()
  13. secondData = secondSolution.data.copy()
  14. splitIndex = int(size / 2)
  15. if random.uniform(0, 1) > 0.5:
  16. firstData[splitIndex:(size - 1)] = firstData[splitIndex:(size - 1)]
  17. currentData = firstData
  18. else:
  19. secondData[splitIndex:(size - 1)] = firstData[splitIndex:(size - 1)]
  20. currentData = secondData
  21. # create solution of same kind with new data
  22. return globals()[type(solution).__name__](currentData, size)