Passed
Pull Request — master (#110)
by
unknown
12:02 queued 10:25
created

hyperactive.experiment.toy._ackley   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 105
Duplicated Lines 9.52 %

Importance

Changes 0
Metric Value
wmc 5
eloc 28
dl 10
loc 105
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A AckleyFunction._score() 10 10 1
A AckleyFunction._paramnames() 0 2 1
A AckleyFunction._get_score_params() 0 15 1
A AckleyFunction.get_test_params() 0 34 1
A AckleyFunction.__init__() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

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
12
    .. math::
13
        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
14
15
    where A is a constant.
16
    Parameters
17
    ----------
18
    A : float
19
        Amplitude constant used in the calculation of the Ackley function.
20
21
    Example
22
    -------
23
    >>> from hyperactive.experiment.toy import AckleyFunction
24
    >>> ackley = AckleyFunction(A=20)
25
    >>> params = {"x0": 1, "x1": 2}
26
    >>> score, add_info = ackley.score(params)
27
    Quick call without metadata return or dictionary:
28
    >>> score = ackley(x0=1, x1=2)
29
    """  # noqa: E501
30
31
    _tags = {
32
        "property:randomness": "deterministic",  # random or deterministic
33
        # if deterministic, two calls of score will result in the same value
34
        # random = two calls may result in different values; same as "stochastic"
35
    }
36
37
    def __init__(self, A):
38
        self.A = A
39
        super().__init__()
40
41
    def _paramnames(self):
42
        return ["x0", "x1"]
43
44 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...
45
        x = params["x0"]
46
        y = params["x1"]
47
48
        loss1 = -self.A * np.exp(-0.2 * np.sqrt(0.5 * (x * x + y * y)))
49
        loss2 = -np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y)))
50
        loss3 = np.exp(1)
51
        loss4 = self.A
52
53
        return -(loss1 + loss2 + loss3 + loss4), {}
54
55
    @classmethod
56
    def get_test_params(cls, parameter_set="default"):
57
        """Return testing parameter settings for the skbase object.
58
59
        ``get_test_params`` is a unified interface point to store
60
        parameter settings for testing purposes. This function is also
61
        used in ``create_test_instance`` and ``create_test_instances_and_names``
62
        to construct test instances.
63
64
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
65
66
        Each ``dict`` is a parameter configuration for testing,
67
        and can be used to construct an "interesting" test instance.
68
        A call to ``cls(**params)`` should
69
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
70
71
        The ``get_test_params`` need not return fixed lists of dictionaries,
72
        it can also return dynamic or stochastic parameter settings.
73
74
        Parameters
75
        ----------
76
        parameter_set : str, default="default"
77
            Name of the set of test parameters to return, for use in tests. If no
78
            special parameters are defined for a value, will return `"default"` set.
79
80
        Returns
81
        -------
82
        params : dict or list of dict, default = {}
83
            Parameters to create testing instances of the class
84
            Each dict are parameters to construct an "interesting" test instance, i.e.,
85
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
86
            `create_test_instance` uses the first (or only) dictionary in `params`
87
        """
88
        return [{"A": 0}, {"A": 20}, {"A": -42}]
89
90
    @classmethod
91
    def _get_score_params(self):
92
        """Return settings for the score function.
93
94
        Returns a list, the i-th element corresponds to self.get_test_params()[i].
95
        It should be a valid call for self.score.
96
97
        Returns
98
        -------
99
        list of dict
100
            The parameters to be used for scoring.
101
        """
102
        params0 = {"x0": 0, "x1": 0}
103
        params1 = {"x0": 1, "x1": 1}
104
        return [params0, params1]
105