Policy.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """Abstract class which is used for applying strategy when selecting and applying operator
  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. # compute fitness of new solution
  35. newSolution.evaluate(self.algo.evaluator)
  36. logging.info("---- Obtaining %s" % (_solution))
  37. return newSolution
  38. def setAlgo(self, _algo):
  39. """Keep into policy reference of the whole algorithm
  40. The reason is to better manage the operator choices (use of rewards as example)
  41. Args:
  42. _algo: {Algorithm} -- the algorithm reference runned
  43. """
  44. self.algo = _algo