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

11 statements  

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

1""" 

2The `1rs` "algorithm" creates one single random solution. 

3 

4The single random sample algorithm applies the nullary search operator, 

5an implementation of :meth:`~moptipy.api.operators.Op0.op0`, 

6to sample exactly one single random solution. It then evaluates the 

7solution by passing it to 

8:meth:`~moptipy.api.process.Process.evaluate`. It then terminates. 

9 

10This is a very very bad optimization algorithm. We only use it in our 

11book to illustrate one basic concept for solving optimization problems: 

12The generation of random solutions. The single-random sampling 

13algorithm here is actually very wasteful: since it only generates 

14exactly one single solution, it does not use its computational budget 

15well. Even if you grant it 10'000 years, it will still only generate 

16one solution. Even if it could generate and test thousands or millions 

17of solutions, it will not do it. Nevertheless, after applying this 

18"algorithm," you will have one valid solution remembered in the 

19optimization process (embodied as instance `process` of 

20:class:`~moptipy.api.process.Process`). 

21 

22This concept of random sampling is then refined in the 

23:class:`~moptipy.algorithms.random_sampling.RandomSampling` as the `rs` 

24algorithm, which repeats generating random solutions until its allotted 

25runtime is exhausted. 

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 Final 

32 

33from moptipy.api.algorithm import Algorithm0 

34from moptipy.api.operators import Op0 

35from moptipy.api.process import Process 

36 

37 

38# start book 

39class SingleRandomSample(Algorithm0): 

40 """An algorithm that creates one single random solution.""" 

41 

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

43 """ 

44 Apply single random sampling to an optimization problem. 

45 

46 :param process: the black-box process object 

47 """ 

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

49 self.op0.op0(process.get_random(), x) # Create random solution 

50 process.evaluate(x) # Evaluate that random solution. 

51# end book 

52 

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

54 """ 

55 Create the single random sample algorithm. 

56 

57 :param op0: the nullary search operator 

58 """ 

59 super().__init__("1rs", op0)