ZdtExample.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 BinarySolution
  8. from macop.evaluators.discrete.mono import UBQPEvaluator
  9. from macop.operators.continuous.mutators import SimpleMutation
  10. from macop.operators.discrete.mutators import SimpleBinaryMutation
  11. from macop.policies.classicals import RandomPolicy
  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.log', level=logging.DEBUG)
  19. random.seed(42)
  20. # usefull instance data
  21. n = 100
  22. ubqp_instance_file = 'instances/ubqp/ubqp_instance.txt'
  23. filepath = "data/checkpoints_ubqp.csv"
  24. # default validator
  25. def validator(solution):
  26. return True
  27. # define init random solution
  28. def init():
  29. return BinarySolution.random(n, validator)
  30. filepath = "data/checkpoints.csv"
  31. def main():
  32. # load UBQP instance
  33. with open(ubqp_instance_file, 'r') as f:
  34. lines = f.readlines()
  35. # get all string floating point values of matrix
  36. Q_data = ''.join([ line.replace('\n', '') for line in lines[8:] ])
  37. # load the concatenate obtained string
  38. Q_matrix = np.fromstring(Q_data, dtype=float, sep=' ').reshape(n, n)
  39. print(f'Q_matrix shape: {Q_matrix.shape}')
  40. operators = [SimpleBinaryMutation(), SimpleMutation()]
  41. policy = RandomPolicy(operators)
  42. callback = BasicCheckpoint(every=5, filepath=filepath)
  43. evaluator = UBQPEvaluator(data={'Q': Q_matrix})
  44. # passing global evaluation param from ILS
  45. hcfi = HillClimberFirstImprovment(init, evaluator, operators, policy, validator, maximise=True, verbose=True)
  46. algo = ILS(init, evaluator, operators, policy, validator, localSearch=hcfi, maximise=True, verbose=True)
  47. # add callback into callback list
  48. algo.addCallback(callback)
  49. bestSol = algo.run(10000, ls_evaluations=100)
  50. print('Solution for UBQP instance score is {}'.format(evaluator.compute(bestSol)))
  51. if __name__ == "__main__":
  52. main()