BasicCheckpoint.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. class BasicCheckpoint(Checkpoint):
  10. """
  11. BasicCheckpoint is used for loading previous computations and start again after loading checkpoit
  12. Attributes:
  13. algo: {Algorithm} -- main algorithm instance reference
  14. every: {int} -- checkpoint frequency used (based on number of evaluations)
  15. filepath: {str} -- file path where checkpoints will be saved
  16. """
  17. def __init__(self, _algo, _every, _filepath):
  18. self.algo = _algo
  19. self.every = _every
  20. self.filepath = _filepath
  21. def run(self):
  22. """
  23. Check if necessary to do backup based on `every` variable
  24. """
  25. # get current best solution
  26. solution = self.algo.bestSolution
  27. currentEvaluation = self.algo.getGlobalEvaluation()
  28. # backup if necessary
  29. if currentEvaluation % self.every == 0:
  30. logging.info("Checkpoint is done into " + self.filepath)
  31. solutionData = ""
  32. solutionSize = len(solution.data)
  33. for index, val in enumerate(solution.data):
  34. solutionData += str(val)
  35. if index < solutionSize - 1:
  36. solutionData += ' '
  37. line = str(currentEvaluation) + ';' + solutionData + ';' + str(
  38. solution.fitness()) + ';\n'
  39. # check if file exists
  40. if not os.path.exists(self.filepath):
  41. with open(self.filepath, 'w') as f:
  42. f.write(line)
  43. else:
  44. with open(self.filepath, 'a') as f:
  45. f.write(line)
  46. def load(self):
  47. """
  48. Load last backup line of solution and set algorithm state (best solution and evaluations) at this backup
  49. """
  50. if os.path.exists(self.filepath):
  51. logging.info('Load best solution from last checkpoint')
  52. with open(self.filepath) as f:
  53. # get last line and read data
  54. lastline = f.readlines()[-1]
  55. data = lastline.split(';')
  56. # get evaluation information
  57. globalEvaluation = int(data[0])
  58. if self.algo.parent is not None:
  59. self.algo.parent.numberOfEvaluations = globalEvaluation
  60. else:
  61. self.algo.numberOfEvaluations = globalEvaluation
  62. # get best solution data information
  63. solutionData = list(map(int, data[1].split(' ')))
  64. self.algo.bestSolution.data = np.array(solutionData)
  65. self.algo.bestSolution.score = float(data[2])
  66. else:
  67. print('No backup found... Start running')
  68. logging.info(
  69. "Can't load backup... Backup filepath not valid in Checkpoint")