base.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """Abstract solution class
  2. """
  3. from abc import abstractmethod
  4. from copy import deepcopy
  5. class Solution():
  6. """Base abstract solution class structure
  7. - stores solution data representation into ndarray `data` attribute
  8. - get size (shape) of specific data representation
  9. - stores the score of the solution
  10. """
  11. def __init__(self, data, size):
  12. """
  13. Abstract solution class constructor
  14. Attributes:
  15. data: {ndarray} -- ndarray of values
  16. size: {int} -- size of ndarray values
  17. score: {float} -- fitness score value
  18. """
  19. self._data = data
  20. self._size = size
  21. self._score = None
  22. def isValid(self, validator):
  23. """
  24. Use of custom function which checks if a solution is valid or not
  25. Args:
  26. validator: {function} -- specific function which validates or not a solution
  27. Returns:
  28. {bool} -- `True` is solution is valid
  29. """
  30. return validator(self)
  31. def evaluate(self, evaluator):
  32. """
  33. Evaluate solution using specific `evaluator`
  34. Args:
  35. _evaluator: {function} -- specific function which computes fitness of solution
  36. Returns:
  37. {float} -- fitness score value
  38. """
  39. self._score = evaluator.compute(self)
  40. return self._score
  41. def fitness(self):
  42. """
  43. Returns fitness score
  44. Returns:
  45. {float} -- fitness score value
  46. """
  47. return self._score
  48. def getData(self):
  49. """
  50. Returns solution data
  51. Returns:
  52. {ndarray} -- data values
  53. """
  54. return self._data
  55. def setData(self, data):
  56. """
  57. Set solution data
  58. """
  59. self._data = data
  60. def setScore(self, score):
  61. """
  62. Set solution score as wished
  63. """
  64. self._score = score
  65. @staticmethod
  66. def random(size, validator=None):
  67. """
  68. initialise solution using random data with validator or not
  69. Args:
  70. size: {int} -- expected solution size to generate
  71. validator: {function} -- specific function which validates or not a solution (if None, not validation is applied)
  72. Returns:
  73. {Solution} -- generated solution
  74. """
  75. return None
  76. def clone(self):
  77. """Clone the current solution and its data, but without keeping evaluated `_score`
  78. Returns:
  79. {Solution} -- clone of current solution
  80. """
  81. copy_solution = deepcopy(self)
  82. copy_solution._score = None
  83. return copy_solution
  84. def __str__(self):
  85. print("Generic solution with ", self._data)