Algorithm.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 resume(self):
  59. """Resume algorithm using Callback instances
  60. """
  61. # load every callback if many things are necessary to do before running algorithm
  62. for callback in self.callbacks:
  63. callback.load()
  64. def initRun(self):
  65. """
  66. Initialize the current solution and best solution
  67. """
  68. self.currentSolution = self.initializer()
  69. # evaluate current solution
  70. self.currentSolution.evaluate(self.evaluator)
  71. # keep in memory best known solution (current solution)
  72. self.bestSolution = self.currentSolution
  73. def increaseEvaluation(self):
  74. """
  75. Increase number of evaluation once a solution is evaluated
  76. """
  77. self.numberOfEvaluations += 1
  78. if self.parent is not None:
  79. self.parent.numberOfEvaluations += 1
  80. def getGlobalEvaluation(self):
  81. """Get the global number of evaluation (if inner algorithm)
  82. Returns:
  83. {int} -- current global number of evaluation
  84. """
  85. if self.parent is not None:
  86. return self.parent.numberOfEvaluations
  87. return self.numberOfEvaluations
  88. def getGlobalMaxEvaluation(self):
  89. """Get the global max number of evaluation (if inner algorithm)
  90. Returns:
  91. {int} -- current global max number of evaluation
  92. """
  93. if self.parent is not None:
  94. return self.parent.maxEvaluations
  95. return self.maxEvaluations
  96. def stop(self):
  97. """
  98. Global stopping criteria (check for inner algorithm too)
  99. """
  100. if self.parent is not None:
  101. return self.parent.numberOfEvaluations >= self.parent.maxEvaluations or self.numberOfEvaluations >= self.maxEvaluations
  102. return self.numberOfEvaluations >= self.maxEvaluations
  103. def evaluate(self, _solution):
  104. """
  105. Evaluate a solution using evaluator passed when intialize algorithm
  106. Args:
  107. solution: {Solution} -- solution to evaluate
  108. Returns:
  109. fitness score of solution which is not already evaluated or changed
  110. Note:
  111. if multi-objective problem this method can be updated using array of `evaluator`
  112. """
  113. return _solution.evaluate(self.evaluator)
  114. def update(self, _solution):
  115. """
  116. Apply update function to solution using specific `policy`
  117. Check if solution is valid after modification and returns it
  118. Args:
  119. solution: {Solution} -- solution to update using current policy
  120. Returns:
  121. {Solution} -- updated solution obtained by the selected operator
  122. """
  123. # two parameters are sent if specific crossover solution are wished
  124. sol = self.policy.apply(_solution)
  125. if (sol.isValid(self.validator)):
  126. return sol
  127. else:
  128. logging.info("-- New solution is not valid %s" % sol)
  129. return _solution
  130. def isBetter(self, _solution):
  131. """
  132. Check if solution is better than best found
  133. Args:
  134. solution: {Solution} -- solution to compare with best one
  135. Returns:
  136. {bool} -- `True` if better
  137. """
  138. # depending of problem to solve (maximizing or minimizing)
  139. if self.maximise:
  140. if _solution.fitness() > self.bestSolution.fitness():
  141. return True
  142. else:
  143. if _solution.fitness() < self.bestSolution.fitness():
  144. return True
  145. # by default
  146. return False
  147. def run(self, _evaluations):
  148. """
  149. Run the specific algorithm following number of evaluations to find optima
  150. """
  151. # append number of max evaluation if multiple run called
  152. self.maxEvaluations += _evaluations
  153. # check if global evaluation is used or not
  154. if self.parent is not None and self.getGlobalEvaluation() != 0:
  155. # init number evaluations of inner algorithm depending of globalEvaluation
  156. # allows to restart from `checkpoint` last evaluation into inner algorithm
  157. rest = self.getGlobalEvaluation() % self.maxEvaluations
  158. self.numberOfEvaluations = rest
  159. else:
  160. self.numberOfEvaluations = 0
  161. logging.info("Run %s with %s evaluations" %
  162. (self.__str__(), _evaluations))
  163. def progress(self):
  164. """
  165. Log progress and apply callbacks if necessary
  166. """
  167. if len(self.callbacks) > 0:
  168. for callback in self.callbacks:
  169. callback.run()
  170. macop_progress(self.getGlobalEvaluation(),
  171. self.getGlobalMaxEvaluation())
  172. logging.info("-- %s evaluation %s of %s (%s%%) - BEST SCORE %s" %
  173. (type(self).__name__, self.numberOfEvaluations,
  174. self.maxEvaluations, "{0:.2f}".format(
  175. (self.numberOfEvaluations) / self.maxEvaluations *
  176. 100.), self.bestSolution.fitness()))
  177. def end(self):
  178. """Display end message into `run` method
  179. """
  180. print(
  181. macop_text('({}) Found after {} evaluations \n - {}'.format(
  182. type(self).__name__, self.numberOfEvaluations,
  183. self.bestSolution)))
  184. print(macop_line())
  185. def information(self):
  186. logging.info("-- Best %s - SCORE %s" %
  187. (self.bestSolution, self.bestSolution.fitness()))
  188. def __str__(self):
  189. return "%s using %s" % (type(self).__name__, type(
  190. self.bestSolution).__name__)