"""Sequential, multi-metric, bounded paired evaluation. Uses established empirical-Bernstein and Hoeffding bounds with explicit union-bound spending across proposals, registered looks, metrics and bounds. Proposal/environment/distribution must remain fixed during its evaluation. No choice of statistical test can certify unmeasured qualities. """ from dataclasses import dataclass,asdict import json import math from pathlib import Path import numpy as np from .certificates import ConfidenceLedger @dataclass(frozen=True) class MetricSpec: name: str minimum: float = 0. maximum: float = 1. direction: int = 1 min_gain: float = 0. penalty: float = 0. def __post_init__(self): if not isinstance(self.name,str) or not self.name.strip():raise ValueError('metric name required') if not all(math.isfinite(x) for x in (self.minimum,self.maximum,self.min_gain,self.penalty)): raise ValueError('metric constants must be finite') if self.maximum<=self.minimum or self.penalty<0 or isinstance(self.direction,bool) or self.direction not in (-1,1): raise ValueError('invalid bounds, direction or penalty') @dataclass(frozen=True) class ParetoAuditResult: accepted: bool n_pairs: int look: int lower_gain_bounds: dict empirical_gains: dict radii: dict active_bounds: dict attempt_delta: float look_delta: float candidate_id: str status: str scope: str='registered metrics only; fresh IID pairs, fixed proposal and known bounds' def confidence_radius(n: int,variance: float,width: float,delta: float,method: str='hybrid') -> tuple[float,str]: """width is the known range width of signed paired DIFFERENCES. A pair of returns each in [a,b] gives difference width 2*(b-a), not (b-a). Hybrid allocates delta/2 to each candidate inequality. """ if isinstance(n,bool) or not isinstance(n,int) or n<2:raise ValueError('n>=2 required') if not all(math.isfinite(x) for x in (variance,width,delta)) or variance<0 or width<=0 or not 0=2') if method not in ('hybrid','hoeffding','bernstein'):raise ValueError('invalid confidence method') if not isinstance(candidate_id,str) or not candidate_id.strip():raise ValueError('fixed candidate ID required') self.candidate_id=candidate_id self.n=0;self.look_index=0 self.mean=np.zeros(len(self.metrics));self.m2=np.zeros(len(self.metrics)) self.result=None;self.attempt_delta=ledger.spend() if ledger_path is not None:ledger.save(ledger_path) @property def finished(self):return bool(self.result is not None and self.result.accepted) or self.look_index>=len(self.looks) def _look(self): j=self.look_index+1 alpha=self.attempt_delta*6/(math.pi**2*j*j) lower={};radii={};bounds={};empirical={} for k,spec in enumerate(self.metrics): radius,bound=confidence_radius(self.n,max(0.,float(self.m2[k]/(self.n-1))), 2*(spec.maximum-spec.minimum),alpha/len(self.metrics),self.method) lower[spec.name]=float(self.mean[k]-radius-spec.penalty) radii[spec.name]=radius;bounds[spec.name]=bound;empirical[spec.name]=float(self.mean[k]) accept=all(lower[s.name]>=s.min_gain for s in self.metrics) status='certified_registered_margins' if accept else ('inconclusive_budget_exhausted' if j==len(self.looks) else 'continue') self.result=ParetoAuditResult(bool(accept),self.n,j,lower,empirical,radii,bounds, self.attempt_delta,alpha,self.candidate_id,status) self.look_index+=1 def add(self,candidate,baseline,*,candidate_id: str) -> ParetoAuditResult | None: if candidate_id!=self.candidate_id:raise ValueError('proposal changed during evaluation') if self.finished:raise RuntimeError('audit already finished') c=np.asarray(candidate,dtype=np.float64);b=np.asarray(baseline,dtype=np.float64) if c.ndim==1 and len(self.metrics)==1:c=c[:,None] if b.ndim==1 and len(self.metrics)==1:b=b[:,None] if c.ndim!=2 or c.shape!=b.shape or c.shape[1]!=len(self.metrics) or len(c)<1: raise ValueError('paired outcomes [N,metrics] required') if not np.isfinite(c).all() or not np.isfinite(b).all():raise ValueError('nonfinite outcome') for k,s in enumerate(self.metrics): if (c[:,k]s.maximum).any() or (b[:,k]s.maximum).any(): raise ValueError('outcome outside declared bounds') diff=(c-b)*np.array([s.direction for s in self.metrics]) offset=0 # Aggregate chunks with parallel Welford, stopping at each registered look. while offsetobj.looks[-1] or isinstance(i,bool) or not isinstance(i,int) or not 0<=i<=len(obj.looks): raise ValueError('invalid persisted sample counts') if i!=sum(n>=v for v in obj.looks) or not math.isfinite(d) or not 0