"""Numeric-only precomputation cache; no pickle or executable payload.""" import hashlib,json from pathlib import Path import numpy as np from .control import ActionLibrary from .rational import RationalDistanceSpectrum from yeorinx2.spectrum import DistanceSpectrum SPECTRUM_ARRAYS=('distance','pw','pd','pd2','pb','pdb','gram') def profile_key(width,height,fov,weights,protected,rho): info=dict(width=int(width),height=int(height),fov=float(fov),protected=[list(x) for x in protected],rho=float(rho),version='3.0.0',directions=24,magnitudes=[.0015,.003,.006,.012,.024,.04]) w=np.asarray(weights,float);w=w/w.sum() h=hashlib.sha256(json.dumps(info,sort_keys=True).encode()+np.ascontiguousarray(w).tobytes()).hexdigest() return h,info def save(lib,path): key,meta=profile_key(lib.width,lib.height,lib.fov,lib.weights,lib.protected,lib.rho) meta.update(key=key,fx=lib.fx,fy=lib.fy,spectrum_operator=lib.spectrum.operator_norm,spectrum_storage=lib.spectrum.storage_bytes) arrays={k:getattr(lib,k) for k in ['angles','z','energy','maximum','lipschitz','rational_moments','weights']} arrays.update({'s_'+k:getattr(lib.spectrum,k) for k in SPECTRUM_ARRAYS}) arrays.update({'r_'+k:getattr(lib.rational_spectrum,k) for k in ['d','prefix','prefix_d']}) arrays['metadata']=np.asarray(json.dumps(meta));np.savez_compressed(path,**arrays) def load(path,width,height,fov,weights,protected,rho): expected,_=profile_key(width,height,fov,weights,protected,rho) with np.load(path,allow_pickle=False) as z: meta=json.loads(str(z['metadata'])) if meta['key']!=expected:raise ValueError('cache geometry, weights or policy do not match') lib=ActionLibrary.__new__(ActionLibrary) for k in ['angles','z','energy','maximum','lipschitz','rational_moments','weights']: a=z[k].copy() if not np.all(np.isfinite(a)):raise ValueError('nonfinite cache payload') setattr(lib,k,a) lib.width,lib.height,lib.fov,lib.rho=width,height,fov,rho lib.protected=tuple(tuple(x) for x in protected);lib.fx,lib.fy=meta['fx'],meta['fy'];lib.basis=None;lib.native=None s=DistanceSpectrum.__new__(DistanceSpectrum) for k in SPECTRUM_ARRAYS:setattr(s,k,z['s_'+k].copy()) s.width,s.height,s.fx,s.fy=width,height,lib.fx,lib.fy;s.operator_norm=meta['spectrum_operator'];s.storage_bytes=meta['spectrum_storage'] lib.spectrum=s;r=RationalDistanceSpectrum.__new__(RationalDistanceSpectrum) for k in ['d','prefix','prefix_d']:setattr(r,k,z['r_'+k].copy()) r.f=lib.fx;lib.rational_spectrum=r return lib