Completed
Push — master ( ff5cab...a135cc )
by
unknown
17s queued 13s
created

FlowerPollinationAlgorithm.runIteration()   A

Complexity

Conditions 5

Size

Total Lines 29
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nop 8
dl 0
loc 29
rs 9.3333
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
# encoding=utf8
2
import logging
3
4
from scipy.special import gamma as Gamma
5
from numpy import where, sin, fabs, pi, zeros
6
7
from NiaPy.algorithms.algorithm import Algorithm
8
9
logging.basicConfig()
10
logger = logging.getLogger('NiaPy.algorithms.basic')
11
logger.setLevel('INFO')
12
13
__all__ = ['FlowerPollinationAlgorithm']
14
15
class FlowerPollinationAlgorithm(Algorithm):
16
	r"""Implementation of Flower Pollination algorithm.
17
18
	Algorithm:
19
		Flower Pollination algorithm
20
21
	Date:
22
		2018
23
24
	Authors:
25
		Dusan Fister, Iztok Fister Jr. and Klemen Berkovič
26
27
	License:
28
		MIT
29
30
	Reference paper:
31
		Yang, Xin-She. "Flower pollination algorithm for global optimization. International conference on unconventional computing and natural computation. Springer, Berlin, Heidelberg, 2012.
32
33
	References URL:
34
		Implementation is based on the following MATLAB code: https://www.mathworks.com/matlabcentral/fileexchange/45112-flower-pollination-algorithm?requestedDomain=true
35
36
	Attributes:
37
		Name (List[str]): List of strings representing algorithm names.
38
		p (float): probability switch.
39
		beta (float): Shape of the gamma distribution (should be greater than zero).
40
41
	See Also:
42
		* :class:`NiaPy.algorithms.Algorithm`
43
	"""
44
	Name = ['FlowerPollinationAlgorithm', 'FPA']
45
46
	@staticmethod
47
	def algorithmInfo():
48
		r"""Get default information of algorithm.
49
50
		Returns:
51
			str: Basic information.
52
53
		See Also:
54
			* :func:`NiaPy.algorithms.Algorithm.algorithmInfo`
55
		"""
56
		return r"""Yang, Xin-She. "Flower pollination algorithm for global optimization. International conference on unconventional computing and natural computation. Springer, Berlin, Heidelberg, 2012."""
57
58 View Code Duplication
	@staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
59
	def typeParameters():
60
		r"""TODO.
61
62
		Returns:
63
			Dict[str, Callable]:
64
				* p (function): TODO
65
				* beta (function): TODO
66
67
		See Also:
68
			* :func:`NiaPy.algorithms.Algorithm.typeParameters`
69
		"""
70
		d = Algorithm.typeParameters()
71
		d.update({
72
			'p': lambda x: isinstance(x, float) and 0 <= x <= 1,
73
			'beta': lambda x: isinstance(x, (float, int)) and x > 0,
74
		})
75
		return d
76
77
	def setParameters(self, NP=25, p=0.35, beta=1.5, **ukwargs):
78
		r"""Set core parameters of FlowerPollinationAlgorithm algorithm.
79
80
		Arguments:
81
			NP (int): Population size.
82
			p (float): Probability switch.
83
			beta (float): Shape of the gamma distribution (should be greater than zero).
84
85
		See Also:
86
			* :func:`NiaPy.algorithms.Algorithm.setParameters`
87
		"""
88
		Algorithm.setParameters(self, NP=NP, **ukwargs)
89
		self.p, self.beta = p, beta
90
		self.S = zeros((NP, 10))
91
92 View Code Duplication
	def repair(self, x, task):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
93
		r"""Repair solution to search space.
94
95
		Args:
96
			x (numpy.ndarray): Solution to fix.
97
			task (Task): Optimization task.
98
99
		Returns:
100
			numpy.ndarray: fixed solution.
101
		"""
102
		ir = where(x > task.Upper)
103
		x[ir] = task.Lower[ir] + x[ir] % task.bRange[ir]
104
		ir = where(x < task.Lower)
105
		x[ir] = task.Lower[ir] + x[ir] % task.bRange[ir]
106
		return x
107
108
	def levy(self, D):
109
		r"""Levy function.
110
111
		Returns:
112
			float: Next Levy number.
113
		"""
114
		sigma = (Gamma(1 + self.beta) * sin(pi * self.beta / 2) / (Gamma((1 + self.beta) / 2) * self.beta * 2 ** ((self.beta - 1) / 2))) ** (1 / self.beta)
115
		return 0.01 * (self.normal(0, 1, D) * sigma / fabs(self.normal(0, 1, D)) ** (1 / self.beta))
116
117
	def initPopulation(self, task):
118
		pop, fpop, d = Algorithm.initPopulation(self, task)
119
		d.update({'S': zeros((self.NP, task.D))})
120
		return pop, fpop, d
121
122
	def runIteration(self, task, Sol, Sol_f, xb, fxb, S, **dparams):
123
		r"""Core function of FlowerPollinationAlgorithm algorithm.
124
125
		Args:
126
			task (Task): Optimization task.
127
			Sol (numpy.ndarray): Current population.
128
			Sol_f (numpy.ndarray): Current population fitness/function values.
129
			xb (numpy.ndarray): Global best solution.
130
			fxb (float): Global best solution function/fitness value.
131
			**dparams (Dict[str, Any]): Additional arguments.
132
133
		Returns:
134
			Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, float, Dict[str, Any]]:
135
				1. New population.
136
				2. New populations fitness/function values.
137
				3. New global best solution.
138
				4. New global best solution fitness/objective value.
139
				5. Additional arguments.
140
		"""
141
		for i in range(self.NP):
142
			if self.uniform(0, 1) > self.p: S[i] += self.levy(task.D) * (Sol[i] - xb)
143
			else:
144
				JK = self.Rand.permutation(self.NP)
145
				S[i] += self.uniform(0, 1) * (Sol[JK[0]] - Sol[JK[1]])
146
			S[i] = self.repair(S[i], task)
147
			f_i = task.eval(S[i])
148
			if f_i <= Sol_f[i]: Sol[i], Sol_f[i] = S[i], f_i
149
			if f_i <= fxb: xb, fxb = S[i].copy(), f_i
150
		return Sol, Sol_f, xb, fxb, {'S': S}
151
152
# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
153