base.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 `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} -- array of binary values
  16. size: {int} -- size of binary array 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. @staticmethod
  49. def random(size, validator=None):
  50. """
  51. Initialize solution using random data with validator or not
  52. Args:
  53. size: {int} -- expected solution size to generate
  54. validator: {function} -- specific function which validates or not a solution (if None, not validation is applied)
  55. Returns:
  56. {Solution} -- generated solution
  57. """
  58. return None
  59. def clone(self):
  60. """Clone the current solution and its data, but without keeping evaluated `_score`
  61. Returns:
  62. {Solution} -- clone of current solution
  63. """
  64. copy_solution = deepcopy(self)
  65. copy_solution._score = None
  66. return copy_solution
  67. def __str__(self):
  68. print("Generic solution with ", self._data)