knapsacks.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Knapsack evaluators classes
  2. """
  3. # main imports
  4. from abc import abstractmethod
  5. from .base import Evaluator
  6. class KnapsackEvaluator(Evaluator):
  7. """Knapsack evaluator class which enables to compute solution using specific `_data`
  8. - stores into its `_data` dictionary attritute required measures when computing a knapsack solution
  9. - `_data['worths']` stores knapsack objects worths information
  10. - `_data['weights']` stores knapsack objects weights information
  11. - `compute` method enables to compute and associate a score to a given knapsack solution
  12. """
  13. def compute(self, solution):
  14. """Apply the computation of fitness from solution
  15. Args:
  16. solution: {Solution} -- Solution instance
  17. Returns:
  18. {float} -- fitness score of solution
  19. """
  20. fitness = 0
  21. for index, elem in enumerate(solution._data):
  22. fitness += self._data['worths'][index] * elem
  23. return fitness
  24. class KnapsackMultiEvaluator(Evaluator):
  25. """Knapsack multi-objective evaluator class which enables to compute solution using specific `_data`
  26. - stores into its `_data` dictionary attritute required measures when computing a knapsack solution
  27. - `_data['worths1']` stores knapsack objects worths information
  28. - `_data['worths2']` stores knapsack objects worths information
  29. - `_data['weights']` stores knapsack objects weights information
  30. - `compute` method enables to compute and associate a score to a given knapsack solution
  31. """
  32. def compute(self, solution):
  33. """Apply the computation of fitness from solution
  34. Args:
  35. solution: {Solution} -- Solution instance
  36. Returns:
  37. {float} -- fitness score of solution
  38. """
  39. fitness = 0
  40. for index, elem in enumerate(solution._data):
  41. fitness += self._data['worths1'][index] * elem
  42. return fitness