"""AIONVITA finite host-relative learner language and functional certificates. No universal language invention or sentience is represented. Features are small ASTs; learning rules are ridge adaptation followed by prediction. The host constructor set is fixed, while admitted grammar productions and reconstruction guides may change. """ from __future__ import annotations from dataclasses import dataclass, asdict import hashlib, json import numpy as np BASE = ('one', 'x', 'z') SPECS = { 'one':('const',), 'x':('input',0), 'z':('input',1), 'lagx':('input',2), 'lagz':('input',3), 'x2':('mul','x','x'), 'z2':('mul','z','z'), 'xz':('mul','x','z'), 'absx':('abs','x'), 'absz':('abs','z'), 'signx':('sign','x'), 'signz':('sign','z'), 'sinx':('sin','x'), 'sinz':('sin','z'), 'x3':('mul','x2','x'), 'z3':('mul','z2','z'), 'x2z':('mul','x2','z'), 'xz2':('mul','x','z2'), 'absxz':('mul','absx','z'), 'xlagx':('mul','x','lagx'), 'zlagz':('mul','z','lagz'), 'alias_x2':('add','x2','zero'), 'zero':('zero',), 'scaled_x2':('scale','x2',2.0), } EXT = ('x2','xz','lagx','absx','z2','lagz','absz','signx','signz','sinx','sinz','x3','z3','x2z','xz2','absxz','xlagx','zlagz','alias_x2','scaled_x2') POS={n:i for i,n in enumerate(EXT)} def dependencies(name): s=SPECS[name] return tuple(a for a in s[1:] if isinstance(a,str) and a in SPECS) def reconstruct(fragments, roots): """Guide = ordered roots; topological dependency assembly ignores storage order.""" available={name:spec for name,spec in fragments} order=[]; visiting=set(); done=set() def walk(n): if n in done: return if n in visiting: raise ValueError('cyclic guide') if n not in available: raise ValueError('missing fragment '+n) if available[n] != SPECS[n]: raise TypeError('fragment type/body mismatch') visiting.add(n) for d in dependencies(n): walk(d) visiting.remove(n); done.add(n); order.append(n) for n in roots: walk(n) return tuple(order) def eval_features(x, names): cache={} def ev(n): if n in cache:return cache[n] s=SPECS[n];op=s[0] if op=='const':v=np.ones(len(x)) elif op=='zero':v=np.zeros(len(x)) elif op=='input':v=x[:,s[1]] elif op=='mul':v=ev(s[1])*ev(s[2]) elif op=='add':v=ev(s[1])+ev(s[2]) elif op=='abs':v=np.abs(ev(s[1])) elif op=='sign':v=np.sign(ev(s[1])) elif op=='sin':v=np.sin(np.pi*ev(s[1])) elif op=='scale':v=s[2]*ev(s[1]) else:raise TypeError(op) cache[n]=v;return v return np.stack([ev(n) for n in names],axis=1) def ridge_fit(f,y,lam=1e-4): return np.linalg.solve(f.T@f+lam*np.eye(f.shape[1]),f.T@y) def model_predict(train_x,train_y,query_x,extra,lam=1e-4): names=BASE+tuple(extra) f=eval_features(train_x,names); q=eval_features(query_x,names) return q@ridge_fit(f,train_y,lam) def semantic_rank(x,names,tol=1e-7): f=eval_features(x,names) z=np.linalg.norm(f,axis=0); z[z<1e-12]=1 return int(np.linalg.matrix_rank(f/z,tol=tol)) def novelty_margin(x,old,new): """Scale-invariant finite response independence; no cohomology claim.""" a=eval_features(x,old); b=eval_features(x,(new,))[:,0] norm=np.linalg.norm(b) if norm<1e-12:return 0.0 residual=b-a@np.linalg.lstsq(a,b,rcond=1e-10)[0] return float(np.linalg.norm(residual)/norm) def span_certificate(x,old_names,new_names,tol=1e-7): a=eval_features(x,old_names);b=eval_features(x,new_names) qa=np.linalg.svd(a,full_matrices=False) rank=np.count_nonzero(qa[1]>1e-8) u=qa[0][:,:rank] residual=u-b@np.linalg.lstsq(b,u,rcond=1e-10)[0] err=float(np.linalg.norm(residual,2)) if rank else 0.0 return {'holds':bool(err<=tol),'operator_error':err,'old_rank':int(rank),'scope':'finite declared anchor set'} def adaptive_dimension(train_x, extra, shifts, noise_tolerance=.02): """Functional rank of label-intervention -> future-prediction adaptation map. Interventions are orthonormal directions spanning learner-relevant label changes. Each response must be nonzero and jointly independent on EVERY shift. Singular values use RMS normalization. The minimum rank is reported, not hidden width. This deterministic finite-design statistic is not a confidence interval. """ names=BASE+tuple(extra); f=eval_features(train_x,names) u,s,_=np.linalg.svd(f,full_matrices=False) u=u[:,s>1e-8] if u.shape[1]==0:return {'persistent_rank':0,'ranks':[],'min_singular':0} w=np.linalg.solve(f.T@f+1e-4*np.eye(f.shape[1]), f.T@u) ranks=[];sing=[] for x in shifts: response=eval_features(x,names)@w*np.sqrt(len(train_x)/len(x)) sv=np.linalg.svd(response,compute_uv=False) ranks.append(int(np.count_nonzero(sv>noise_tolerance))) sing.append(float(sv[-1])) return {'persistent_rank':min(ranks),'ranks':ranks,'min_singular':min(sing),'intervention_count':u.shape[1], 'threshold':noise_tolerance} def obstruction_witness(): """Exact rational affine obstruction: values x² at x=-1,0,1 have nonzero Δ².""" x=np.array([[-1,0,0,0],[0,0,0,0],[1,0,0,0]],float) linear=eval_features(x,BASE); target=eval_features(x,('x2',))[:,0] annihilator=np.array([1,-2,1],dtype=int) return {'points':x.tolist(),'annihilator':annihilator.tolist(), 'base_annihilation':(annihilator@linear).tolist(), 'target_witness':float(annihilator@target), 'extended_rank':int(np.linalg.matrix_rank(np.c_[linear,target])), 'scope':'affine span restricted to these three inputs'} def lineage_digest(previous,guide,contracts): payload=json.dumps({'previous':previous,'guide':list(guide),'contracts':contracts},sort_keys=True) return hashlib.sha256(payload.encode()).hexdigest() def fixed_label_interventions(train_x,tol=1e-8): """One fixed ordered label-intervention dictionary shared by all programs. Sequential Gram-Schmidt over the declared host catalogue, without looking at a candidate program or targets. Label directions are named by their first independent host fragment. Directions/normalization stay fixed across all compared programs on this task; they do not depend on an architecture's SVD. """ f=eval_features(train_x,BASE+EXT);cols=[];names=[] for j,name in enumerate(BASE+EXT): v=f[:,j].copy() for q in cols:v-=q*(q@v) for q in cols:v-=q*(q@v) # reorthogonalization norm=np.linalg.norm(v) if norm>tol: cols.append(v/norm);names.append(name) return tuple(names),np.stack(cols,axis=1) def useful_common_dimension(train_x,train_y,extra,shifts,shift_targets,gamma=.02,delta=.01): """Common conditionally ablation-useful unit-label response proxy. Every chosen column names the SAME label intervention at every shift and across all compared programs on this task. Each passes a utility ablation: removing this component of the observed support labels worsens normalized noiseless audit risk at EACH shift. Greedy common σ_min checks enforce joint independence of the unit-label responses. Ablation utility is measured at coefficient-scaled endpoints in a different context, so this is an empirical proxy, NOT a formal AIONVITA dimension certificate or a lower bound for the manuscript theorem. This is finite-design, finite-horizon and oracle-audit scoped; it is NOT an uncertainty bound. Raw rank is separate. """ intervention_names,u=fixed_label_interventions(train_x) names=BASE+tuple(extra);f=eval_features(train_x,names) solve=np.linalg.solve(f.T@f+1e-4*np.eye(f.shape[1]),f.T) w=solve@train_y;response_weights=solve@u responses=[];baseline=[];variances=[] for x,y in zip(shifts,shift_targets): q=eval_features(x,names);responses.append(q@response_weights) baseline.append(mse_local(q@w,y));variances.append(float(np.var(y))+1e-12) eligible=[];margins={} for j,name in enumerate(intervention_names): ablated_y=train_y-u[:,j]*(u[:,j]@train_y) w0=solve@ablated_y;gains=[] for x,y,risk,var in zip(shifts,shift_targets,baseline,variances): gains.append((mse_local(eval_features(x,names)@w0,y)-risk)/var) margins[name]=min(gains) if min(gains)>delta:eligible.append(j) # Fixed order, not task-conditioned best-subset search. This proxy count may # fall below its finite optimum when choices conflict across shifts. chosen=[];smallest=[] for j in eligible: proposal=chosen+[j] svs=[np.linalg.svd(r[:,proposal]*np.sqrt(len(train_x)/len(r)),compute_uv=False)[-1] for r in responses] if min(svs)>=gamma: chosen=proposal;smallest=svs chosen_names=[intervention_names[j] for j in chosen] return {'common_useful_lower_bound':len(chosen),'useful_new_lower_bound':sum(n not in BASE for n in chosen_names), 'chosen_interventions':chosen_names,'all_intervention_names':list(intervention_names), 'minimum_shift_singular':min(smallest) if smallest else 0., 'utility_margins':margins,'gamma':gamma,'delta':delta, 'scope':'declared support-label interventions, two finite audit shifts; empirical proxy', 'statistic_scope':'common conditionally ablation-useful unit-label response directions; empirical proxy, not formal AIONVITA dimension certificate'} def mse_local(a,b):return float(np.mean((a-b)**2)) def invent_distinguishing_probe(left,right,existing,proposal_pool,tolerance=1e-8): """Finite exact evaluator refinement by operational disagreement. If two scalar feature programs alias on existing probes, search declared new input points and append a witness of maximal difference. Empty output means only indistinguishability on the finite proposal pool, not global equivalence. """ old=(eval_features(existing,(left,))-eval_features(existing,(right,)))[:,0] if np.max(np.abs(old),initial=0)>tolerance: return {'needed':False,'old_max_difference':float(np.max(np.abs(old)))} difference=(eval_features(proposal_pool,(left,))-eval_features(proposal_pool,(right,)))[:,0] j=int(np.argmax(np.abs(difference))) if abs(difference[j])<=tolerance:return {'needed':True,'found':False} return {'needed':True,'found':True,'point':proposal_pool[j].tolist(), 'difference':float(difference[j]),'tested_pool_size':len(proposal_pool)}