Passed
Pull Request — master (#101)
by Simon
01:22
created

test_function.AckleyFunction.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import numpy as np
2
3
from hyperactive.base import BaseExperiment
4
5
6
class SphereFunction(BaseExperiment):
7
    """
8
    A class representing a Sphere function experiment.
9
10
    This class inherits from BaseExperiment and implements a simple
11
    Sphere function, which is a common test function for optimization
12
    algorithms. The function is defined as the sum of the squares of
13
    its input parameters plus a constant.
14
15
    Attributes:
16
        const (float): A constant added to the function's result.
17
        n_dim (int): The number of dimensions for the input parameters.
18
19
    Methods:
20
        _score(**params): Computes the Sphere function value for the
21
        given parameters.
22
    """
23
24
    def __init__(self, const, n_dim=2):
25
        super().__init__()
26
27
        self.const = const
28
        self.n_dim = n_dim
29
30
    def _score(self, **params):
31
        return np.sum(np.array(params) ** 2) + self.const
32
33
34
class AckleyFunction(BaseExperiment):
35
    """
36
    A class representing the Ackley function, used as a benchmark for optimization algorithms.
37
38
    Attributes:
39
        A (float): A constant used in the calculation of the Ackley function.
40
41
    Methods:
42
        _score(**params): Computes the Ackley function value for given parameters 'x0' and 'x1'.
43
44
    The Ackley function is a non-convex function used to test optimization algorithms.
45
    """
46
47
    def __init__(self, A):
48
        super().__init__()
49
        self.A = A
50
51 View Code Duplication
    def _score(self, **params):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
52
        x = params["x0"]
53
        y = params["x1"]
54
55
        loss1 = -self.A * np.exp(-0.2 * np.sqrt(0.5 * (x * x + y * y)))
56
        loss2 = -np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y)))
57
        loss3 = np.exp(1)
58
        loss4 = self.A
59
60
        return -(loss1 + loss2 + loss3 + loss4)
61