SimpleMutation.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Mutation implementation for binary solution, swap two bits randomly from solution
  2. """
  3. # main imports
  4. import random
  5. import sys
  6. import pkgutil
  7. # module imports
  8. from .Mutation import Mutation
  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 SimpleMutation(Mutation):
  15. """Mutation implementation for binary solution, swap two bits randomly from solution
  16. Attributes:
  17. kind: {KindOperator} -- specify the kind of operator
  18. """
  19. def apply(self, _solution):
  20. """Create new solution based on 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. firstCell = 0
  28. secondCell = 0
  29. # copy data of solution
  30. currentData = _solution.data.copy()
  31. while firstCell == secondCell:
  32. firstCell = random.randint(0, size - 1)
  33. secondCell = random.randint(0, size - 1)
  34. temp = currentData[firstCell]
  35. # swicth values
  36. currentData[firstCell] = currentData[secondCell]
  37. currentData[secondCell] = temp
  38. # create solution of same kind with new data
  39. class_name = type(_solution).__name__
  40. return getattr(globals()['macop.solutions.' + class_name],
  41. class_name)(currentData, size)