mono.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Knapsack evaluators classes
  2. """
  3. # main imports
  4. from ..base import Evaluator
  5. class KnapsackEvaluator(Evaluator):
  6. """Knapsack evaluator class which enables to compute solution using specific `_data`
  7. - stores into its `_data` dictionary attritute required measures when computing a knapsack solution
  8. - `_data['worths']` stores knapsack objects worths information
  9. - `compute` method enables to compute and associate a score to a given knapsack solution
  10. Example:
  11. >>> import random
  12. >>> # binary solution import
  13. >>> from macop.solutions.discrete import BinarySolution
  14. >>> # evaluator import
  15. >>> from macop.evaluators.discrete.mono import KnapsackEvaluator
  16. >>> solution_data = [1, 0, 0, 1, 1, 0, 1, 0]
  17. >>> size = len(solution_data)
  18. >>> solution = BinarySolution(solution_data, size)
  19. >>> # evaluator initialization (worths objects passed into data)
  20. >>> worths = [ random.randint(5, 20) for i in range(size) ]
  21. >>> evaluator = KnapsackEvaluator(data={'worths': worths})
  22. >>> # compute solution score
  23. >>> evaluator.compute(solution)
  24. 40
  25. """
  26. def compute(self, solution):
  27. """Apply the computation of fitness from solution
  28. Args:
  29. solution: {Solution} -- Solution instance
  30. Returns:
  31. {float} -- fitness score of solution
  32. """
  33. fitness = 0
  34. for index, elem in enumerate(solution._data):
  35. fitness += self._data['worths'][index] * elem
  36. return fitness