SurrogateCheckpoint.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Basic Checkpoint class implementation
  2. """
  3. # main imports
  4. import os
  5. import logging
  6. import numpy as np
  7. # module imports
  8. from macop.callbacks.Callback import Callback
  9. from macop.utils.color import macop_text, macop_line
  10. class SurrogateCheckpoint(Callback):
  11. """
  12. SurrogateCheckpoint is used for logging training data information about surrogate
  13. Attributes:
  14. algo: {Algorithm} -- main algorithm instance reference
  15. every: {int} -- checkpoint frequency used (based on number of evaluations)
  16. filepath: {str} -- file path where checkpoints will be saved
  17. """
  18. def run(self):
  19. """
  20. Check if necessary to do backup based on `every` variable
  21. """
  22. # get current best solution
  23. solution = self._algo._bestSolution
  24. surrogate_analyser = self._algo._surrogate_analyser
  25. # Do nothing is surrogate analyser does not exist
  26. if surrogate_analyser is None:
  27. return
  28. currentEvaluation = self._algo.getGlobalEvaluation()
  29. # backup if necessary
  30. if currentEvaluation % self._every == 0:
  31. logging.info(f"Surrogate analysis checkpoint is done into {self._filepath}")
  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 = str(currentEvaluation) + ';' + str(surrogate_analyser._every_ls) + ';' + str(surrogate_analyser._time) + ';' + str(surrogate_analyser._r2) \
  39. + ';' + solutionData + ';' + str(solution.fitness()) + ';\n'
  40. # check if file exists
  41. if not os.path.exists(self._filepath):
  42. with open(self._filepath, 'w') as f:
  43. f.write(line)
  44. else:
  45. with open(self._filepath, 'a') as f:
  46. f.write(line)
  47. def load(self):
  48. """
  49. Load nothing there, as we only log surrogate training information
  50. """
  51. logging.info("No loading to do with surrogate checkpoint")