ParetoCheckpoint.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """Pareto front Checkpoint class implementation
  2. """
  3. # main imports
  4. import os
  5. import logging
  6. import numpy as np
  7. import sys
  8. # module imports
  9. from .Callback import Callback
  10. from ..utils.color import macop_text, macop_line
  11. from ..utils.modules import load_class
  12. class ParetoCheckpoint(Callback):
  13. """
  14. Pareto checkpoint is used for loading previous computations and start again after loading checkpoint
  15. Attributes:
  16. algo: {Algorithm} -- main algorithm instance reference
  17. every: {int} -- checkpoint frequency used (based on number of evaluations)
  18. filepath: {str} -- file path where checkpoints will be saved
  19. """
  20. def run(self):
  21. """
  22. Check if necessary to do backup based on `every` variable
  23. """
  24. # get current population
  25. pfPop = self._algo.pfPop
  26. currentEvaluation = self._algo.getGlobalEvaluation()
  27. # backup if necessary
  28. if currentEvaluation % self._every == 0:
  29. logging.info("Checkpoint is done into " + self._filepath)
  30. with open(self._filepath, 'w') as f:
  31. for solution in pfPop:
  32. solutionData = ""
  33. solutionSize = len(solution.data)
  34. for index, val in enumerate(solution.data):
  35. solutionData += str(val)
  36. if index < solutionSize - 1:
  37. solutionData += ' '
  38. line = ''
  39. for i in range(len(self._algo.evaluator)):
  40. line += str(solution.scores[i]) + ';'
  41. line += solutionData + ';\n'
  42. f.write(line)
  43. def load(self):
  44. """
  45. Load backup lines as population and set algorithm state (population and pareto front) at this backup
  46. """
  47. if os.path.exists(self._filepath):
  48. logging.info('Load best solution from last checkpoint')
  49. with open(self._filepath) as f:
  50. # reinit pf population
  51. self._algo.pfPop = []
  52. # retrieve class name from algo
  53. class_name = type(self._algo.population[0]).__name__
  54. # dynamically load solution class if unknown
  55. if class_name not in sys.modules:
  56. load_class(class_name, globals())
  57. # read data for each line
  58. for line in f.readlines():
  59. data = line.replace(';\n', '').split(';')
  60. nObjectives = len(self._algo.evaluator)
  61. scores = [float(s) for s in data[0:nObjectives]]
  62. # get best solution data information
  63. solutionData = list(map(int, data[-1].split(' ')))
  64. newSolution = getattr(
  65. globals()['macop.solutions.' + class_name],
  66. class_name)(solutionData, len(solutionData))
  67. newSolution.scores = scores
  68. self._algo.pfPop.append(newSolution)
  69. print(
  70. macop_text(
  71. 'Load of available pareto front backup from `{}`'.format(
  72. self._filepath)))
  73. else:
  74. print(
  75. macop_text(
  76. 'No pareto front found... Start running algorithm with new pareto front population.'
  77. ))
  78. logging.info("No pareto front backup used...")
  79. print(macop_line())