Passed
Push — master ( 4a40b1...18f8a0 )
by Simon
01:39
created

Sphere._evaluate()   A

Complexity

Conditions 1

Size

Total Lines 17
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 17
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
    r"""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
        "property:higher_or_lower_is_better": "lower",
54
        # values are "higher", "lower", "mixed"
55
        # whether higher or lower scores are better
56
    }
57
58
    def __init__(self, const=0, n_dim=2):
59
        self.const = const
60
        self.n_dim = n_dim
61
62
        super().__init__()
63
64
    def _paramnames(self):
65
        return [f"x{i}" for i in range(self.n_dim)]
66
67
    def _evaluate(self, params):
68
        """Evaluate the parameters.
69
70
        Parameters
71
        ----------
72
        params : dict with string keys
73
            Parameters to evaluate.
74
75
        Returns
76
        -------
77
        float
78
            The value of the parameters as per evaluation.
79
        dict
80
            Additional metadata about the search.
81
        """
82
        params_vec = np.array([params[f"x{i}"] for i in range(self.n_dim)])
83
        return np.sum(params_vec ** 2) + self.const, {}
84
85
    @classmethod
86
    def get_test_params(cls, parameter_set="default"):
87
        """Return testing parameter settings for the skbase object.
88
89
        ``get_test_params`` is a unified interface point to store
90
        parameter settings for testing purposes. This function is also
91
        used in ``create_test_instance`` and ``create_test_instances_and_names``
92
        to construct test instances.
93
94
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
95
96
        Each ``dict`` is a parameter configuration for testing,
97
        and can be used to construct an "interesting" test instance.
98
        A call to ``cls(**params)`` should
99
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
100
101
        The ``get_test_params`` need not return fixed lists of dictionaries,
102
        it can also return dynamic or stochastic parameter settings.
103
104
        Parameters
105
        ----------
106
        parameter_set : str, default="default"
107
            Name of the set of test parameters to return, for use in tests. If no
108
            special parameters are defined for a value, will return `"default"` set.
109
110
        Returns
111
        -------
112
        params : dict or list of dict, default = {}
113
            Parameters to create testing instances of the class
114
            Each dict are parameters to construct an "interesting" test instance, i.e.,
115
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
116
            `create_test_instance` uses the first (or only) dictionary in `params`
117
        """
118
        params0 = {}
119
        params1 = {"n_dim": 3, "const": 1.0}
120
        return [params0, params1]
121
122
    @classmethod
123
    def _get_score_params(self):
124
        """Return settings for testing score/evaluate functions. Used in tests only.
125
126
        Returns a list, the i-th element should be valid arguments for
127
        self.evaluate and self.score, of an instance constructed with
128
        self.get_test_params()[i].
129
130
        Returns
131
        -------
132
        list of dict
133
            The parameters to be used for scoring.
134
        """
135
        score_params0 = {"x0": 0, "x1": 0}
136
        score_params1 = {"x0": 1, "x1": 2, "x2": 3}
137
        return [score_params0, score_params1]
138