SimpleMutation.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """Mutation implementation for binary solution, swap two bits 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 SimpleMutation(Mutation):
  10. """Mutation implementation for binary solution, swap two bits 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. firstCell = 0
  23. secondCell = 0
  24. # copy data of solution
  25. currentData = solution._data.copy()
  26. while firstCell == secondCell:
  27. firstCell = random.randint(0, size - 1)
  28. secondCell = random.randint(0, size - 1)
  29. temp = currentData[firstCell]
  30. # swicth values
  31. currentData[firstCell] = currentData[secondCell]
  32. currentData[secondCell] = temp
  33. # create solution of same kind with new data
  34. class_name = type(solution).__name__
  35. # dynamically load solution class if unknown
  36. if class_name not in sys.modules:
  37. load_class(class_name, globals())
  38. return getattr(globals()['macop.solutions.' + class_name],
  39. class_name)(currentData, size)