Policy.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. # here you can define your statistical variables for choosing next operator to apply
  11. def __init__(self, _operators):
  12. self.operators = _operators
  13. def select(self):
  14. """
  15. Select specific operator to solution and returns solution
  16. """
  17. raise NotImplementedError
  18. def apply(self, _solution):
  19. """
  20. Apply specific operator chosen to create new solution, computes its fitness and returns solution
  21. Args:
  22. _solution: {Solution} -- the solution to use for generating new solution
  23. Returns:
  24. {Solution} -- new generated solution
  25. """
  26. operator = self.select()
  27. logging.info("---- Applying %s on %s" %
  28. (type(operator).__name__, _solution))
  29. # apply operator on solution
  30. newSolution = operator.apply(_solution)
  31. # compute fitness of new solution
  32. newSolution.evaluate(self.algo.evaluator)
  33. print(newSolution.fitness())
  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