GravitationalSearchAlgorithm.algorithmInfo()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
# encoding=utf8
2
import logging
3
4
from numpy import apply_along_axis, asarray, argmin, argmax, sum, full
5
6
from NiaPy.algorithms.algorithm import Algorithm
7
8
__all__ = ['GravitationalSearchAlgorithm']
9
10
logging.basicConfig()
11
logger = logging.getLogger('NiaPy.algorithms.basic')
12
logger.setLevel('INFO')
13
14
class GravitationalSearchAlgorithm(Algorithm):
15
	r"""Implementation of Gravitational Search Algorithm.
16
17
	Algorithm:
18
		Gravitational Search Algorithm
19
20
	Date:
21
		2018
22
23
	Author:
24
		Klemen Berkoivč
25
26
	License:
27
		MIT
28
29
	Reference URL:
30
		https://doi.org/10.1016/j.ins.2009.03.004
31
32
	Reference paper:
33
		Esmat Rashedi, Hossein Nezamabadi-pour, Saeid Saryazdi, GSA: A Gravitational Search Algorithm, Information Sciences, Volume 179, Issue 13, 2009, Pages 2232-2248, ISSN 0020-0255
34
35
	Attributes:
36
		Name (List[str]): List of strings representing algorithm name.
37
38
	See Also:
39
		* :class:`NiaPy.algorithms.algorithm.Algorithm`
40
	"""
41
	Name = ['GravitationalSearchAlgorithm', 'GSA']
42
43
	@staticmethod
44
	def algorithmInfo():
45
		r"""Get algorithm information.
46
47
		Returns:
48
			str: Algorithm information.
49
		"""
50
		return r"""Esmat Rashedi, Hossein Nezamabadi-pour, Saeid Saryazdi, GSA: A Gravitational Search Algorithm, Information Sciences, Volume 179, Issue 13, 2009, Pages 2232-2248, ISSN 0020-0255"""
51
52 View Code Duplication
	@staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
53
	def typeParameters():
54
		r"""TODO.
55
56
		Returns:
57
			Dict[str, Callable]:
58
				* G_0 (Callable[[Union[int, float]], bool]): TODO
59
				* epsilon (Callable[[float], bool]): TODO
60
61
		See Also:
62
			* :func:`NiaPy.algorithms.algorithm.Algorithm.typeParameters`
63
		"""
64
		d = Algorithm.typeParameters()
65
		d.update({
66
			'G_0': lambda x: isinstance(x, (int, float)) and x >= 0,
67
			'epsilon': lambda x: isinstance(x, float) and 0 < x < 1
68
		})
69
		return d
70
71
	def setParameters(self, NP=40, G_0=2.467, epsilon=1e-17, **ukwargs):
72
		r"""Set the algorithm parameters.
73
74
		Arguments:
75
			G_0 (float): Starting gravitational constant.
76
			epsilon (float): TODO.
77
78
		See Also:
79
			* :func:`NiaPy.algorithms.algorithm.Algorithm.setParameters`
80
		"""
81
		Algorithm.setParameters(self, NP=NP, **ukwargs)
82
		self.G_0, self.epsilon = G_0, epsilon
83
84
	def getParameters(self):
85
		r"""Get algorithm parameters values.
86
87
		Returns:
88
			Dict[str, Any]: TODO.
89
90
		See Also:
91
			* :func:`NiaPy.algorithms.algorithm.Algorithm.getParameters`
92
		"""
93
		d = Algorithm.getParameters(self)
94
		d.update({
95
			'G_0': self.G_0,
96
			'epsilon': self.epsilon
97
		})
98
		return d
99
100
	def G(self, t):
101
		r"""TODO.
102
103
		Args:
104
			t (int): TODO
105
106
		Returns:
107
			float: TODO
108
		"""
109
		return self.G_0 / t
110
111
	def d(self, x, y, ln=2):
112
		r"""TODO.
113
114
		Args:
115
			x:
116
			y:
117
			ln:
118
119
		Returns:
120
			TODO
121
		"""
122
		return sum((x - y) ** ln) ** (1 / ln)
123
124
	def initPopulation(self, task):
125
		r"""Initialize staring population.
126
127
		Args:
128
			task (Task): Optimization task.
129
130
		Returns:
131
			Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:
132
				1. Initialized population.
133
				2. Initialized populations fitness/function values.
134
				3. Additional arguments:
135
					* v (numpy.ndarray[float]): TODO
136
137
		See Also:
138
			* :func:`NiaPy.algorithms.algorithm.Algorithm.initPopulation`
139
		"""
140
		X, X_f, _ = Algorithm.initPopulation(self, task)
141
		v = full([self.NP, task.D], 0.0)
142
		return X, X_f, {'v': v}
143
144
	def runIteration(self, task, X, X_f, xb, fxb, v, **dparams):
145
		r"""Core function of GravitationalSearchAlgorithm algorithm.
146
147
		Args:
148
			task (Task): Optimization task.
149
			X (numpy.ndarray): Current population.
150
			X_f (numpy.ndarray): Current populations fitness/function values.
151
			xb (numpy.ndarray): Global best solution.
152
			fxb (float): Global best fitness/function value.
153
			v (numpy.ndarray): TODO
154
			**dparams (Dict[str, Any]): Additional arguments.
155
156
		Returns:
157
			Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, float, Dict[str, Any]]:
158
				1. New population.
159
				2. New populations fitness/function values.
160
				3. New global best solution
161
				4. New global best solutions fitness/objective value
162
				5. Additional arguments:
163
					* v (numpy.ndarray): TODO
164
		"""
165
		ib, iw = argmin(X_f), argmax(X_f)
166
		m = (X_f - X_f[iw]) / (X_f[ib] - X_f[iw])
167
		M = m / sum(m)
168
		Fi = asarray([[self.G(task.Iters) * ((M[i] * M[j]) / (self.d(X[i], X[j]) + self.epsilon)) * (X[j] - X[i]) for j in range(len(M))] for i in range(len(M))])
169
		F = sum(self.rand([self.NP, task.D]) * Fi, axis=1)
170
		a = F.T / (M + self.epsilon)
171
		v = self.rand([self.NP, task.D]) * v + a.T
172
		X = apply_along_axis(task.repair, 1, X + v, self.Rand)
173
		X_f = apply_along_axis(task.eval, 1, X)
174
		xb, fxb = self.getBest(X, X_f, xb, fxb)
175
		return X, X_f, xb, fxb, {'v': v}
176
177
# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
178