validator.rst 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. Validate a solution
  2. ======================
  3. When an optimisation 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. 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. In fact, **[1, 0, 1, 0, 0]** is an invalid solution as we have a weight of **16** which violates the knapsack capacity constraint.
  12. To avoid taking into account invalid solutions, we can define our function which will validate or not a solution based on our problem instance:
  13. .. code-block:: python
  14. """
  15. Problem instance definition
  16. """
  17. elements_score = [ 4, 2, 10, 1, 2 ] # worth 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. # add weight if current object is set to 1
  26. weight_sum += w * solution._data[i]
  27. # validation condition
  28. return weight_sum <= 15
  29. Use of validator
  30. ~~~~~~~~~~~~~~~~~~~~~
  31. We can now generate solutions randomly by passing our validation function as a parameter:
  32. .. code-block:: python
  33. """
  34. Problem instance definition
  35. """
  36. ...
  37. """
  38. Validator function definition
  39. """
  40. ...
  41. # ensure valid solution
  42. solution = BinarySolution.random(5, validator)
  43. .. warning::
  44. If the search space for valid solutions is very small compared to the overall search space, this can involve a considerable time for validating the solution and therefore obtaining a solution.
  45. The validation of a solution is therefore now possible. In the next part we will focus on the evaluation of a solution.