Coverage for moptipy / algorithms / random_sampling.py: 100%

17 statements  

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

1""" 

2The random sampling algorithm `rs`. 

3 

4The random sampling algorithm keeps creating random solutions until 

5the computational budget is exhausted or any other termination 

6criterion is met. 

7In a loop that is repeated until the termination criterion 

8:meth:`~moptipy.api.process.Process.should_terminate` becomes `True`, 

9it 

10 

11- applies the nullary search operator, an implementation of 

12 :meth:`~moptipy.api.operators.Op0.op0`, to sample exactly one single 

13 random solution. It then 

14- evaluates the solution by passing it to 

15 :meth:`~moptipy.api.process.Process.evaluate`. 

16 

17This algorithm has a very bad performance. It makes no use of the 

18information that is learned during the search. Every single solution is 

19created completely independent on anything that has happened before 

20in the algorithm. Only if the problem is completely random, has no 

21structure, or is entirely deceptive, this algorithm can be of any use. 

22 

23Basically, this algorithm is an iterated version of the `1rs` algorithm 

24implemented in 

25:class:`~moptipy.algorithms.single_random_sample.SingleRandomSample`. 

26 

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

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

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

30""" 

31from typing import Callable, Final 

32 

33from numpy.random import Generator 

34 

35from moptipy.api.algorithm import Algorithm0 

36from moptipy.api.operators import Op0 

37from moptipy.api.process import Process 

38 

39 

40# start book 

41class RandomSampling(Algorithm0): 

42 """In each step, random sampling creates a new, random solution.""" 

43 

44 def solve(self, process: Process) -> None: 

45 """ 

46 Apply the random sampling approach to an optimization problem. 

47 

48 :param process: the black-box process object 

49 """ 

50 x: Final = process.create() # Create the solution record. 

51 # Obtain the random number generator. 

52 random: Final[Generator] = process.get_random() 

53 

54 # Put function references in variables to save time. 

55 evaluate: Final[Callable] = process.evaluate # the objective 

56 op0: Final[Callable] = self.op0.op0 # the nullary operator 

57 should_terminate: Final[Callable] = process.should_terminate 

58 

59 while not should_terminate(): # Until we need to quit... 

60 op0(random, x) # Sample a completely random solution. 

61 evaluate(x) # Evaluate the solution ... but ignore result. 

62# end book 

63 

64 def __init__(self, op0: Op0) -> None: 

65 """ 

66 Create the random sampling algorithm. 

67 

68 :param op0: the nullary search operator 

69 """ 

70 super().__init__("rs", op0)