Total Complexity | 8 |
Total Lines | 53 |
Duplicated Lines | 0 % |
Changes | 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 |