Algorithm.py 2.8 KB

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