SimpleBinaryMutation.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Mutation implementation for binary solution, swap bit 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 SimpleBinaryMutation(Mutation):
  15. """Mutation implementation for binary solution, swap bit 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. cell = random.randint(0, size - 1)
  28. # copy data of solution
  29. currentData = _solution.data.copy()
  30. # swicth values
  31. if currentData[cell]:
  32. currentData[cell] = 0
  33. else:
  34. currentData[cell] = 1
  35. # create solution of same kind with new data
  36. class_name = type(_solution).__name__
  37. return getattr(globals()['macop.solutions.' + class_name],
  38. class_name)(currentData, size)