"""RRLS geometry operator runtime and guarded algebraic compiler (NumPy required). Programs are ordered JSON operation lists. Affine coefficients are composed as exact fractions; point evaluation is float64, not bitwise-equivalent arithmetic. Compiler identities are supplied mathematics. Learned parameters live separately. """ from __future__ import annotations from fractions import Fraction as Q from itertools import product import copy, json, math import numpy as np class DomainError(ValueError):pass def q(x):return Q(str(x)) if not isinstance(x,Q) else x def enc(x): v=q(x);return str(v.numerator) if v.denominator==1 else f'{v.numerator}/{v.denominator}' def num(x):return float(q(x)) def eye(d):return [[Q(int(i==j)) for j in range(d)] for i in range(d)] def matmul(a,b):return [[sum((x*y for x,y in zip(row,col)),Q(0)) for col in zip(*b)] for row in a] def matvec(a,v):return [sum((x*y for x,y in zip(row,v)),Q(0)) for row in a] def affine(a,b=None): return {'op':'affine','A':[[enc(x) for x in row] for row in a], 'b':[enc(x) for x in (b if b is not None else [0]*len(a))]} def unpack(op):return [[q(x) for x in row] for row in op['A']],[q(x) for x in op['b']] def compose(first,second): a,b=unpack(first);c,d=unpack(second) if len(c[0])!=len(a):raise ValueError('Incompatible affine dimensions') return affine(matmul(c,a),[x+y for x,y in zip(matvec(c,b),d)]) def is_identity(op): if op['op']!='affine':return False a,b=unpack(op);return a==eye(len(a)) and not any(b) def inverse_matrix(a): n=len(a) if not n or any(len(row)!=n for row in a):raise DomainError('A full inverse requires a square matrix') rows=[[q(x) for x in row]+e for row,e in zip(a,eye(n))] for col in range(n): pivot=next((i for i in range(col,n) if rows[i][col]),None) if pivot is None:raise DomainError('Singular map: information has been lost') rows[col],rows[pivot]=rows[pivot],rows[col];v=rows[col][col] rows[col]=[x/v for x in rows[col]] for i in range(n): if i!=col: v=rows[i][col];rows[i]=[x-v*y for x,y in zip(rows[i],rows[col])] return [r[n:] for r in rows] AFFINE_KINDS={'identity','affine','translate','scale','rotate','quarter_turn','reflect_axis', 'reflect_plane','central_inversion','shear','embed','select'} def lower(op,d): name=op['op'];a=eye(d);b=[Q(0)]*d if name not in AFFINE_KINDS:return None if name=='affine': a,b=unpack(op) if not a or any(len(row)!=d for row in a) or len(b)!=len(a):raise ValueError('Invalid affine shape') elif name=='translate': b=list(map(q,op['vector'])) if len(b)!=d:raise ValueError('Translation dimension differs') elif name=='scale': f=op['factors'];f=f if isinstance(f,list) else [f]*d if len(f)!=d:raise ValueError('Scale dimension differs') a=[[q(f[i])*x for x in row] for i,row in enumerate(a)] elif name in ('rotate','quarter_turn'): i,j=op.get('plane',[0,1]);_axes(d,i,j) if name=='quarter_turn': k=op.get('turns',1) if not isinstance(k,int):raise ValueError('Quarter-turn count must be an integer') k%=4;c,s=[(1,0),(0,1),(-1,0),(0,-1)][k] else:c,s=math.cos(num(op['angle'])),math.sin(num(op['angle'])) a[i][i]=a[j][j]=q(c);a[i][j]=-q(s);a[j][i]=q(s) elif name=='reflect_axis': i=op.get('axis',0);_axes(d,i);a[i][i]=-1 elif name=='central_inversion':a=[[-x for x in row] for row in a] elif name=='reflect_plane': n=list(map(q,op['normal']));ss=sum(x*x for x in n) if len(n)!=d or not ss:raise DomainError('Reflection normal must be nonzero and dimension-matched') a=[[x-2*n[i]*n[j]/ss for j,x in enumerate(row)] for i,row in enumerate(a)] b=[2*q(op.get('offset',0))*x/ss for x in n] elif name=='shear': i,j=op['target'],op['source'];_axes(d,i,j);a[i][j]=q(op['amount']) elif name=='embed': k=op['output_dim'] if not isinstance(k,int):raise ValueError('Embedding dimension must be an integer') if k=d for i in axes):raise ValueError('Invalid selected axes') a=[eye(d)[i] for i in axes];b=[Q(0)]*len(axes) if 'center' in op and name in ('rotate','quarter_turn','scale','central_inversion'): c=list(map(q,op['center'])) if len(c)!=d:raise ValueError('Center dimension mismatch') b=[x-y for x,y in zip(c,matvec(a,c))] return affine(a,b) def _axes(d,*axes): if len(set(axes))!=len(axes) or any(not isinstance(i,int) or not 0<=i=math.pi):raise DomainError('Bend requires 1+k*y>0 and |k*x|=math.pi):raise DomainError('Unbend lies on excluded center or branch cut') y[:,i]=a/k;y[:,j]=(r-1)/k elif name in ('sine_shear','polynomial_shear'): i,j=op['target'],op['source'];_axes(d,i,j) if name=='sine_shear': t=num(op.get('frequency',1))*x[:,j] delta=num(op.get('sin',0))*np.sin(t)+num(op.get('cos',0))*np.cos(t) else:delta=np.polynomial.polynomial.polyval(x[:,j],[num(c) for c in op['coefficients']]) y[:,i]+=delta elif name=='sphere_inversion': center=np.asarray([num(v) for v in op.get('center',[0]*d)]) r=num(op.get('radius',1)) if len(center)!=d or r<=0:raise ValueError('Inversion requires matching center and positive radius') v=x-center;s=np.sum(v*v,axis=1) if np.any(s==0):raise DomainError('Sphere inversion is undefined at its center') y=center+r*r*v/s[:,None] elif name=='reciprocal': axes=op.get('axes',list(range(d))) for i in axes:_axes(d,i) if len(set(axes))!=len(axes):raise ValueError('Duplicate reciprocal axis') if np.any(x[:,axes]==0):raise DomainError('Reciprocal is undefined at zero') y[:,axes]=1/x[:,axes] elif name=='fold': i=op.get('axis',0);_axes(d,i);y[:,i]=abs(y[:,i]) elif name=='projective': h=np.asarray([[num(z) for z in row] for row in op['H']]) if h.ndim!=2 or h.shape[1]!=d+1 or h.shape[0]<2:raise ValueError('Projective matrix dimension mismatch') v=np.column_stack((x,np.ones(len(x))))@h.T if np.any(v[:,-1]==0):raise DomainError('Projective denominator is zero') y=v[:,:-1]/v[:,-1,None] elif name=='feature_lift': powers=op['powers'] if any(len(p)!=d or any(int(v)!=v or v<0 for v in p) for p in powers):raise ValueError('Invalid monomial powers') y=np.column_stack((x,features(x,powers))) elif name=='polynomial_map': powers=op['powers'];c=np.asarray([[num(v) for v in row] for row in op['coefficients']]) if any(len(p)!=d or any(int(v)!=v or v<0 for v in p) for p in powers) or c.shape[1]!=len(powers):raise ValueError('Invalid polynomial map') y=features(x,powers)@c.T elif name=='guard': if op['kind']=='not_center': if np.any(np.all(x==np.asarray([num(v) for v in op['center']]),axis=1)):raise DomainError('Canceled inversion remains undefined at its center') elif op['kind']=='nonzero': if np.any(x[:,op['axes']]==0):raise DomainError('Canceled reciprocal remains undefined at zero') else:raise ValueError('Unknown guard') else:raise ValueError('Unknown operation '+name) if not np.all(np.isfinite(y)):raise DomainError('Numeric overflow or non-finite output') return y def run(program,points): x=point_array(points) for op in program:x=apply(op,x) if not np.all(np.isfinite(x)):raise DomainError('Numeric overflow or non-finite output') return x def output_dim(op,d): a=lower(op,d) if a is not None:return len(a['A']) if op['op']=='feature_lift':return d+len(op['powers']) if op['op']=='polynomial_map':return len(op['coefficients']) if op['op']=='projective':return len(op['H'])-1 if op['op']=='repeat': k=d for b in op['body']:k=output_dim(b,k) if k!=d and op['count']>1:raise ValueError('Repeated body must preserve dimension') return k if op['count'] else d return d def inverse_op(op,d): a=lower(op,d) if a is not None: mat,b=unpack(a);inv=inverse_matrix(mat);return affine(inv,[-v for v in matvec(inv,b)]) p=copy.deepcopy(op);name=p['op'] if name=='twist':p['rate']=enc(-q(p.get('rate',0)));p['angle']=enc(-q(p.get('angle',0))) elif name=='sine_shear':p['sin']=enc(-q(p.get('sin',0)));p['cos']=enc(-q(p.get('cos',0))) elif name=='polynomial_shear':p['coefficients']=[enc(-q(v)) for v in p['coefficients']] elif name in ('bend','unbend','taper','untaper'):p['op']={'bend':'unbend','unbend':'bend','taper':'untaper','untaper':'taper'}[name] elif name in ('sphere_inversion','reciprocal'):pass elif name=='projective':p['H']=[[enc(v) for v in row] for row in inverse_matrix(p['H'])] elif name=='repeat': if p['count']==0:return {'op':'identity'} p['body']=inverse_program(p['body'],d) else:raise DomainError(f'{name} has no registered global inverse; a branch or missing coordinates may be required') return p def inverse_program(program,input_dim): d=input_dim;items=[] for op in program:items.append((op,d));d=output_dim(op,d) return [inverse_op(op,dim) for op,dim in reversed(items)] def affine_power(op,count): if not isinstance(count,int) or count<0:raise ValueError('Invalid repeat count') a,b=unpack(op) if len(a)!=len(a[0]):raise ValueError('Repeated affine map must be square') result=affine(eye(len(a)));base=op while count: if count&1:result=compose(result,base) count//=2 if count:base=compose(base,base) return result def _key(op,exclude=()):return json.dumps({k:v for k,v in op.items() if k not in exclude},sort_keys=True) def compile_program(program,input_dim): out=[];trace=[];d=input_dim def record(rule):trace.append({'rule':rule,'provenance':'supplied algebraic identity; not inferred from samples'}) for original in program: op=copy.deepcopy(original);before=d if op['op']=='repeat': n=op['count'] if not isinstance(n,int) or n<0:raise ValueError('Invalid repeat count') if n==0:record('zero_repetitions');continue body=compile_program(op['body'],d) if body['output_dim']!=d and n>1:raise ValueError('Repeated body changes dimensions') if not body['program']:record('repeat_identity');continue single=body['program'][0] if len(body['program'])==1 else None if single and single['op']=='affine': op=single if n==1 else affine_power(single,n);record('affine_power_by_squaring') elif single and single['op'] in ('twist','sine_shear','polynomial_shear','fold'): op=copy.deepcopy(single) if op['op']=='polynomial_shear':op['coefficients']=[enc(n*q(v)) for v in op['coefficients']] elif op['op']=='twist': for k in ('rate','angle'):op[k]=enc(n*q(op.get(k,0))) elif op['op']=='sine_shear': for k in ('sin','cos'):op[k]=enc(n*q(op.get(k,0))) record('repeated_same_generator') else:op['body']=body['program'] linear=lower(op,d) if linear is not None:op=linear d=output_dim(op,d) if out and op['op']=='affine' and out[-1]['op']=='affine': op=compose(out.pop(),op);record('fuse_affine_chain') # A feature lift followed by a linear readout becomes one polynomial map. if out and out[-1]['op']=='feature_lift' and op['op']=='affine': lift=out.pop();din=lift['_input_dim'];a,b=unpack(op) powers=[[int(i==j) for i in range(din)] for j in range(din)]+lift['powers'] merged={} for j,p in enumerate(powers): key=tuple(p);merged.setdefault(key,[Q(0)]*len(a)) for i in range(len(a)):merged[key][i]+=a[i][j] key=(0,)*din;merged.setdefault(key,[Q(0)]*len(a)) for i,v in enumerate(b):merged[key][i]+=v merged={k:v for k,v in merged.items() if any(v)} if all(sum(k)<=1 for k in merged): aa=[[Q(0)]*din for _ in a];bb=[Q(0)]*len(a) for k,v in merged.items(): if sum(k)==0:bb=v else: j=k.index(1) for i,c in enumerate(v):aa[i][j]=c op=affine(aa,bb) else: ks=sorted(merged);op={'op':'polynomial_map','powers':[list(k) for k in ks], 'coefficients':[[enc(merged[k][i]) for k in ks] for i in range(len(a))]} record('eliminate_feature_lift_and_prune_unused_monomials') if op['op']=='feature_lift':op['_input_dim']=before if out: prev=out[-1];kind=op['op'] if kind=='sphere_inversion' and _key(prev)==_key(op): out.pop();op={'op':'guard','kind':'not_center','center':op.get('center',[0]*d)};record('involution_with_domain_guard') elif kind=='reciprocal' and _key(prev)==_key(op): out.pop();op={'op':'guard','kind':'nonzero','axes':op.get('axes',list(range(d)))};record('reciprocal_with_domain_guard') elif kind=='fold' and _key(prev)==_key(op):record('fold_idempotence');continue elif kind in ('twist','sine_shear','polynomial_shear') and prev['op']==kind: params={'twist':('rate','angle'),'sine_shear':('sin','cos'),'polynomial_shear':('coefficients',)}[kind] if _key(prev,params)==_key(op,params): out.pop() if kind=='polynomial_shear': a=prev['coefficients'];b=op['coefficients'];n=max(len(a),len(b)) op['coefficients']=[enc(q(a[i] if itolerance));basis=vt[:rank].T;z=(x-origin)@basis;recon=z@basis.T+origin return {'origin':origin.tolist(),'basis':basis.tolist(),'coordinates':z.tolist(),'rank':rank, 'ambient_dim':x.shape[1],'tolerance':tolerance,'max_reconstruction_error':float(np.max(abs(recon-x))), 'scope':'observed point cloud; held-out points must satisfy the same affine-hull constraint'} def affine_hull_project(model,points): x=point_array(points);o=np.asarray(model['origin']);b=np.asarray(model['basis']);z=(x-o)@b if np.max(abs(z@b.T+o-x))>model['tolerance']:raise DomainError('Point lies outside the learned affine hull; reduction would lose information') return z def project_with_fiber(points,matrix): x=point_array(points);p=np.asarray(matrix,float);u,s,vt=np.linalg.svd(p,full_matrices=True) tol=max(p.shape)*np.finfo(float).eps*(s[0] if len(s) else 0);rank=int(np.sum(s>tol)) kernel=vt[rank:].T;y=x@p.T;hidden=x@kernel recon=y@np.linalg.pinv(p).T+hidden@kernel.T return {'visible':y,'hidden':hidden,'kernel':kernel,'reconstructed':recon,'rank':rank, 'missing_dimensions':p.shape[1]-rank} def cartesian_product(a,b): a=point_array(a);b=point_array(b) return np.column_stack((np.repeat(a,len(b),axis=0),np.tile(b,(len(a),1)))) def minkowski_points(a,b): a=point_array(a);b=point_array(b) if a.shape[1]!=b.shape[1]:raise ValueError('Minkowski operands must have the same ambient dimension') return (a[:,None,:]+b[None,:,:]).reshape(-1,a.shape[1]) def minkowski_support(a,b,direction): u=np.asarray(direction);return float(np.max(point_array(a)@u)+np.max(point_array(b)@u)) def tensor_apply(a,b,grid): """Apply (A tensor B) to row-major vec(grid) without building the Kronecker matrix.""" return np.asarray(a)@np.asarray(grid)@np.asarray(b).T def face_count_product(a,b): c=[Q(0)]*(len(a)+len(b)-1) for i,x in enumerate(a): for j,y in enumerate(b):c[i+j]+=q(x)*q(y) return [enc(x) for x in c] def reflection_decomposition(matrix,tolerance=1e-10): """Construct <=d Householder reflections for an orthogonal map, numerically. Known Cartan–Dieudonne construction, not a learned empirical conjecture. Returned operations act in execution order, which reverses the reduction. """ target=np.asarray(matrix,float);d=len(target) if target.shape!=(d,d) or np.max(abs(target.T@target-np.eye(d)))>tolerance: raise ValueError('An orthogonal matrix is required') a=target.copy();ops=[] for _ in range(d): delta=a-np.eye(d) if np.max(abs(delta))<=tolerance:break j=int(np.argmax(np.sum(delta*delta,axis=0)));v=delta[:,j];ss=v@v h=np.eye(d)-2*np.outer(v,v)/ss;a=h@a ops.append({'op':'reflect_plane','normal':v.tolist()}) if np.max(abs(a-np.eye(d)))>10*tolerance:raise ValueError('Numerical reflection reduction failed') return list(reversed(ops)) class Instances: """Copies share one base point array. Multiplicity and ordering are preserved.""" def __init__(self,base,programs): self.base=point_array(base);self.programs=[compile_program(p,self.base.shape[1])['program'] for p in programs] def materialize(self):return [run(p,self.base) for p in self.programs] def support(self,direction):return max(float(np.max(run(p,self.base)@np.asarray(direction))) for p in self.programs) def simplify_set(node): n=copy.deepcopy(node);op=n['op'] if op=='complement': a=simplify_set(n['child']) return a['child'] if a['op']=='complement' else {'op':op,'child':a} if op not in ('union','intersection','difference'):return n a=simplify_set(n['left']);b=simplify_set(n['right']) if a==b:return {'op':'empty'} if op=='difference' else a if op=='union': if a['op']=='empty':return b if b['op']=='empty':return a if op=='intersection' and (a['op']=='empty' or b['op']=='empty'):return {'op':'empty'} if op=='difference' and (a['op']=='empty' or b['op']=='empty'):return a return {'op':op,'left':a,'right':b} def contains(node,points): x=point_array(points);op=node['op'] if op=='empty':return np.zeros(len(x),dtype=bool) if op=='box':return np.all((x>=node['min'])&(x<=node['max']),axis=1) if op=='ball':return np.sum((x-node['center'])**2,axis=1)<=node['radius']**2 if op=='halfspace':return x@np.asarray(node['normal'])<=node['offset'] if op=='complement':return ~contains(node['child'],x) if op=='cartesian': k=node['left_dim'];return contains(node['left'],x[:,:k])&contains(node['right'],x[:,k:]) a=contains(node['left'],x);b=contains(node['right'],x) if op=='union':return a|b if op=='intersection':return a&b if op=='difference':return a&~b raise ValueError('Unknown set operation')