base.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Abstract classes for Operator Selection Strategy
  2. """
  3. import logging
  4. from abc import abstractmethod
  5. # define policy to choose `operator` function at current iteration
  6. class Policy():
  7. """Abstract class which is used for applying strategy when selecting and applying operator
  8. Attributes:
  9. operators: {[Operator]} -- list of selected operators for the algorithm
  10. """
  11. def __init__(self, operators):
  12. self._operators = operators
  13. @abstractmethod
  14. def select(self):
  15. """
  16. Select specific operator
  17. Returns:
  18. {Operator} -- selected operator
  19. """
  20. pass
  21. def apply(self, solution):
  22. """
  23. Apply specific operator chosen to create new solution, computes its fitness and returns solution
  24. Args:
  25. _solution: {Solution} -- the solution to use for generating new solution
  26. Returns:
  27. {Solution} -- new generated solution
  28. """
  29. operator = self.select()
  30. logging.info("---- Applying %s on %s" %
  31. (type(operator).__name__, solution))
  32. # apply operator on solution
  33. newSolution = operator.apply(solution)
  34. logging.info("---- Obtaining %s" % (solution))
  35. return newSolution
  36. def setAlgo(self, algo):
  37. """Keep into policy reference of the whole algorithm
  38. The reason is to better manage the operator choices (use of rewards as example)
  39. Args:
  40. algo: {Algorithm} -- the algorithm reference runned
  41. """
  42. self._algo = algo