Algorithm.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import logging
  2. # Generic algorithm class
  3. class Algorithm():
  4. def __init__(self, _initalizer, _evaluator, _updators, _policy, _validator, _maximise=True):
  5. """
  6. Initialize all usefull parameters for problem to solve
  7. """
  8. self.initializer = _initalizer
  9. self.evaluator = _evaluator
  10. self.updators = _updators
  11. self.validator = _validator
  12. self.policy = _policy
  13. # other parameters
  14. self.maxEvalutations = 0 # by default
  15. self.maximise = _maximise
  16. self.initRun()
  17. def initRun(self):
  18. """
  19. Reinit the whole variables
  20. """
  21. self.currentSolution = self.initializer()
  22. # evaluate current solution
  23. self.currentSolution.evaluate(self.evaluator)
  24. # keep in memory best known solution (current solution)
  25. self.bestSolution = self.currentSolution
  26. self.numberOfEvaluations = 0
  27. def evaluate(self, solution):
  28. """
  29. Returns:
  30. fitness score of solution which is not already evaluated or changed
  31. Note:
  32. if multi-objective problem this method can be updated using array of `evaluator`
  33. """
  34. return solution.evaluate(self.evaluator)
  35. def update(self, solution):
  36. """
  37. Apply update function to solution using specific `policy`
  38. Check if solution is valid after modification and returns it
  39. Returns:
  40. updated solution
  41. """
  42. sol = self.policy.apply(solution)
  43. if(sol.isValid(self.validator)):
  44. return sol
  45. else:
  46. print("New solution is not valid", sol)
  47. return solution
  48. def isBetter(self, solution):
  49. """
  50. Check if solution is better than best found
  51. Returns:
  52. `True` if better
  53. """
  54. # depending of problem to solve (maximizing or minimizing)
  55. if self.maximise:
  56. if self.evaluate(solution) > self.bestSolution.fitness():
  57. return True
  58. else:
  59. if self.evaluate(solution) < self.bestSolution.fitness():
  60. return True
  61. # by default
  62. return False
  63. def run(self, _evaluations):
  64. """
  65. Run the specific algorithm following number of evaluations to find optima
  66. """
  67. self.maxEvalutations = _evaluations
  68. self.initRun()
  69. logging.info("Run %s with %s evaluations" % (self.__str__(), _evaluations))
  70. def progress(self):
  71. logging.info("-- Evaluation n°%s of %s, %s%%" % (self.numberOfEvaluations, self.maxEvalutations, "{0:.2f}".format((self.numberOfEvaluations) / self.maxEvalutations * 100.)))
  72. def information(self):
  73. logging.info("-- Found %s with score of %s" % (self.bestSolution, self.bestSolution.fitness()))
  74. def __str__(self):
  75. return "%s using %s" % (type(self).__name__, type(self.bestSolution).__name__)