hyperactive.experiment.bench._sphere   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 140
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 140
rs 10
c 0
b 0
f 0
wmc 5

5 Methods

Rating   Name   Duplication   Size   Complexity  
A Sphere.get_test_params() 0 36 1
A Sphere.__init__() 0 5 1
A Sphere._paramnames() 0 2 1
A Sphere._evaluate() 0 17 1
A Sphere._get_score_params() 0 16 1
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
    """Sphere class."""
11
12
    r"""Simple Sphere function, common benchmark for optimization algorithms.
13
14
    Sphere function parameterized by the formula:
15
16
    .. math::
17
        f(x_1, x_2, \ldots, x_n) = \sum_{i=1}^n x_i^2 + c
18
19
    where :math:`c` is a constant offset added to the sum of squares,
20
    and :math:`n` is the number of dimensions.
21
    Both :math:`c` (= `const`) and :math:`n` (= `n_dim`) can be set as parameters.
22
23
    The function arguments :math:`x_1`, :math:`x_2`, ..., :math:`x_n`
24
    are the input variables of the `score` method,
25
    and are set as `x0`, `x1`, ..., `x[n]` respectively.
26
27
    This function is a common test function for optimization algorithms.
28
29
    Parameters
30
    ----------
31
    const : float, optional, default=0
32
        A constant offset added to the sum of squares.
33
    n_dim : int, optional, default=2
34
        The number of dimensions for the Sphere function. The default is 2.
35
36
    Example
37
    -------
38
    >>> from hyperactive.experiment.bench import Sphere
39
    >>> sphere = Sphere(const=0, n_dim=3)
40
    >>> params = {"x0": 1, "x1": 2, "x2": 3}
41
    >>> score, add_info = sphere.score(params)
42
43
    Quick call without metadata return or dictionary:
44
    >>> score = sphere(x0=1, x1=2, x2=3)
45
46
    Different number of dimensions changes the parameter names:
47
    >>> sphere4D = Sphere(const=0, n_dim=4)
48
    >>> score4D = sphere4D(x0=1, x1=2, x2=3, x3=4)
49
    """
50
51
    _tags = {
52
        "property:randomness": "deterministic",  # random or deterministic
53
        # if deterministic, two calls of score will result in the same value
54
        # random = two calls may result in different values; same as "stochastic"
55
        "property:higher_or_lower_is_better": "lower",
56
        # values are "higher", "lower", "mixed"
57
        # whether higher or lower scores are better
58
    }
59
60
    def __init__(self, const=0, n_dim=2):
61
        self.const = const
62
        self.n_dim = n_dim
63
64
        super().__init__()
65
66
    def _paramnames(self):
67
        return [f"x{i}" for i in range(self.n_dim)]
68
69
    def _evaluate(self, params):
70
        """Evaluate the parameters.
71
72
        Parameters
73
        ----------
74
        params : dict with string keys
75
            Parameters to evaluate.
76
77
        Returns
78
        -------
79
        float
80
            The value of the parameters as per evaluation.
81
        dict
82
            Additional metadata about the search.
83
        """
84
        params_vec = np.array([params[f"x{i}"] for i in range(self.n_dim)])
85
        return np.sum(params_vec**2) + self.const, {}
86
87
    @classmethod
88
    def get_test_params(cls, parameter_set="default"):
89
        """Return testing parameter settings for the skbase object.
90
91
        ``get_test_params`` is a unified interface point to store
92
        parameter settings for testing purposes. This function is also
93
        used in ``create_test_instance`` and ``create_test_instances_and_names``
94
        to construct test instances.
95
96
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
97
98
        Each ``dict`` is a parameter configuration for testing,
99
        and can be used to construct an "interesting" test instance.
100
        A call to ``cls(**params)`` should
101
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
102
103
        The ``get_test_params`` need not return fixed lists of dictionaries,
104
        it can also return dynamic or stochastic parameter settings.
105
106
        Parameters
107
        ----------
108
        parameter_set : str, default="default"
109
            Name of the set of test parameters to return, for use in tests. If no
110
            special parameters are defined for a value, will return `"default"` set.
111
112
        Returns
113
        -------
114
        params : dict or list of dict, default = {}
115
            Parameters to create testing instances of the class
116
            Each dict are parameters to construct an "interesting" test instance, i.e.,
117
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
118
            `create_test_instance` uses the first (or only) dictionary in `params`
119
        """
120
        params0 = {}
121
        params1 = {"n_dim": 3, "const": 1.0}
122
        return [params0, params1]
123
124
    @classmethod
125
    def _get_score_params(self):
126
        """Return settings for testing score/evaluate functions. Used in tests only.
127
128
        Returns a list, the i-th element should be valid arguments for
129
        self.evaluate and self.score, of an instance constructed with
130
        self.get_test_params()[i].
131
132
        Returns
133
        -------
134
        list of dict
135
            The parameters to be used for scoring.
136
        """
137
        score_params0 = {"x0": 0, "x1": 0}
138
        score_params1 = {"x0": 1, "x1": 2, "x2": 3}
139
        return [score_params0, score_params1]
140