Passed
Push — master ( 99abb6...4fb8fc )
by Simon
05:03 queued 14s
created

ObjectiveFunction.run_callbacks()   A

Complexity

Conditions 3

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import numpy as np
7
from .dictionary import DictClass
8
9
10
def gfo2hyper(search_space, para):
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
    def __init__(self, objective_function, optimizer, callbacks, catch, nth_process):
21
        super().__init__()
22
23
        self.objective_function = objective_function
24
        self.optimizer = optimizer
25
        self.callbacks = callbacks
26
        self.catch = catch
27
        self.nth_process = nth_process
28
29
        self.nth_iter = 0
30
31
    def run_callbacks(self, type_):
32
        if self.callbacks and type_ in self.callbacks:
33
            [callback(self) for callback in self.callbacks[type_]]
34
35
    def __call__(self, search_space):
36
        # wrapper for GFOs
37
        def _model(para):
38
            self.nth_iter = len(self.optimizer.pos_l)
39
            para = gfo2hyper(search_space, para)
40
            self.para_dict = para
41
42
            try:
43
                self.run_callbacks("before")
44
                results = self.objective_function(self)
45
                self.run_callbacks("after")
46
            except tuple(self.catch.keys()) as e:
47
                results = self.catch[e.__class__]
48
49
            return results
50
51
        _model.__name__ = self.objective_function.__name__
52
        return _model
53