SimpleBinaryMutation.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Mutation implementation for binary solution, swap bit randomly from solution
  2. """
  3. # main imports
  4. import random
  5. import sys
  6. # module imports
  7. from .Mutation import Mutation
  8. from ...solutions.BinarySolution import BinarySolution
  9. from ...solutions.Solution import Solution
  10. class SimpleBinaryMutation(Mutation):
  11. """Mutation implementation for binary solution, swap bit randomly from solution
  12. Attributes:
  13. kind: {KindOperator} -- specify the kind of operator
  14. """
  15. def apply(self, _solution):
  16. """Create new solution based on 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. cell = random.randint(0, size - 1)
  24. # copy data of solution
  25. currentData = _solution.data.copy()
  26. # swicth values
  27. if currentData[cell]:
  28. currentData[cell] = 0
  29. else:
  30. currentData[cell] = 1
  31. # create solution of same kind with new data
  32. return globals()[type(_solution).__name__](currentData, size)