cache.py 1.38 KB
Newer Older
1
2
3
import sympy as sp
import json

4
5
6
7
8
9
10
try:
    from functools import lru_cache as memorycache
except ImportError:
    from backports.functools_lru_cache import lru_cache as memorycache

try:
    from joblib import Memory
11
12
    from appdirs import user_cache_dir
    diskcache = Memory(cachedir=user_cache_dir('pystencils'), verbose=False).cache
13
14
15
16
17
18
19
20
21
22
23
except ImportError:
    # fallback to in-memory caching if joblib is not available
    diskcache = memorycache(maxsize=64)


# joblibs Memory decorator does not play nicely with sphinx autodoc (decorated functions do not occur in autodoc)
# -> if this script is imported by sphinx we use functools instead
import sys
calledBySphinx = 'sphinx' in sys.modules
if calledBySphinx:
    diskcache = memorycache(maxsize=64)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45


# ------------------------ Helper classes to JSON serialize sympy objects ----------------------------------------------


class SympyJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, sp.Basic):
            return {"_type": "sp", "str": str(obj)}
        else:
            super(SympyJSONEncoder, self).default(obj)


class SympyJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, obj):
        if '_type' in obj:
            return sp.sympify(obj['str'])
        else:
            return obj