Policy.py 1.6 KB

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