gradient_free_optimizers._objective_functions._sphere_function   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 17
dl 0
loc 36
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A SphereFunction.objective_function() 0 9 2
A SphereFunction.search_space() 0 3 1
A SphereFunction.__init__() 0 3 1
1
import numpy as np
2
3
from ._base_function import BaseFunction
4
5
6
class SphereFunction(BaseFunction):
7
    """
8
    Implements the Sphere objective function for optimization tasks.
9
10
    Attributes:
11
        n_dim (int): Number of dimensions.
12
        A (float): Coefficient for the quadratic term.
13
14
    Methods:
15
        objective_function(para): Calculates the Sphere function value for a given parameter dictionary.
16
        search_space: Property that defines the search space for each dimension as a range from -8 to 8 with step 0.1.
17
    """
18
19
    def __init__(self, n_dim, A=1):
20
        self.n_dim = n_dim
21
        self.A = A
22
23
    def objective_function(self, para):
24
        loss = 0
25
        for dim in range(self.n_dim):
26
            dim_str = "x" + str(dim)
27
            x = para[dim_str]
28
29
            loss += self.A * x * x
30
31
        return loss
32
33
    @property
34
    def search_space(self):
35
        return {"x" + str(idx): np.arange(-8, 8, 0.1) for idx in range(self.n_dim)}
36