hyperactive.optimizers.objective_function   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 35
dl 0
loc 58
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A gfo2hyper() 0 8 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A ObjectiveFunction.__call__() 0 20 2
A ObjectiveFunction.run_callbacks() 0 4 3
A ObjectiveFunction.__init__() 0 10 1
1
"""objective_function module for Hyperactive optimization."""
2
3
# Email: [email protected]
4
# License: MIT License
5
6
from .dictionary import DictClass
7
8
9
def gfo2hyper(search_space, para):
10
    """Gfo2Hyper function."""
11
    values_dict = {}
12
    for _, key in enumerate(search_space.keys()):
13
        pos_ = int(para[key])
14
        values_dict[key] = search_space[key][pos_]
15
16
    return values_dict
17
18
19
class ObjectiveFunction(DictClass):
20
    """ObjectiveFunction class."""
21
22
    def __init__(self, objective_function, optimizer, callbacks, catch, nth_process):
23
        super().__init__()
24
25
        self.objective_function = objective_function
26
        self.optimizer = optimizer
27
        self.callbacks = callbacks
28
        self.catch = catch
29
        self.nth_process = nth_process
30
31
        self.nth_iter = 0
32
33
    def run_callbacks(self, type_):
34
        """Run Callbacks function."""
35
        if self.callbacks and type_ in self.callbacks:
36
            [callback(self) for callback in self.callbacks[type_]]
37
38
    def __call__(self, search_space):
39
        """Make object callable with search space."""
40
41
        # wrapper for GFOs
42
        def _model(para):
43
            self.nth_iter = len(self.optimizer.pos_l)
44
            para = gfo2hyper(search_space, para)
45
            self.para_dict = para
46
47
            try:
48
                self.run_callbacks("before")
49
                results = self.objective_function(self)
50
                self.run_callbacks("after")
51
            except tuple(self.catch.keys()) as e:
52
                results = self.catch[e.__class__]
53
54
            return results
55
56
        _model.__name__ = self.objective_function.__name__
57
        return _model
58