base.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Abstract solution class
  2. """
  3. from abc import abstractmethod
  4. from copy import deepcopy
  5. class Solution():
  6. def __init__(self, data, size):
  7. """
  8. Binary integer solution class
  9. Attributes:
  10. data: {ndarray} -- array of binary values
  11. size: {int} -- size of binary array values
  12. score: {float} -- fitness score value
  13. """
  14. self._data = data
  15. self._size = size
  16. self._score = None
  17. def isValid(self, validator):
  18. """
  19. Use of custom method which validates if solution is valid or not
  20. Args:
  21. validator: {function} -- specific function which validates or not a solution
  22. Returns:
  23. {bool} -- `True` is solution is valid
  24. """
  25. return validator(self)
  26. def evaluate(self, evaluator):
  27. """
  28. Evaluate solution using specific `evaluator`
  29. Args:
  30. _evaluator: {function} -- specific function which computes fitness of solution
  31. Returns:
  32. {float} -- fitness score value
  33. """
  34. self._score = evaluator.compute(self)
  35. return self._score
  36. def fitness(self):
  37. """
  38. Returns fitness score
  39. Returns:
  40. {float} -- fitness score value
  41. """
  42. return self._score
  43. @abstractmethod
  44. def random(self, validator):
  45. """
  46. Initialize solution using random data
  47. Args:
  48. validator: {function} -- specific function which validates or not a solution
  49. Returns:
  50. {Solution} -- generated solution
  51. """
  52. pass
  53. def clone(self):
  54. """Clone the current solution and its data, but without keeping evaluated `_score`
  55. Returns:
  56. {Solution} -- clone of current solution
  57. """
  58. copy_solution = deepcopy(self)
  59. copy_solution._score = None
  60. return copy_solution
  61. def __str__(self):
  62. print("Generic solution with ", self._data)