BasicCheckpoint.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # main imports
  2. import os
  3. import logging
  4. # module imports
  5. from .Checkpoint import Checkpoint
  6. class BasicCheckpoint(Checkpoint):
  7. def __init__(self, _algo, _every, _filepath):
  8. self.algo = _algo
  9. self.every = _every
  10. self.filepath = _filepath
  11. def run(self):
  12. # get current best solution
  13. solution = self.algo.bestSolution
  14. currentEvaluation = self.algo.getGlobalEvaluation()
  15. # backup if necessary
  16. if currentEvaluation % self.every == 0:
  17. logging.info("Checkpoint is done into " + self.filepath)
  18. cleanSolution = str(solution.data).replace('[', '').replace(']', '')
  19. line = str(currentEvaluation) + ';' + cleanSolution + ';' + str(solution.fitness()) + ';\n'
  20. # check if file exists
  21. if not os.path.exists(self.filepath):
  22. with open(self.filepath, 'w') as f:
  23. f.write(line)
  24. else:
  25. with open(self.filepath, 'a') as f:
  26. f.write(line)
  27. def load(self):
  28. if os.path.exists(self.filepath):
  29. logging.info('Load best solution from last checkpoint')
  30. with open(self.filepath) as f:
  31. # get last line and read data
  32. lastline = f.readlines()[-1]
  33. data = lastline.split(';')
  34. # get evaluation information
  35. globalEvaluation = int(data[0])
  36. print(globalEvaluation, data)
  37. if self.algo.parent is not None:
  38. self.algo.parent.numberOfEvaluations = globalEvaluation
  39. else:
  40. self.algo.numberOfEvaluations = globalEvaluation
  41. print(self.algo.numberOfEvaluations)
  42. # get best solution data information
  43. solutionData = list(map(int, data[1].split(' ')))
  44. print(solutionData)
  45. self.algo.bestSolution.data = solutionData
  46. self.algo.bestSolution.score = float(data[2])
  47. else:
  48. logging.info("Can't load backup... Backup filepath not valid in Checkpoint")