BasicCheckpoint.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 .Callback import Callback
  9. from ..utils.color import macop_text, macop_line
  10. class BasicCheckpoint(Callback):
  11. """
  12. BasicCheckpoint is used for loading previous computations and start again after loading checkpoint
  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. currentEvaluation = self._algo.getGlobalEvaluation()
  25. # backup if necessary
  26. if currentEvaluation % self._every == 0:
  27. logging.info("Checkpoint is done into " + self._filepath)
  28. solutionData = ""
  29. solutionSize = len(solution.data)
  30. for index, val in enumerate(solution.data):
  31. solutionData += str(val)
  32. if index < solutionSize - 1:
  33. solutionData += ' '
  34. line = str(currentEvaluation) + ';' + solutionData + ';' + str(
  35. solution.fitness()) + ';\n'
  36. # check if file exists
  37. if not os.path.exists(self._filepath):
  38. with open(self._filepath, 'w') as f:
  39. f.write(line)
  40. else:
  41. with open(self._filepath, 'a') as f:
  42. f.write(line)
  43. def load(self):
  44. """
  45. Load last backup line of solution and set algorithm state (best solution and evaluations) 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. # get last line and read data
  51. lastline = f.readlines()[-1]
  52. data = lastline.split(';')
  53. # get evaluation information
  54. globalEvaluation = int(data[0])
  55. if self._algo.getParent() is not None:
  56. self._algo.getParent().numberOfEvaluations = globalEvaluation
  57. else:
  58. self._algo._numberOfEvaluations = globalEvaluation
  59. # get best solution data information
  60. solutionData = list(map(int, data[1].split(' ')))
  61. if self._algo._bestSolution is None:
  62. self._algo._bestSolution = self._algo.initializer()
  63. self._algo._bestSolution.data = np.array(solutionData)
  64. self._algo._bestSolution.score = float(data[2])
  65. print(macop_line())
  66. print(
  67. macop_text('Checkpoint found from `{}` file.'.format(
  68. self._filepath)))
  69. print(
  70. macop_text('Restart algorithm from evaluation {}.'.format(
  71. self._algo._numberOfEvaluations)))
  72. else:
  73. print(
  74. macop_text(
  75. 'No backup found... Start running algorithm from evaluation 0.'
  76. ))
  77. logging.info(
  78. "Can't load backup... Backup filepath not valid in Checkpoint")
  79. print(macop_line())