Coverage for moptipy / operators / permutations / op0_shuffle.py: 94%

17 statements  

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

1""" 

2A nullary operator shuffling a permutation. 

3 

4This operator first copies the canonical permutation to the destination 

5string. It then applies the shuffle procedure of the random number 

6generator, which probably internally applies a Fisher-Yates Shuffle. 

7The result is a random permutation. 

8 

91. Thomas Weise. *Optimization Algorithms.* 2021. Hefei, Anhui, China: 

10 Institute of Applied Optimization (IAO), School of Artificial Intelligence 

11 and Big Data, Hefei University. http://thomasweise.github.io/oa/ 

12""" 

13from typing import Final 

14 

15import numpy as np 

16from numpy.random import Generator 

17from pycommons.types import type_error 

18 

19from moptipy.api.operators import Op0 

20from moptipy.spaces.permutations import Permutations 

21 

22 

23# start book 

24class Op0Shuffle(Op0): 

25 """Shuffle permutations randomly.""" 

26 

27 def __init__(self, space: Permutations): 

28 """ 

29 Initialize this shuffle operation: use blueprint from space. 

30 

31 :param space: the search space 

32 """ 

33 super().__init__() # -book 

34 if not isinstance(space, Permutations): # -book 

35 raise type_error(space, "space", Permutations) # -book 

36 #: the internal blueprint for filling permutations 

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

38 

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

40 """ 

41 Copy the base string to `dest` and shuffle it randomly. 

42 

43 :param random: the random number generator 

44 :param dest: the permutation that should be filled with a random 

45 sequence of the base permutation. 

46 """ 

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

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

49 # end book 

50 

51 def __str__(self) -> str: 

52 """ 

53 Get the name of this operator. 

54 

55 :return: "shuffle" 

56 """ 

57 return "shuffle"