ZdtExample.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # main imports
  2. import logging
  3. import os
  4. import random
  5. import numpy as np
  6. import math
  7. # module imports
  8. from macop.solutions.continuous import ContinuousSolution
  9. from macop.evaluators.continuous.mono import ZdtEvaluator
  10. from macop.operators.continuous.mutators import PolynomialMutation
  11. from macop.operators.continuous.crossovers import BasicDifferentialEvolutionCrossover
  12. from macop.policies.classicals import RandomPolicy
  13. from macop.algorithms.mono import IteratedLocalSearch as ILS
  14. from macop.algorithms.mono import HillClimberFirstImprovment
  15. from macop.callbacks.classicals import ContinuousCheckpoint
  16. if not os.path.exists('data'):
  17. os.makedirs('data')
  18. # logging configuration
  19. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/example.log', level=logging.DEBUG)
  20. random.seed(42)
  21. # usefull instance data
  22. n = 10
  23. filepath = "data/checkpoints_zdt_Rosenbrock.csv"
  24. problem_interval = -10, 10 # fixed value interval (avoid infinite)
  25. # check each value in order to validate
  26. def validator(solution):
  27. mini, maxi = problem_interval
  28. for x in solution.data:
  29. if x < mini or x > maxi:
  30. return False
  31. return True
  32. # define init random solution
  33. def init():
  34. return ContinuousSolution.random(n, problem_interval, validator)
  35. def main():
  36. # Rosenbrock function with a=1 and b=100 (see https://en.wikipedia.org/wiki/Rosenbrock_function)
  37. Rosenbrock_function = lambda s: sum([ 100 * math.pow(s.data[i + 1] - (math.pow(s.data[i], 2)), 2) + math.pow((1 - s.data[i]), 2) for i in range(len(s.data) - 1) ])
  38. operators = [PolynomialMutation(interval=problem_interval), BasicDifferentialEvolutionCrossover(interval=problem_interval)]
  39. policy = RandomPolicy(operators)
  40. callback = ContinuousCheckpoint(every=5, filepath=filepath)
  41. evaluator = ZdtEvaluator(data={'f': Rosenbrock_function})
  42. # passing global evaluation param from ILS
  43. hcfi = HillClimberFirstImprovment(init, evaluator, operators, policy, validator, maximise=False, verbose=True)
  44. algo = ILS(init, evaluator, operators, policy, validator, localSearch=hcfi, maximise=False, verbose=True)
  45. # add callback into callback list
  46. algo.addCallback(callback)
  47. bestSol = algo.run(100000, ls_evaluations=100)
  48. print(bestSol.data)
  49. print('Solution for Rosenbrock Zdt instance score is {}'.format(evaluator.compute(bestSol)))
  50. if __name__ == "__main__":
  51. main()