Completed
Push — master ( 2b17b1...77ef8d )
by Simon
03:52
created

hyperactive.memory.memory_io.MemoryIO._read_dill()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import os
6
import glob
7
import dill
8
9
10
from .util import get_hash, get_model_id
11
from .paths import get_meta_path, get_model_path, get_date_path, get_datetime
12
13
14
class MemoryIO:
15
    def __init__(self, _space_, _main_args_, _cand_):
16
        self._space_ = _space_
17
        self._main_args_ = _main_args_
18
19
        self.feature_hash = get_hash(_main_args_.X)
20
        self.label_hash = get_hash(_main_args_.y)
21
22
        self.score_col_name = "_score_"
23
24
        model_id = get_model_id(_cand_.func_)
25
26
        self.datetime = get_datetime()
27
28
        self.meta_path = get_meta_path()
29
        self.model_path = self.meta_path + get_model_path(model_id)
30
        self.date_path = self.model_path + get_date_path(self.datetime)
31
32
        self.dataset_info_path = self.model_path + "dataset_info/"
33
34
        if not os.path.exists(self.date_path):
35
            os.makedirs(self.date_path, exist_ok=True)
36
37
        self.hash2obj = self._hash2obj()
38
39
    def _read_dill(self, value):
40
        paths = self._get_pkl_hash(value)
41
        for path in paths:
42
            with open(path, "rb") as fp:
43
                value = dill.load(fp)
44
                value = dill.loads(value)
45
                break
46
47
        return value
48
49
    def _get_pkl_hash(self, hash):
50
        paths = glob.glob(self.model_path + hash + "*.pkl")
51
52
        return paths
53
54
    def _hash2obj(self):
55
        hash2obj_dict = {}
56
        para_hash_list = self._get_para_hash_list()
57
58
        for para_hash in para_hash_list:
59
            obj = self._read_dill(para_hash)
60
            hash2obj_dict[para_hash] = obj
61
62
        return hash2obj_dict
63
64
    def _get_para_hash_list(self):
65
        para_hash_list = []
66
        for key in self._space_.search_space.keys():
67
            values = self._space_.search_space[key]
68
69
            for value in values:
70
                if (
71
                    not isinstance(value, int)
72
                    and not isinstance(value, float)
73
                    and not isinstance(value, str)
74
                ):
75
76
                    para_dill = dill.dumps(value)
77
                    para_hash = get_hash(para_dill)
78
                    para_hash_list.append(para_hash)
79
80
        return para_hash_list
81