BasicCheckpoint.py 2.2 KB

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