base.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. @staticmethod
  61. def random(size, validator=None):
  62. """
  63. Initialize solution using random data with validator or not
  64. Args:
  65. size: {int} -- expected solution size to generate
  66. validator: {function} -- specific function which validates or not a solution (if None, not validation is applied)
  67. Returns:
  68. {Solution} -- generated solution
  69. """
  70. return None
  71. def clone(self):
  72. """Clone the current solution and its data, but without keeping evaluated `_score`
  73. Returns:
  74. {Solution} -- clone of current solution
  75. """
  76. copy_solution = deepcopy(self)
  77. copy_solution._score = None
  78. return copy_solution
  79. def __str__(self):
  80. print("Generic solution with ", self._data)