knapsackExample.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.mono.IteratedLocalSearch import IteratedLocalSearch as ILS
  15. from macop.callbacks.BasicCheckpoint import BasicCheckpoint
  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. elements_score = [ random.randint(1, 20) for _ in range(30) ]
  22. elements_weight = [ random.randint(2, 5) for _ in range(30) ]
  23. def knapsackWeight(solution):
  24. weight_sum = 0
  25. for index, elem in enumerate(solution._data):
  26. weight_sum += elements_weight[index] * elem
  27. return weight_sum
  28. # default validator
  29. def validator(solution):
  30. if knapsackWeight(solution) <= 80:
  31. return True
  32. else:
  33. False
  34. # define init random solution
  35. def init():
  36. return BinarySolution([], 30).random(validator)
  37. def evaluator(solution):
  38. fitness = 0
  39. for index, elem in enumerate(solution._data):
  40. fitness += (elements_score[index] * elem)
  41. return fitness
  42. filepath = "data/checkpoints.csv"
  43. def main():
  44. operators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover(), RandomSplitCrossover()]
  45. policy = UCBPolicy(operators)
  46. callback = BasicCheckpoint(every=5, filepath=filepath)
  47. algo = ILS(init, evaluator, operators, policy, validator, maximise=True)
  48. # add callback into callback list
  49. algo.addCallback(callback)
  50. bestSol = algo.run(1000)
  51. print('Solution score is {}'.format(evaluator(bestSol)))
  52. print('Solution weigth is {}'.format(knapsackWeight(bestSol)))
  53. if __name__ == "__main__":
  54. main()