classicals.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """Classical policies classes implementations
  2. """
  3. # main imports
  4. import random
  5. # module imports
  6. from macop.policies.base import Policy
  7. class RandomPolicy(Policy):
  8. """Policy class implementation which is used for select operator randomly from the `operators` list
  9. Attributes:
  10. operators: {[:class:`~macop.operators.base.Operator`]} -- list of selected operators for the algorithm
  11. Example:
  12. >>> import random
  13. >>> random.seed(42)
  14. >>> from macop.operators.discrete.crossovers import SimpleCrossover
  15. >>> from macop.operators.discrete.mutators import SimpleMutation
  16. >>> from macop.policies.classicals import RandomPolicy
  17. >>>
  18. >>> # create policy instance and select next operator to apply using policy
  19. >>> policy = RandomPolicy([SimpleCrossover(), SimpleMutation()])
  20. >>> operator = policy.select()
  21. >>> type(operator).__name__
  22. 'SimpleCrossover'
  23. """
  24. def select(self):
  25. """Select randomly the next operator to use
  26. Returns:
  27. {:class:`~macop.operators.base.Operator`}: the selected operator
  28. """
  29. # choose operator randomly
  30. index = random.randint(0, len(self._operators) - 1)
  31. return self._operators[index]