qapExample.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # main imports
  2. import logging
  3. import os
  4. import random
  5. import numpy as np
  6. # module imports
  7. from macop.solutions.discrete import CombinatoryIntegerSolution
  8. from macop.evaluators.discrete.mono import QAPEvaluator
  9. from macop.operators.discrete.mutators import SimpleMutation
  10. from macop.policies.classicals import RandomPolicy
  11. from macop.policies.reinforcement import UCBPolicy
  12. from macop.algorithms.mono import IteratedLocalSearch as ILS
  13. from macop.algorithms.mono import HillClimberFirstImprovment
  14. from macop.callbacks.classicals import BasicCheckpoint
  15. if not os.path.exists('data'):
  16. os.makedirs('data')
  17. # logging configuration
  18. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/example_qap.log', level=logging.DEBUG)
  19. random.seed(42)
  20. # usefull instance data
  21. n = 100
  22. qap_instance_file = 'instances/qap/qap_instance.txt'
  23. filepath = "data/checkpoints_qap.csv"
  24. # default validator
  25. def validator(solution):
  26. if len(list(solution.data)) > len(set(list(solution.data))):
  27. print("not valid")
  28. return False
  29. return True
  30. # define init random solution
  31. def init():
  32. return CombinatoryIntegerSolution.random(n, validator)
  33. def main():
  34. with open(qap_instance_file, 'r') as f:
  35. file_data = f.readlines()
  36. print(f'Instance information {file_data[0]}')
  37. D_lines = file_data[1:n + 1]
  38. D_data = ''.join(D_lines).replace('\n', '')
  39. F_lines = file_data[n:2 * n + 1]
  40. F_data = ''.join(F_lines).replace('\n', '')
  41. D_matrix = np.fromstring(D_data, dtype=float, sep=' ').reshape(n, n)
  42. print(f'D matrix shape: {D_matrix.shape}')
  43. F_matrix = np.fromstring(F_data, dtype=float, sep=' ').reshape(n, n)
  44. print(f'F matrix shape: {F_matrix.shape}')
  45. operators = [SimpleMutation()]
  46. policy = RandomPolicy(operators)
  47. callback = BasicCheckpoint(every=5, filepath=filepath)
  48. evaluator = QAPEvaluator(data={'F': F_matrix, 'D': D_matrix})
  49. # passing global evaluation param from ILS
  50. hcfi = HillClimberFirstImprovment(init, evaluator, operators, policy, validator, maximise=False, verbose=True)
  51. algo = ILS(init, evaluator, operators, policy, validator, localSearch=hcfi, maximise=False, verbose=True)
  52. # add callback into callback list
  53. algo.addCallback(callback)
  54. bestSol = algo.run(10000, ls_evaluations=100)
  55. print('Solution for QAP instance score is {}'.format(evaluator.compute(bestSol)))
  56. if __name__ == "__main__":
  57. main()