knapsackMultiExample.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # main imports
  2. import logging
  3. import os
  4. import random
  5. # module imports
  6. from macop.solutions.BinarySolution import BinarySolution
  7. from macop.evaluators.EvaluatorExample import evaluatorExample
  8. from macop.operators.mutators.SimpleMutation import SimpleMutation
  9. from macop.operators.mutators.SimpleBinaryMutation import SimpleBinaryMutation
  10. from macop.operators.crossovers.SimpleCrossover import SimpleCrossover
  11. from macop.operators.crossovers.RandomSplitCrossover import RandomSplitCrossover
  12. from macop.operators.policies.RandomPolicy import RandomPolicy
  13. from macop.operators.policies.UCBPolicy import UCBPolicy
  14. from macop.algorithms.multi.MOEAD import MOEAD
  15. from macop.callbacks.MultiCheckpoint import MultiCheckpoint
  16. if not os.path.exists('data'):
  17. os.makedirs('data')
  18. # logging configuration
  19. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/exampleMOEAD.log', level=logging.DEBUG)
  20. random.seed(42)
  21. elements_score1 = [ random.randint(1, 100) for _ in range(200) ]
  22. elements_score2 = [ random.randint(1, 200) for _ in range(200) ]
  23. elements_weight = [ random.randint(2, 10) for _ in range(200) ]
  24. def knapsackWeight(_solution):
  25. weight_sum = 0
  26. for index, elem in enumerate(_solution.data):
  27. weight_sum += elements_weight[index] * elem
  28. return weight_sum
  29. # default validator
  30. def validator(_solution):
  31. if knapsackWeight(_solution) <= 600:
  32. return True
  33. else:
  34. False
  35. # define init random solution
  36. def init():
  37. return BinarySolution([], 200).random(validator)
  38. def evaluator1(_solution):
  39. fitness = 0
  40. for index, elem in enumerate(_solution.data):
  41. fitness += (elements_score1[index] * elem)
  42. return fitness
  43. def evaluator2(_solution):
  44. fitness = 0
  45. for index, elem in enumerate(_solution.data):
  46. fitness += (elements_score2[index] * elem)
  47. return fitness
  48. filepath = "data/checkpointsMOEAD.csv"
  49. def main():
  50. operators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover(), RandomSplitCrossover()]
  51. policy = UCBPolicy(operators)
  52. # pass list of evaluators
  53. algo = MOEAD(20, 5, init, [evaluator1, evaluator2], operators, policy, validator, _maximise=True)
  54. algo.addCallback(MultiCheckpoint(_every=5, _filepath=filepath))
  55. paretoFront = algo.run(100000)
  56. if __name__ == "__main__":
  57. main()