File: datacaching.py

package info (click to toggle)
orange3 3.40.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,908 kB
  • sloc: python: 162,745; ansic: 622; makefile: 322; sh: 93; cpp: 77
file content (57 lines) | stat: -rw-r--r-- 1,701 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from collections import defaultdict
from operator import itemgetter

def getCached(data, funct, params=(), **kwparams):
    # pylint: disable=protected-access
    if data is None:
        return None
    if not hasattr(data, "__data_cache"):
        data.__data_cache = {}
    info = data.__data_cache
    if funct in info:
        return info[funct]
    if isinstance(funct, str):
        return None
    info[funct] = res = funct(*params, **kwparams)
    return res


def setCached(data, name, value):
    if data is None:
        return
    if not hasattr(data, "__data_cache"):
        data.__data_cache = {}
    data.__data_cache[name] = value

def delCached(data, name):
    info = data is not None and getattr(data, "__data_cache")
    if info and name in info:
        del info[name]


class DataHintsCache(object):
    def __init__(self, ):
        self._hints = defaultdict(lambda: defaultdict(list))
        pass

    def set_hint(self, data, key, value, weight=1.0):
        attrs = data.domain.variables + data.domain.metas
        for attr in attrs:
            self._hints[key][attr].append((value, weight/len(attrs)))

    def get_weighted_hints(self, data, key):
        attrs = data.domain.variables + data.domain.metas
        weighted_hints = defaultdict(float)
        for attr in attrs:
            for val, w in self._hints[key][attr]:
                weighted_hints[val] += w
        return sorted(weighted_hints.items(), key=itemgetter(1), reverse=True)

    def get_hint(self, data, key, default=None):
        hints = self.get_weighted_hints(data, key)
        if hints:
            return hints[0][0]
        else:
            return default

data_hints = DataHintsCache()