LocalSearch.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Local Search algorithm
  2. """
  3. # main imports
  4. import logging
  5. # module imports
  6. from ..Algorithm import Algorithm
  7. class LocalSearch(Algorithm):
  8. """Local Search used as exploitation optimization 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. """
  20. def run(self, _evaluations):
  21. """
  22. Run the local search algorithm
  23. Args:
  24. _evaluations: {int} -- number of Local search evaluations
  25. Returns:
  26. {Solution} -- best solution found
  27. """
  28. # by default use of mother method to initialize variables
  29. super().run(_evaluations)
  30. solutionSize = self.bestSolution.size
  31. # local search algorithm implementation
  32. while not self.stop():
  33. for _ in range(solutionSize):
  34. # update solution using policy
  35. newSolution = self.update(self.bestSolution)
  36. # if better solution than currently, replace it
  37. if self.isBetter(newSolution):
  38. self.bestSolution = newSolution
  39. # increase number of evaluations
  40. self.increaseEvaluation()
  41. self.progress()
  42. logging.info("---- Current %s - SCORE %s" %
  43. (newSolution, newSolution.fitness()))
  44. # stop algorithm if necessary
  45. if self.stop():
  46. break
  47. logging.info("End of %s, best solution found %s" %
  48. (type(self).__name__, self.bestSolution))
  49. return self.bestSolution