Algorithm.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. """Abstract Algorithm class used as basic algorithm implementation with some specific initialization
  2. """
  3. # main imports
  4. import logging
  5. from ..utils.color import macop_text, macop_line, macop_progress
  6. # Generic algorithm class
  7. class Algorithm():
  8. """Algorithm class used as basic algorithm
  9. Attributes:
  10. initalizer: {function} -- basic function strategy to initialize solution
  11. evaluator: {function} -- basic function in order to obtained fitness (mono or multiple objectives)
  12. operators: {[Operator]} -- list of operator to use when launching algorithm
  13. policy: {Policy} -- Policy class implementation strategy to select operators
  14. validator: {function} -- basic function to check if solution is valid or not under some constraints
  15. maximise: {bool} -- specify kind of optimization problem
  16. currentSolution: {Solution} -- current solution managed for current evaluation
  17. bestSolution: {Solution} -- best solution found so far during running algorithm
  18. callbacks: {[Callback]} -- list of Callback class implementation to do some instructions every number of evaluations and `load` when initializing algorithm
  19. parent: {Algorithm} -- parent algorithm reference in case of inner Algorithm instance (optional)
  20. """
  21. def __init__(self,
  22. _initalizer,
  23. _evaluator,
  24. _operators,
  25. _policy,
  26. _validator,
  27. _maximise=True,
  28. _parent=None):
  29. self.initializer = _initalizer
  30. self.evaluator = _evaluator
  31. self.operators = _operators
  32. self.policy = _policy
  33. self.validator = _validator
  34. self.callbacks = []
  35. self.bestSolution = None
  36. # by default
  37. self.numberOfEvaluations = 0
  38. self.maxEvaluations = 0
  39. # other parameters
  40. self.parent = _parent # parent algorithm if it's sub algorithm
  41. #self.maxEvaluations = 0 # by default
  42. self.maximise = _maximise
  43. # track reference of algo into operator (keep an eye into best solution)
  44. for operator in self.operators:
  45. operator.setAlgo(self)
  46. # also track reference for policy
  47. self.policy.setAlgo(self)
  48. self.initRun()
  49. def addCallback(self, _callback):
  50. """Add new callback to algorithm specifying usefull parameters
  51. Args:
  52. _callback: {Callback} -- specific Callback instance
  53. """
  54. # specify current main algorithm reference
  55. _callback.setAlgo(self)
  56. # set as new
  57. self.callbacks.append(_callback)
  58. def setCheckpoint(self, _callback):
  59. """Set checkpoint instance directly
  60. Args:
  61. _callback: {Callback} -- Callback instance used for checkpoint
  62. """
  63. # specify current main algorithm reference if necessary
  64. if _callback.algo is None:
  65. _callback.setAlgo(self)
  66. # set as checkpoint
  67. self.checkpoint = _callback
  68. def resume(self):
  69. """Resume algorithm using Callback instances
  70. """
  71. # load every callback if many things are necessary to do before running algorithm
  72. for callback in self.callbacks:
  73. callback.load()
  74. def initRun(self):
  75. """
  76. Initialize the current solution and best solution
  77. """
  78. self.currentSolution = self.initializer()
  79. # evaluate current solution
  80. self.currentSolution.evaluate(self.evaluator)
  81. # keep in memory best known solution (current solution)
  82. self.bestSolution = self.currentSolution
  83. def increaseEvaluation(self):
  84. """
  85. Increase number of evaluation once a solution is evaluated
  86. """
  87. self.numberOfEvaluations += 1
  88. if self.parent is not None:
  89. self.parent.numberOfEvaluations += 1
  90. def getGlobalEvaluation(self):
  91. """Get the global number of evaluation (if inner algorithm)
  92. Returns:
  93. {int} -- current global number of evaluation
  94. """
  95. if self.parent is not None:
  96. return self.parent.numberOfEvaluations
  97. return self.numberOfEvaluations
  98. def getGlobalMaxEvaluation(self):
  99. """Get the global max number of evaluation (if inner algorithm)
  100. Returns:
  101. {int} -- current global max number of evaluation
  102. """
  103. if self.parent is not None:
  104. return self.parent.maxEvaluations
  105. return self.maxEvaluations
  106. def stop(self):
  107. """
  108. Global stopping criteria (check for inner algorithm too)
  109. """
  110. if self.parent is not None:
  111. return self.parent.numberOfEvaluations >= self.parent.maxEvaluations or self.numberOfEvaluations >= self.maxEvaluations
  112. return self.numberOfEvaluations >= self.maxEvaluations
  113. def evaluate(self, _solution):
  114. """
  115. Evaluate a solution using evaluator passed when intialize algorithm
  116. Args:
  117. solution: {Solution} -- solution to evaluate
  118. Returns:
  119. fitness score of solution which is not already evaluated or changed
  120. Note:
  121. if multi-objective problem this method can be updated using array of `evaluator`
  122. """
  123. return _solution.evaluate(self.evaluator)
  124. def update(self, _solution):
  125. """
  126. Apply update function to solution using specific `policy`
  127. Check if solution is valid after modification and returns it
  128. Args:
  129. solution: {Solution} -- solution to update using current policy
  130. Returns:
  131. {Solution} -- updated solution obtained by the selected operator
  132. """
  133. # two parameters are sent if specific crossover solution are wished
  134. sol = self.policy.apply(_solution)
  135. if (sol.isValid(self.validator)):
  136. return sol
  137. else:
  138. logging.info("-- New solution is not valid %s" % sol)
  139. return _solution
  140. def isBetter(self, _solution):
  141. """
  142. Check if solution is better than best found
  143. Args:
  144. solution: {Solution} -- solution to compare with best one
  145. Returns:
  146. {bool} -- `True` if better
  147. """
  148. # depending of problem to solve (maximizing or minimizing)
  149. if self.maximise:
  150. if _solution.fitness() > self.bestSolution.fitness():
  151. return True
  152. else:
  153. if _solution.fitness() < self.bestSolution.fitness():
  154. return True
  155. # by default
  156. return False
  157. def run(self, _evaluations):
  158. """
  159. Run the specific algorithm following number of evaluations to find optima
  160. """
  161. # append number of max evaluation if multiple run called
  162. self.maxEvaluations += _evaluations
  163. # check if global evaluation is used or not
  164. if self.parent is not None and self.getGlobalEvaluation() != 0:
  165. # init number evaluations of inner algorithm depending of globalEvaluation
  166. # allows to restart from `checkpoint` last evaluation into inner algorithm
  167. rest = self.getGlobalEvaluation() % self.maxEvaluations
  168. self.numberOfEvaluations = rest
  169. else:
  170. self.numberOfEvaluations = 0
  171. logging.info("Run %s with %s evaluations" %
  172. (self.__str__(), _evaluations))
  173. def progress(self):
  174. """
  175. Log progress and apply callbacks if necessary
  176. """
  177. if len(self.callbacks) > 0:
  178. for callback in self.callbacks:
  179. callback.run()
  180. macop_progress(self.getGlobalEvaluation(),
  181. self.getGlobalMaxEvaluation())
  182. logging.info("-- %s evaluation %s of %s (%s%%) - BEST SCORE %s" %
  183. (type(self).__name__, self.numberOfEvaluations,
  184. self.maxEvaluations, "{0:.2f}".format(
  185. (self.numberOfEvaluations) / self.maxEvaluations *
  186. 100.), self.bestSolution.fitness()))
  187. def end(self):
  188. """Display end message into `run` method
  189. """
  190. print(
  191. macop_text('({}) Found after {} evaluations \n - {}'.format(
  192. type(self).__name__, self.numberOfEvaluations,
  193. self.bestSolution)))
  194. print(macop_line())
  195. def information(self):
  196. logging.info("-- Best %s - SCORE %s" %
  197. (self.bestSolution, self.bestSolution.fitness()))
  198. def __str__(self):
  199. return "%s using %s" % (type(self).__name__, type(
  200. self.bestSolution).__name__)