"""Finite exact-moment robust action selection, with an inherited v2 candidate. Guarantees rank lower bounds in a declared loss; they do not guarantee higher realized average improvement than every comparator or than NVIDIA Reflex. """ from dataclasses import dataclass from pathlib import Path import json import numpy as np from yeorinx2.core import camera_basis, cone_field from yeorinx2.spectrum import DistanceSpectrum from .geometry import projective_cone from .rational import grid_monomials,field_moments,RationalDistanceSpectrum,certified_correlations,scalar_select @dataclass(frozen=True) class Choice: template: int # -1 = inherited v2 cone, -2 = native/identity alpha: float lower_bound: float shift: tuple target_angles: tuple norm_bound_px: float reason: str def validate_regions(centers,radii,slack): centers=np.asarray(centers,float);radii=np.asarray(radii,float) if centers.ndim!=2 or centers.shape[1]!=2 or radii.shape!=centers.shape or len(centers)==0: raise ValueError('regions must be nonempty arrays of shape N x 2') if not np.all(np.isfinite(centers)) or not np.all(np.isfinite(radii)) or np.any(radii<0) or not np.isfinite(slack) or slack<0: raise ValueError('invalid uncertainty regions') return centers,radii,float(slack) def best_ray(z,energy,amplitude_max,centers,radii,slack,pixel_cap, model_error_px=0.,path_cost=0.,include_zero=False,margin=1e-10): z=np.asarray(z,float);energy=np.asarray(energy,float);amplitude_max=np.asarray(amplitude_max,float) centers,radii,slack=validate_regions(centers,radii,slack) if z.ndim!=2 or z.shape[1]!=2 or energy.shape!=(len(z),) or amplitude_max.shape!=energy.shape: raise ValueError('invalid action summaries') if not np.all(np.isfinite(z)) or not np.all(np.isfinite(energy)) or not np.all(np.isfinite(amplitude_max)) or np.any(energy<0) or np.any(amplitude_max<0): raise ValueError('invalid finite action geometry') vals=np.asarray([pixel_cap,model_error_px,path_cost,margin]) if not np.all(np.isfinite(vals)) or np.any(vals<0):raise ValueError('invalid nonnegative caps/costs') a=np.min(centers@z.T-radii@abs(z).T,axis=0)-slack*np.linalg.norm(z,axis=1) if include_zero:a=np.minimum(a,0.) a-=model_error_px*np.sqrt(energy) cap=np.minimum(1.,pixel_cap/np.maximum(amplitude_max,1e-300)) alpha=np.clip(np.divide(a,energy,out=np.zeros_like(a),where=energy>1e-25),0,cap) bound=2*a*alpha-energy*alpha**2-path_cost j=int(np.argmax(bound)) if alpha[j]<=0 or bound[j]<=margin:return -1,0.,0.,bound return j,float(alpha[j]),float(bound[j]),bound class ActionLibrary: def __init__(self,width,height,fov,weights,protected=(),rho=.12, directions=24,magnitudes=(.0015,.003,.006,.012,.024,.04)): if directions<4:raise ValueError('at least four directions required') self.width,self.height,self.fov=width,height,float(fov) self.protected=tuple(tuple(x) for x in protected);self.rho=float(rho) self.basis,self.fx,self.fy=camera_basis(width,height,fov) weights=np.asarray(weights,float) if weights.shape!=(height,width) or not np.all(np.isfinite(weights)) or np.any(weights<0) or weights.sum()<=0: raise ValueError('invalid pixel weights') self.weights=weights/weights.sum() self.spectrum=DistanceSpectrum(width,height,fov,self.weights,protected) qs=[];zs=[];es=[];ms=[];ls=[];rms=[] mon,focal=grid_monomials(width,height,fov) self.rational_spectrum=RationalDistanceSpectrum(width,height,self.weights,protected,fov) for mag in magnitudes: if not np.isfinite(mag) or mag<=0:raise ValueError('invalid template magnitude') for phi in np.arange(directions)*2*np.pi/directions: q=mag*np.array([np.cos(phi),np.sin(phi)]) v,info=projective_cone(width,height,q,rho,protected,fov) if not info['feasible']:continue qs.append(q) zs.append(np.einsum('hwij,hwi,hw->j',self.basis,v,self.weights)) es.append(np.sum(self.weights*np.sum(v*v,axis=-1))) ms.append(np.linalg.norm(v,axis=-1).max());ls.append(info['target_lipschitz_bound']) rms.append(field_moments(v,self.weights,mon,focal)) self.angles=np.asarray(qs);self.z=np.asarray(zs);self.energy=np.asarray(es);self.maximum=np.asarray(ms);self.lipschitz=np.asarray(ls) self.rational_moments=np.asarray(rms) self.native=None if not len(self.angles):raise ValueError('no feasible templates') def choose(self,mu,centers,radii,slack,pixel_cap,model_error_px=0.,path_cost=0.,include_zero=False): mu=np.asarray(mu,float) if mu.shape!=(2,) or not np.all(np.isfinite(mu)):raise ValueError('invalid center') shift=np.array([self.fx*mu[0],-self.fy*mu[1]]) z0,e0=self.spectrum.moments(shift,self.rho) # Spectrum returns the exact sampled field max separately here; the # analytic shift norm is a safe upper bound (possibly conservative). max0=float(np.linalg.norm(shift)) z=np.vstack([z0,self.z]);e=np.r_[e0,self.energy];m=np.r_[max0,self.maximum] j,alpha,bound,_=best_ray(z,e,m,centers,radii,slack,pixel_cap,model_error_px,path_cost,include_zero) if j<0:return Choice(-2,0.,0.,tuple(shift),(0.,0.),0.,'abstain') if j==0:return Choice(-1,alpha,bound,tuple(shift),(0.,0.),alpha*max0,'conditional_inherited_cone') return Choice(j-1,alpha,bound,(0.,0.),tuple(self.angles[j-1]),alpha*self.maximum[j-1],'conditional_projective_cone') def choose_rational(self,mu,centers,radii,slack,pixel_cap,source_pitch_cap,path_cost=0.,include_zero=False): shift=np.array([self.fx*mu[0],-self.fy*mu[1]]) _,e0=self.spectrum.moments(shift,self.rho) moments=np.concatenate([self.rational_spectrum.moments(shift,self.rho)[None,:,:],self.rational_moments],axis=0) energy=np.r_[e0,self.energy];maximum=np.r_[np.linalg.norm(shift),self.maximum] if self.native is not None: j,out=self.native.select(moments,energy,maximum,centers,radii,slack,self.width,self.height,self.fov,source_pitch_cap,pixel_cap,path_cost,include_zero) alpha,bound,baseline,max_charge=map(float,out) else: a,charge=certified_correlations(moments,energy,self.width,self.height,centers,radii,slack,source_pitch_cap,self.fov,include_zero) j,alpha,bound,all_bounds=scalar_select(a,energy,maximum,pixel_cap,path_cost) baseline=max(0.,float(all_bounds[0]));max_charge=float(np.max(charge)) diagnostics={'inherited_bound':baseline,'max_region_charge_px':max_charge} if j<0:return Choice(-2,0.,0.,tuple(shift),(0.,0.),0.,'abstain_rational'),diagnostics if j==0:return Choice(-1,alpha,bound,tuple(shift),(0.,0.),float(alpha*maximum[0]),'conditional_inherited_rational'),diagnostics return Choice(j-1,alpha,bound,(0.,0.),tuple(self.angles[j-1]),float(alpha*maximum[j]),'conditional_projective_rational'),diagnostics def field(self,choice): if choice.template==-2:return np.zeros((self.height,self.width,2)) if choice.template==-1:return choice.alpha*cone_field(self.width,self.height,choice.shift,self.rho,self.protected) v,_=projective_cone(self.width,self.height,choice.target_angles,self.rho,self.protected,self.fov) return choice.alpha*v def export(self,path): np.savez_compressed(path,angles=self.angles,z=self.z,energy=self.energy,maximum=self.maximum,lipschitz=self.lipschitz,rational_moments=self.rational_moments)