Total Complexity | 3 |
Total Lines | 38 |
Duplicated Lines | 26.32 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | import numpy as np |
||
2 | |||
3 | from hyperactive.base import BaseExperiment |
||
4 | |||
5 | |||
6 | class AckleyFunction(BaseExperiment): |
||
7 | r"""Ackley function, common benchmark for optimization algorithms. |
||
8 | |||
9 | The Ackley function is a non-convex function used to test optimization algorithms. |
||
10 | It is defined as: |
||
11 | .. math:: |
||
12 | f(x, y) = -A \cdot \exp(-0.2 \sqrt{0.5 (x^2 + y^2)}) - \exp(0.5 (\cos(2 \pi x) + \cos(2 \pi y))) + \exp(1) + A |
||
13 | |||
14 | where A is a constant. |
||
15 | Parameters |
||
16 | ---------- |
||
17 | A : float |
||
18 | Amplitude constant used in the calculation of the Ackley function. |
||
19 | """ # noqa: E501 |
||
20 | |||
21 | def __init__(self, A): |
||
22 | self.A = A |
||
23 | super().__init__() |
||
24 | |||
25 | def _paramnames(self): |
||
26 | return ["x0", "x1"] |
||
27 | |||
28 | View Code Duplication | def _score(self, params): |
|
|
|||
29 | x = params["x0"] |
||
30 | y = params["x1"] |
||
31 | |||
32 | loss1 = -self.A * np.exp(-0.2 * np.sqrt(0.5 * (x * x + y * y))) |
||
33 | loss2 = -np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y))) |
||
34 | loss3 = np.exp(1) |
||
35 | loss4 = self.A |
||
36 | |||
37 | return -(loss1 + loss2 + loss3 + loss4), {} |
||
38 |