SimpleBinaryMutation.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 ...utils.modules import load_class
  9. class SimpleBinaryMutation(Mutation):
  10. """Mutation implementation for binary solution, swap bit randomly from solution
  11. Attributes:
  12. kind: {KindOperator} -- specify the kind of operator
  13. """
  14. def apply(self, solution):
  15. """Create new solution based on solution passed as parameter
  16. Args:
  17. solution: {Solution} -- the solution to use for generating new solution
  18. Returns:
  19. {Solution} -- new generated solution
  20. """
  21. size = solution._size
  22. cell = random.randint(0, size - 1)
  23. # copy data of solution
  24. currentData = solution._data.copy()
  25. # swicth values
  26. if currentData[cell]:
  27. currentData[cell] = 0
  28. else:
  29. currentData[cell] = 1
  30. # create solution of same kind with new data
  31. class_name = type(solution).__name__
  32. # dynamically load solution class if unknown
  33. if class_name not in sys.modules:
  34. load_class(class_name, globals())
  35. return getattr(globals()['macop.solutions.' + class_name],
  36. class_name)(currentData, size)