#!/usr/bin/env python3 """Runs verify_explicit_waring.py (all parts, as 'python3 verify_explicit_waring.py' does) so that it can be resumed after an interruption: the values of the expensive deterministic functions listed in WRAP are stored on disk when they have been computed and are read back, instead of being recomputed, in a later run. The program itself is not changed; the checks are those of main(). The key of a stored value is formed from the function's name, its arguments (bound to the signature, with defaults applied; arrays by their bytes) and the four module flags A_PAIRS_ON, A_MULT_ON, A_CANCEL_ON and A_MCANCEL_ON, which part 14 switches off temporarily. None of these functions uses a random number generator. Usage: python3 run_cached.py [options of the program, e.g. --appendix]""" import sys, os, pickle, hashlib, time, inspect prog_dir, cache_dir = os.path.abspath(sys.argv[1]), os.path.abspath(sys.argv[2]) sys.path.insert(0, prog_dir) sys.argv = ['verify_explicit_waring.py'] + sys.argv[3:] import numpy as np import verify_explicit_waring as V WRAP = ['A_rec_table', 'A_rec_vw', 'A_rec_plain', 'A_rec_potential', 'A_table', 'A_bound_rig', 'A_exact', 'A_exactlog_gain', 'A_V_quadrature', 'A_Y4_bounds'] LOG = os.path.join(cache_dir, 'cache_log.txt') def _feed(h, x): if isinstance(x, np.ndarray): h.update(b'nd'); h.update(str(x.dtype).encode()); h.update(repr(x.shape).encode()); h.update(np.ascontiguousarray(x).tobytes()) elif isinstance(x, (list, tuple)): h.update(b'(' if isinstance(x, tuple) else b'[') for y in x: _feed(h, y) h.update(b')') elif isinstance(x, dict): h.update(b'{') for kk in sorted(x, key=repr): _feed(h, kk); _feed(h, x[kk]) h.update(b'}') else: h.update(type(x).__name__.encode()); h.update(b':'); h.update(repr(x).encode()) h.update(b',') def _wrap(name): f = getattr(V, name); sig = inspect.signature(f) def g(*args, **kwargs): b = sig.bind(*args, **kwargs); b.apply_defaults() h = hashlib.sha256(); _feed(h, name); _feed(h, list(b.arguments.items())); _feed(h, (V.A_PAIRS_ON, V.A_MULT_ON, V.A_CANCEL_ON, V.A_MCANCEL_ON)) path = os.path.join(cache_dir, f"{name}-{h.hexdigest()[:32]}.pkl") if os.path.exists(path): try: with open(path, 'rb') as fh: return pickle.load(fh) except Exception: pass t0 = time.time(); r = f(*args, **kwargs); dt = time.time() - t0 tmp = path + '.tmp' with open(tmp, 'wb') as fh: pickle.dump(r, fh, protocol=pickle.HIGHEST_PROTOCOL) os.replace(tmp, path) short = ", ".join(f"{a}={v!r}"[:40] for a, v in b.arguments.items() if not isinstance(v, (list, np.ndarray))) with open(LOG, 'a') as fh: fh.write(f"{time.strftime('%H:%M:%S')} {dt:10.1f} s {name}({short}) flags={V.A_PAIRS_ON},{V.A_MULT_ON},{V.A_CANCEL_ON},{V.A_MCANCEL_ON}\n") return r setattr(V, name, g) # A_theta_direct (bisection for theta_k) is called very often, with small arguments: its values are kept in one # dictionary, which is written to disk at most every two minutes and at the end TD_PATH = os.path.join(cache_dir, 'A_theta_direct.pkl'); _td = {}; _td_saved = [time.time(), 0] if os.path.exists(TD_PATH): try: with open(TD_PATH, 'rb') as fh: _td = pickle.load(fh) except Exception: _td = {} def _td_save(): tmp = TD_PATH + '.tmp' with open(tmp, 'wb') as fh: pickle.dump(_td, fh, protocol=pickle.HIGHEST_PROTOCOL) os.replace(tmp, TD_PATH); _td_saved[0] = time.time(); _td_saved[1] = len(_td) _td_f = V.A_theta_direct; _td_sig = inspect.signature(_td_f) def _td_g(*args, **kwargs): b = _td_sig.bind(*args, **kwargs); b.apply_defaults() h = hashlib.sha256(); _feed(h, 'A_theta_direct'); _feed(h, list(b.arguments.items())); _feed(h, (V.A_PAIRS_ON, V.A_MULT_ON, V.A_CANCEL_ON, V.A_MCANCEL_ON)) key = h.digest() if key in _td: return _td[key] r = _td_f(*args, **kwargs); _td[key] = r if time.time() - _td_saved[0] > 120: _td_save() return r V.A_theta_direct = _td_g for nm in WRAP: _wrap(nm) try: V.main() finally: if len(_td) > _td_saved[1]: _td_save()