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)