Passed
Push — master ( f2568f...5ba4e8 )
by Simon
02:19 queued 13s
created

gradient_free_optimizers.memory.Memory.__init__()   B

Complexity

Conditions 5

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 30
rs 8.9093
c 0
b 0
f 0
cc 5
nop 4
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import logging
7
import pandas as pd
8
9
from typing import Callable, Any, List
10
from multiprocessing.managers import DictProxy
11
12
13
class Memory:
14
    def __init__(self, warm_start: pd.DataFrame, conv: Any, memory: Any = None):
15
        self.memory_dict = {}
16
        self.memory_dict_new = {}
17
        self.conv = conv
18
19
        if isinstance(memory, DictProxy):
20
            self.memory_dict = memory
21
22
        if warm_start is None:
23
            return
24
25
        if not isinstance(warm_start, pd.DataFrame):
26
            logging.warning(
27
                "Memory warm start must be of type pandas.DataFrame"
28
            )
29
            logging.warning(
30
                "Optimization will continue without memory warm start"
31
            )
32
            return
33
34
        if warm_start.empty:
35
            logging.warning(
36
                "Memory warm start has no values in current search space"
37
            )
38
            logging.warning(
39
                "Optimization will continue without memory warm start"
40
            )
41
            return
42
43
        self.memory_dict.update(self.conv.dataframe2memory_dict(warm_start))
44
45
    def memory(
46
        self, objective_function: Callable[[List[float]], float]
47
    ) -> Callable[[List[float]], float]:
48
        def wrapper(para: List[float]) -> float:
49
            value = self.conv.para2value(para)
50
            position = self.conv.value2position(value)
51
            pos_tuple = tuple(position)
52
53
            if pos_tuple in self.memory_dict:
54
                return self.memory_dict[pos_tuple]
55
            else:
56
                score = objective_function(para)
57
                self.memory_dict[pos_tuple] = score
58
                self.memory_dict_new[pos_tuple] = score
59
                return score
60
61
        return wrapper
62