ParetoCheckpoint.py 3.5 KB

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