BasicCheckpoint.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 .Checkpoint import Checkpoint
  9. from ..utils.color import macop_text, macop_line
  10. class BasicCheckpoint(Checkpoint):
  11. """
  12. BasicCheckpoint is used for loading previous computations and start again after loading checkpoit
  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 __init__(self, _algo, _every, _filepath):
  19. self.algo = _algo
  20. self.every = _every
  21. self.filepath = _filepath
  22. def run(self):
  23. """
  24. Check if necessary to do backup based on `every` variable
  25. """
  26. # get current best solution
  27. solution = self.algo.bestSolution
  28. currentEvaluation = self.algo.getGlobalEvaluation()
  29. # backup if necessary
  30. if currentEvaluation % self.every == 0:
  31. logging.info("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) + ';' + solutionData + ';' + str(
  39. 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 last backup line of solution and set algorithm state (best solution and evaluations) 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. # get last line and read data
  55. lastline = f.readlines()[-1]
  56. data = lastline.split(';')
  57. # get evaluation information
  58. globalEvaluation = int(data[0])
  59. if self.algo.parent is not None:
  60. self.algo.parent.numberOfEvaluations = globalEvaluation
  61. else:
  62. self.algo.numberOfEvaluations = globalEvaluation
  63. # get best solution data information
  64. solutionData = list(map(int, data[1].split(' ')))
  65. self.algo.bestSolution.data = np.array(solutionData)
  66. self.algo.bestSolution.score = float(data[2])
  67. print(
  68. macop_text('Restart algorithm from evaluation {}.'.format(
  69. self.algo.numberOfEvaluations)))
  70. else:
  71. print(
  72. macop_text(
  73. 'No backup found... Start running algorithm from evaluation 0.'
  74. ))
  75. print(macop_line())
  76. logging.info(
  77. "Can't load backup... Backup filepath not valid in Checkpoint")
  78. print(macop_line())