Solution.py 1.6 KB

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