validator.rst 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 4. Validate a solution
  2. ======================
  3. When an optimization problem requires respecting certain constraints, Macop allows you to quickly verify that a solution is valid.
  4. It is based on a defined function taking a solution as input and returning the validity criterion (true or false).
  5. 4.1. Validator definition
  6. ~~~~~~~~~~~~~~~~~~~~~~~~~
  7. An invalid solution can be shown below where the sum of the object weights is greater than 15:
  8. .. image:: ../_static/documentation/project_knapsack_invalid.png
  9. :width: 800 px
  10. :align: center
  11. .. code-block::
  12. Hence, ``[1, 0, 1, 0, 0]`` is an invalid solution.
  13. .. code-block:: python
  14. """
  15. Problem instance definition
  16. """
  17. elements_score = [ 4, 2, 10, 1, 2 ] # value of each object
  18. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  19. """
  20. validator function definition
  21. """
  22. def validator(solution):
  23. weight_sum = 0
  24. for i, w in enumerate(elements_weight):
  25. weight_sum += w * solution._data[i]
  26. return weight_sum <= 15
  27. 4.2. Use of validator
  28. ~~~~~~~~~~~~~~~~~~~~~