BasicCheckpoint.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if self.algo.parent is not None:
  37. self.algo.parent.numberOfEvaluations = globalEvaluation
  38. else:
  39. self.algo.numberOfEvaluations = globalEvaluation
  40. # get best solution data information
  41. solutionData = list(map(int, data[1].split(' ')))
  42. print(solutionData)
  43. self.algo.bestSolution.data = solutionData
  44. self.algo.bestSolution.score = float(data[2])
  45. else:
  46. logging.info("Can't load backup... Backup filepath not valid in Checkpoint")