MultiSurrogateCheckpoint.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 MultiSurrogateCheckpoint(Callback):
  11. """
  12. MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices
  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. k_indices = self._algo._k_indices
  24. # Do nothing is surrogate analyser does not exist
  25. if k_indices is None:
  26. return
  27. currentEvaluation = self._algo.getGlobalEvaluation()
  28. # backup if necessary
  29. if currentEvaluation % self._every == 0:
  30. logging.info(f"Multi surrogate analysis checkpoint is done into {self._filepath}")
  31. line = str(currentEvaluation) + ';'
  32. for indices in k_indices:
  33. indices_data = ""
  34. indices_size = len(indices)
  35. for index, val in enumerate(indices):
  36. indices_data += str(val)
  37. if index < indices_size - 1:
  38. indices_data += ' '
  39. line += indices_data + ';'
  40. line += '\n'
  41. # check if file exists
  42. if not os.path.exists(self._filepath):
  43. with open(self._filepath, 'w') as f:
  44. f.write(line)
  45. else:
  46. with open(self._filepath, 'a') as f:
  47. f.write(line)
  48. def load(self):
  49. """
  50. Load nothing there, as we only log surrogate training information
  51. """
  52. if os.path.exists(self._filepath):
  53. logging.info('Load best solution from last checkpoint')
  54. with open(self._filepath) as f:
  55. # get last line and read data
  56. lastline = f.readlines()[-1].replace(';\n', '')
  57. data = lastline.split(';')
  58. k_indices = data[1:]
  59. k_indices_final = []
  60. for indices in k_indices:
  61. k_indices_final.append(list(map(int, indices.split(' '))))
  62. # set k_indices into main algorithm
  63. self._algo._k_indices = k_indices_final
  64. print(macop_line())
  65. print(macop_text(f' MultiSurrogateCheckpoint found from `{self._filepath}` file.'))
  66. else:
  67. print(macop_text('No backup found... Start running using new `k_indices` values'))
  68. logging.info("Can't load MultiSurrogate backup... Backup filepath not valid in MultiSurrogateCheckpoint")
  69. print(macop_line())