Coverage for moptipy / operators / ordered_choices / op0_choose_and_shuffle.py: 96%

23 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-11-24 08:49 +0000

1"""A nullary operator filling a :mod:`~moptipy.spaces.ordered_choices`.""" 

2from typing import Callable, Final 

3 

4import numpy as np 

5from numpy.random import Generator 

6from pycommons.types import type_error 

7 

8from moptipy.api.operators import Op0 

9from moptipy.spaces.ordered_choices import OrderedChoices 

10 

11 

12class Op0ChooseAndShuffle(Op0): 

13 """Randomly initialize :mod:`~moptipy.spaces.ordered_choices` elements.""" 

14 

15 def __init__(self, space: OrderedChoices): 

16 """ 

17 Initialize this shuffle operation: use blueprint from space. 

18 

19 :param space: the search space 

20 """ 

21 super().__init__() 

22 if not isinstance(space, OrderedChoices): 

23 raise type_error(space, "space", OrderedChoices) 

24 #: the internal blueprint for filling permutations 

25 self.__blueprint: Final[np.ndarray] = space.blueprint 

26 #: the internal choices 

27 self.__choices: Final[Callable[[int], tuple[int, ...]]] \ 

28 = space.choices.__getitem__ 

29 

30 def op0(self, random: Generator, dest: np.ndarray) -> None: 

31 """ 

32 Fill the destination with random choices and shuffle it. 

33 

34 :param random: the random number generator 

35 :param dest: the destination array 

36 """ 

37 np.copyto(dest, self.__blueprint) # Copy blueprint to dest. 

38 random.shuffle(dest) # Shuffle destination array randomly. 

39 

40 # Now we replace the elements in the shuffled destination array 

41 # with random selections. 

42 ri: Final[Callable[[int], int]] = random.integers # fast call 

43 choices: Final[Callable[[int], tuple[int, ...]]] = self.__choices 

44 for i, e in enumerate(dest): 

45 source = choices(e) 

46 dest[i] = source[ri(len(source))] 

47 

48 def __str__(self) -> str: 

49 """ 

50 Get the name of this operator. 

51 

52 :return: "chooseAndShuffle" 

53 """ 

54 return "chooseAndShuffle"