MultiPopCheckpoint.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # main imports
  2. import os
  3. import logging
  4. import numpy as np
  5. # module imports
  6. from macop.callbacks.base import Callback
  7. from macop.utils.progress import macop_text, macop_line
  8. class MultiPopCheckpoint(Callback):
  9. """
  10. MultiCheckpoint is used for loading previous computations and start again after loading checkpoint
  11. Attributes:
  12. algo: {:class:`~macop.algorithms.base.Algorithm`} -- main algorithm instance reference
  13. every: {int} -- checkpoint frequency used (based on number of evaluations)
  14. filepath: {str} -- file path where checkpoints will be saved
  15. """
  16. def run(self):
  17. """
  18. Check if necessary to do backup based on `every` variable
  19. """
  20. # get current population
  21. population = self._algo.population
  22. currentEvaluation = self._algo.getGlobalEvaluation()
  23. # backup if necessary
  24. if currentEvaluation % self._every == 0:
  25. logging.info("Checkpoint is done into " + self._filepath)
  26. with open(self._filepath, 'a') as f:
  27. pop_line = str(currentEvaluation) + ';'
  28. scores = []
  29. pop_data = []
  30. for solution in population:
  31. solution_data = ""
  32. solutionSize = len(solution.data)
  33. for index, val in enumerate(solution.data):
  34. solution_data += str(val)
  35. if index < solutionSize - 1:
  36. solution_data += ' '
  37. scores.append(solution.fitness)
  38. pop_data.append(solution_data)
  39. for score in scores:
  40. pop_line += str(score) + ';'
  41. for data in pop_data:
  42. pop_line += data + ';'
  43. pop_line += '\n'
  44. f.write(pop_line)
  45. def load(self):
  46. """
  47. Load backup lines as population and set algorithm state (population and pareto front) at this backup
  48. """
  49. if os.path.exists(self._filepath):
  50. logging.info('Load best solution from last checkpoint')
  51. with open(self._filepath, 'r') as f:
  52. # read data for each line
  53. data_line = f.readlines()[-1]
  54. data = data_line.replace(';\n', '').split(';')
  55. # get evaluation information
  56. globalEvaluation = int(data[0])
  57. if self._algo.getParent() is not None:
  58. self._algo.getParent(
  59. )._numberOfEvaluations = globalEvaluation
  60. else:
  61. self._algo._numberOfEvaluations = globalEvaluation
  62. nSolutions = len(self._algo.population)
  63. scores = list(map(float, data[1:nSolutions + 1]))
  64. # get best solution data information
  65. pop_str_data = data[nSolutions + 1:]
  66. pop_data = []
  67. for sol_data in pop_str_data:
  68. current_data = list(map(int, sol_data.split(' ')))
  69. pop_data.append(current_data)
  70. for i, sol_data in enumerate(pop_data):
  71. # initialise and fill with data
  72. self._algo.population[i] = self._algo.initialiser()
  73. self._algo.population[i].data = np.array(sol_data)
  74. self._algo.population[i].fitness = scores[i]
  75. macop_line(self._algo)
  76. macop_text(
  77. self._algo,
  78. f'Load of available population from `{self._filepath}`')
  79. macop_text(
  80. self._algo,
  81. f'Restart algorithm from evaluation {self._algo._numberOfEvaluations}.'
  82. )
  83. else:
  84. macop_text(
  85. self._algo,
  86. 'No backup found... Start running algorithm from evaluation 0.'
  87. )
  88. logging.info(
  89. "Can't load backup... Backup filepath not valid in Checkpoint")
  90. macop_line(self._algo)