Algorithm.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # main imports
  2. import logging
  3. # Generic algorithm class
  4. class Algorithm():
  5. def __init__(self, _initalizer, _evaluator, _operators, _policy, _validator, _maximise=True, _parent=None):
  6. """
  7. Initialize all usefull parameters for problem to solve
  8. """
  9. self.initializer = _initalizer
  10. self.evaluator = _evaluator
  11. self.operators = _operators
  12. self.validator = _validator
  13. self.policy = _policy
  14. self.checkpoint = None
  15. # other parameters
  16. self.parent = _parent # parent algorithm if it's sub algorithm
  17. self.maxEvalutations = 0 # by default
  18. self.maximise = _maximise
  19. self.initRun()
  20. def addCheckpoint(self, _class, _every, _filepath):
  21. self.checkpoint = _class(self, _every, _filepath)
  22. def setCheckpoint(self, _checkpoint):
  23. self.checkpoint = _checkpoint
  24. def resume(self):
  25. if self.checkpoint is None:
  26. raise ValueError("Need to `addCheckpoint` or `setCheckpoint` is you want to use this process")
  27. else:
  28. print('Checkpoint loading is called')
  29. self.checkpoint.load()
  30. def initRun(self):
  31. """
  32. Reinit the whole variables
  33. """
  34. self.currentSolution = self.initializer()
  35. # evaluate current solution
  36. self.currentSolution.evaluate(self.evaluator)
  37. # keep in memory best known solution (current solution)
  38. self.bestSolution = self.currentSolution
  39. self.numberOfEvaluations = 0
  40. def increaseEvaluation(self):
  41. self.numberOfEvaluations += 1
  42. if self.parent is not None:
  43. self.parent.numberOfEvaluations += 1
  44. def getGlobalEvaluation(self):
  45. if self.parent is not None:
  46. return self.parent.numberOfEvaluations
  47. return self.numberOfEvaluations
  48. def evaluate(self, solution):
  49. """
  50. Returns:
  51. fitness score of solution which is not already evaluated or changed
  52. Note:
  53. if multi-objective problem this method can be updated using array of `evaluator`
  54. """
  55. return solution.evaluate(self.evaluator)
  56. def update(self, solution, secondSolution=None):
  57. """
  58. Apply update function to solution using specific `policy`
  59. Check if solution is valid after modification and returns it
  60. Returns:
  61. updated solution
  62. """
  63. # two parameters are sent if specific crossover solution are wished
  64. sol = self.policy.apply(solution, secondSolution)
  65. if(sol.isValid(self.validator)):
  66. return sol
  67. else:
  68. logging.info("-- New solution is not valid %s" % sol)
  69. return solution
  70. def isBetter(self, solution):
  71. """
  72. Check if solution is better than best found
  73. Returns:
  74. `True` if better
  75. """
  76. # depending of problem to solve (maximizing or minimizing)
  77. if self.maximise:
  78. if self.evaluate(solution) > self.bestSolution.fitness():
  79. return True
  80. else:
  81. if self.evaluate(solution) < self.bestSolution.fitness():
  82. return True
  83. # by default
  84. return False
  85. def run(self, _evaluations):
  86. """
  87. Run the specific algorithm following number of evaluations to find optima
  88. """
  89. self.maxEvalutations = _evaluations
  90. self.initRun()
  91. logging.info("Run %s with %s evaluations" % (self.__str__(), _evaluations))
  92. def progress(self):
  93. if self.checkpoint is not None:
  94. self.checkpoint.run()
  95. logging.info("-- %s evaluation %s of %s (%s%%) - BEST SCORE %s" % (type(self).__name__, self.numberOfEvaluations, self.maxEvalutations, "{0:.2f}".format((self.numberOfEvaluations) / self.maxEvalutations * 100.), self.bestSolution.fitness()))
  96. def information(self):
  97. logging.info("-- Best %s - SCORE %s" % (self.bestSolution, self.bestSolution.fitness()))
  98. def __str__(self):
  99. return "%s using %s" % (type(self).__name__, type(self.bestSolution).__name__)