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