Passed
Pull Request — master (#110)
by
unknown
01:31
created

hyperactive.experiment.toy._sphere.Sphere._score()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
"""Sphere function, a common benchmark for optimization algorithms."""
2
# copyright: hyperactive developers, MIT License (see LICENSE file)
3
4
import numpy as np
5
6
from hyperactive.base import BaseExperiment
7
8
9
class Sphere(BaseExperiment):
10
    """Simple Sphere function, common benchmark for optimization algorithms.
11
12
    Sphere function parameterized by the formula:
13
14
    .. math::
15
        f(x_1, x_2, \ldots, x_n) = \sum_{i=1}^n x_i^2 + c
16
17
    where :math:`c` is a constant offset added to the sum of squares,
18
    and :math:`n` is the number of dimensions.
19
    Both :math:`c` (= `const`) and :math:`n` (= `n_dim`) can be set as parameters.
20
21
    The function arguments :math:`x_1`, :math:`x_2`, ..., :math:`x_n`
22
    are the input variables of the `score` method,
23
    and are set as `x0`, `x1`, ..., `x[n]` respectively.
24
25
    This function is a common test function for optimization algorithms.
26
27
    Parameters
28
    ----------
29
    const : float, optional, default=0
30
        A constant offset added to the sum of squares.
31
    n_dim : int, optional, default=2
32
        The number of dimensions for the Sphere function. The default is 2.
33
34
    Example
35
    -------
36
    >>> from hyperactive.experiment.toy import Sphere
37
    >>> sphere = Sphere(const=0, n_dim=3)
38
    >>> params = {"x0": 1, "x1": 2, "x2": 3}
39
    >>> score, add_info = sphere.score(params)
40
41
    Quick call without metadata return or dictionary:
42
    >>> score = sphere(x0=1, x1=2, x2=3)
43
44
    Different number of dimensions changes the parameter names:
45
    >>> sphere4D = Sphere(const=0, n_dim=4)
46
    >>> score4D = sphere4D(x0=1, x1=2, x2=3, x3=4)
47
    """
48
49
    _tags = {
50
        "property:randomness": "deterministic",  # random or deterministic
51
        # if deterministic, two calls of score will result in the same value
52
        # random = two calls may result in different values; same as "stochastic"
53
    }
54
55
    def __init__(self, const=0, n_dim=2):
56
        self.const = const
57
        self.n_dim = n_dim
58
59
        super().__init__()
60
61
    def _paramnames(self):
62
        return [f"x{i}" for i in range(self.n_dim)]
63
64
    def _score(self, params):
65
        params_vec = np.array([params[f"x{i}"] for i in range(self.n_dim)])
66
        return np.sum(params_vec ** 2) + self.const, {}
67
68
    @classmethod
69
    def get_test_params(cls, parameter_set="default"):
70
        """Return testing parameter settings for the skbase object.
71
72
        ``get_test_params`` is a unified interface point to store
73
        parameter settings for testing purposes. This function is also
74
        used in ``create_test_instance`` and ``create_test_instances_and_names``
75
        to construct test instances.
76
77
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
78
79
        Each ``dict`` is a parameter configuration for testing,
80
        and can be used to construct an "interesting" test instance.
81
        A call to ``cls(**params)`` should
82
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
83
84
        The ``get_test_params`` need not return fixed lists of dictionaries,
85
        it can also return dynamic or stochastic parameter settings.
86
87
        Parameters
88
        ----------
89
        parameter_set : str, default="default"
90
            Name of the set of test parameters to return, for use in tests. If no
91
            special parameters are defined for a value, will return `"default"` set.
92
93
        Returns
94
        -------
95
        params : dict or list of dict, default = {}
96
            Parameters to create testing instances of the class
97
            Each dict are parameters to construct an "interesting" test instance, i.e.,
98
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
99
            `create_test_instance` uses the first (or only) dictionary in `params`
100
        """
101
        params0 = {}
102
        params1 = {"n_dim": 3, "const": 1.0}
103
        return [params0, params1]
104
105
    @classmethod
106
    def _get_score_params(self):
107
        """Return settings for testing the score function. Used in tests only.
108
109
        Returns a list, the i-th element corresponds to self.get_test_params()[i].
110
        It should be a valid call for self.score.
111
112
        Returns
113
        -------
114
        list of dict
115
            The parameters to be used for scoring.
116
        """
117
        score_params0 = {"x0": 0, "x1": 0}
118
        score_params1 = {"x0": 1, "x1": 2, "x2": 3}
119
        return [score_params0, score_params1]
120