RandomSearch.runIteration()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 24
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 7
dl 0
loc 24
rs 10
c 0
b 0
f 0
1
# encoding=utf8
2
import logging
3
4
import numpy as np
5
6
from NiaPy.algorithms.algorithm import Algorithm
7
8
logging.basicConfig()
9
logger = logging.getLogger('NiaPy.algorithms.other')
10
logger.setLevel('INFO')
11
12
__all__ = ['RandomSearch']
13
14
class RandomSearch(Algorithm):
15
	r"""Implementation of a simple Random Algorithm.
16
17
	Algorithm:
18
		Random Search
19
20
	Date:
21
		11.10.2020
22
23
	Authors:
24
		Iztok Fister Jr., Grega Vrbančič
25
26
	License:
27
		MIT
28
29
	Reference URL: https://en.wikipedia.org/wiki/Random_search
30
31
	Attributes:
32
		Name (List[str]): List of strings representing algorithm name.
33
34
	See Also:
35
		* :class:`NiaPy.algorithms.Algorithm`
36
	"""
37
	Name = ['RandomSearch', 'RS']
38
39
	@staticmethod
40
	def algorithmInfo():
41
		r"""Get basic information of algorithm.
42
43
		Returns:
44
			str: Basic information of algorithm.
45
46
		See Also:
47
			* :func:`NiaPy.algorithms.Algorithm.algorithmInfo`
48
		"""
49
		return r"""None"""
50
51
	def setParameters(self, **ukwargs):
52
		r"""Set the algorithm parameters/arguments.
53
54
		Arguments:
55
		See Also
56
			* :func:`NiaPy.algorithms.Algorithm.setParameters`
57
		"""
58
59
		ukwargs.pop('NP', None)
60
		Algorithm.setParameters(self, NP=1)
61
62
	def getParameters(self):
63
		r"""Get algorithms parametes values.
64
65
		Returns:
66
			Dict[str, Any]:
67
		See Also
68
			* :func:`NiaPy.algorithms.Algorithm.getParameters`
69
		"""
70
		d = Algorithm.getParameters(self)
71
		return d
72
73
	def initPopulation(self, task):
74
		r"""Initialize the starting population.
75
76
		Args:
77
			task (Task): Optimization task.
78
		Returns:
79
			Tuple[numpy.ndarray, float, dict]:
80
			1. Initial solution
81
			2. Initial solutions fitness/objective value
82
			3. Additional arguments
83
		"""
84
		total_candidates = 0
85
		if task.nGEN or task.nFES:
86
			total_candidates = task.nGEN if task.nGEN else task.nFES
87
		self.candidates = []
88
		for i in range(total_candidates):
89
			while True:
90
				x = task.Lower + task.bcRange() * self.rand(task.D)
91
				if not np.any([np.all(a == x) for a in self.candidates]):
92
					self.candidates.append(x)
93
					break
94
95
		xfit = task.eval(self.candidates[0])
96
		return x, xfit, {}
0 ignored issues
show
introduced by
The variable x does not seem to be defined in case the for loop on line 88 is not entered. Are you sure this can never be the case?
Loading history...
97
98
	def runIteration(self, task, x, xfit, xb, fxb, **dparams):
99
		r"""Core function of the algorithm.
100
101
		Args:
102
			task (Task):
103
			x (numpy.ndarray):
104
			xfit (float):
105
			xb (numpy.ndarray):
106
			fxb (float):
107
			**dparams (dict): Additional arguments.
108
109
		Returns:
110
			Tuple[numpy.ndarray, float, numpy.ndarray, float, dict]:
111
			1. New solution
112
			2. New solutions fitness/objective value
113
			3. New global best solution
114
			4. New global best solutions fitness/objective value
115
			5. Additional arguments
116
		"""
117
		current_candidate = task.Evals if task.Evals else task.Iters
118
		x = self.candidates[current_candidate]
119
		xfit = task.eval(x)
120
		xb, fxb = self.getBest(x, xfit, xb, fxb)
121
		return x, xfit, xb, fxb, {}
122