Datasets:
Formats:
json
Languages:
English
Size:
< 1K
Tags:
mathematics
nonlinear-systems
model-reduction
state-representation
exterior-algebra
exact-arithmetic
Download src/continuation.py from PureOne/AELYRAITH-III: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/datasets/PureOne/AELYRAITH-III/resolve/main/src/continuation.py
- Command line
-
hf download hf://datasets/PureOne/AELYRAITH-III/src/continuation.py
-
curl -L -o continuation.py https://huggingface.co/datasets/PureOne/AELYRAITH-III/resolve/main/src/continuation.py
13.2 kB
| """Exact conditional-memory certificates for finite positive branch models. | |
| The model is known. A compact state receives externally supplied branch labels; | |
| it does not, unless separately certified, predict their probabilities. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from itertools import combinations | |
| from typing import Sequence | |
| import numpy as np | |
| import sympy as sp | |
| from scipy.optimize import linprog | |
| def pairs(n: int) -> list[tuple[int, int]]: | |
| if n < 2: | |
| raise ValueError("Ambient dimension must be at least two.") | |
| return list(combinations(range(n), 2)) | |
| def wedge(a: sp.Matrix, b: sp.Matrix) -> sp.Matrix: | |
| a, b = sp.Matrix(a), sp.Matrix(b) | |
| if a.rows != 1 or b.shape != a.shape: | |
| raise ValueError("Wedge arguments must be equal-length rows.") | |
| return sp.Matrix([[a[i]*b[j] - a[j]*b[i] for i,j in pairs(a.cols)]]) | |
| def compound2(T: sp.Matrix) -> sp.Matrix: | |
| T = sp.Matrix(T) | |
| if T.rows != T.cols or T.rows < 2: | |
| raise ValueError("A square matrix of order at least two is required.") | |
| ij = pairs(T.rows) | |
| return sp.Matrix([[T[i,k]*T[j,l]-T[i,l]*T[j,k] | |
| for k,l in ij] for i,j in ij]) | |
| def row_basis(F: sp.Matrix) -> sp.Matrix: | |
| F = sp.Matrix(F) | |
| if F.rows == 0: | |
| return F | |
| inds = F.T.rref()[1] | |
| return F[list(inds), :] if inds else sp.zeros(0, F.cols) | |
| class Ratio: | |
| numerator: sp.Matrix | |
| denominator: sp.Matrix | |
| word: tuple[int, ...] | |
| class ExteriorCertificate: | |
| normalizer: sp.Matrix | |
| readouts: tuple[sp.Matrix, ...] | |
| seeds: tuple[Ratio, ...] | |
| branches: tuple[sp.Matrix, ...] | |
| ratios: list[Ratio] | |
| R: sp.Matrix | |
| transports: list[sp.Matrix] | |
| depth: int | |
| def signature_exact(self, x: sp.Matrix) -> sp.Matrix: | |
| x = sp.Matrix(x) | |
| self._validate_state(x) | |
| out = [] | |
| for r in self.ratios: | |
| den = (r.denominator*x)[0] | |
| if den <= 0: | |
| raise ValueError("A stored denominator is nonpositive.") | |
| out.append((r.numerator*x)[0]/den) | |
| return sp.Matrix(out) | |
| def _validate_state(self, x: sp.Matrix) -> None: | |
| if x.shape != (self.normalizer.cols, 1): | |
| raise ValueError("Incorrect state shape.") | |
| if (self.normalizer*x)[0] != 1 or any(v < 0 for v in x): | |
| raise ValueError("Expected an exactly normalized simplex state.") | |
| def fiber_matrix(self, z: Sequence) -> sp.Matrix: | |
| if len(z) != len(self.ratios): | |
| raise ValueError("Incorrect signature dimension.") | |
| rows = [r.numerator-sp.sympify(v)*r.denominator | |
| for r,v in zip(self.ratios,z)] | |
| return sp.Matrix.vstack(*rows) if rows else sp.zeros(0, self.normalizer.cols) | |
| def reconstruct_fiber_float(self, z: Sequence[float]) -> np.ndarray: | |
| """Find any simplex representative; numerical, not an exact certificate.""" | |
| L = self.fiber_matrix(z) | |
| eq = np.array(sp.Matrix.vstack(self.normalizer,L),dtype=float) | |
| rhs = np.zeros(eq.shape[0]); rhs[0] = 1.0 | |
| res = linprog(np.zeros(eq.shape[1]), A_eq=eq, b_eq=rhs, | |
| bounds=(0,None), method="highs") | |
| if not res.success or np.max(np.abs(eq@res.x-rhs))>1e-7: | |
| raise ValueError("No numerically certified feasible representative.") | |
| return res.x | |
| def update_float(self, z: Sequence[float], branch: int) -> np.ndarray: | |
| if branch < 0 or branch >= len(self.branches): | |
| raise ValueError("Unknown branch.") | |
| x = self.reconstruct_fiber_float(z) | |
| T = np.array(self.branches[branch], dtype=float) | |
| y = T@x | |
| if np.sum(y) <= 0: | |
| raise ValueError("Impossible branch.") | |
| y /= np.sum(y) | |
| return np.array([float(np.array(r.numerator,dtype=float).ravel()@y / | |
| (np.array(r.denominator,dtype=float).ravel()@y)) | |
| for r in self.ratios]) | |
| def verify(self) -> bool: | |
| """Check both directions: seed coverage, genuine orbit rows, closure. | |
| Instrument probability normalization is an additional model obligation; | |
| this checker permits a library containing outcomes of several actions. | |
| """ | |
| try: | |
| n = self.normalizer.cols | |
| if self.normalizer != sp.ones(1,n) or n < 2: | |
| return False | |
| if len(self.branches) != len(self.transports) or not self.branches: | |
| return False | |
| if self.R.shape != (len(self.ratios), n*(n-1)//2): | |
| return False | |
| if self.R.rank() != self.R.rows: | |
| return False | |
| if any(T.shape != (n,n) or any(v <= 0 for v in T) | |
| for T in self.branches): | |
| return False | |
| for seed in self.seeds: | |
| if (seed.numerator.shape != (1,n) or | |
| seed.denominator.shape != (1,n) or seed.word or | |
| any(v <= 0 for v in seed.denominator)): | |
| return False | |
| if sp.Matrix.vstack(self.R,wedge(seed.numerator, | |
| seed.denominator)).rank() != self.R.rows: | |
| return False | |
| for i,r in enumerate(self.ratios): | |
| if (r.numerator.shape != (1,n) or | |
| r.denominator.shape != (1,n) or | |
| any(v <= 0 for v in r.denominator) or | |
| wedge(r.numerator,r.denominator) != self.R[i,:]): | |
| return False | |
| if any(a < 0 or a >= len(self.branches) for a in r.word): | |
| return False | |
| genuine = False | |
| for seed in self.seeds: | |
| beta, alpha = seed.numerator, seed.denominator | |
| # Words are chronological; row products are reverse ordered. | |
| for a in reversed(r.word): | |
| beta, alpha = beta*self.branches[a], alpha*self.branches[a] | |
| if beta == r.numerator and alpha == r.denominator: | |
| genuine = True | |
| break | |
| if not genuine: | |
| return False | |
| for T,H in zip(self.branches,self.transports): | |
| if H.shape != (self.R.rows,self.R.rows): | |
| return False | |
| if self.R*compound2(T) != H*self.R: | |
| return False | |
| return True | |
| except (ValueError, TypeError, IndexError): | |
| return False | |
| def compile_exterior(branches: Sequence[sp.Matrix], | |
| readouts: Sequence[sp.Matrix]) -> ExteriorCertificate: | |
| """Wrapper for ordinary affine mandatory readouts.""" | |
| if not branches: | |
| raise ValueError("At least one branch is required.") | |
| n=sp.Matrix(branches[0]).rows | |
| seeds=[Ratio(sp.Matrix(f),sp.ones(1,n),()) for f in readouts] | |
| return compile_ratios(branches,seeds) | |
| def compile_ratios(branches: Sequence[sp.Matrix], | |
| seeds: Sequence[Ratio]) -> ExteriorCertificate: | |
| """Exact closure for linear-fractional mandatory readouts. | |
| All denominators must be strictly positive on the entire simplex. Branches | |
| are known strictly positive matrices. Instrument normalization is separate. | |
| """ | |
| if not branches: | |
| raise ValueError("At least one branch is required.") | |
| Ts = tuple(sp.Matrix(T) for T in branches) | |
| n = Ts[0].rows | |
| for T in Ts: | |
| if T.shape != (n,n) or any(x <= 0 for x in T): | |
| raise ValueError("Branches must be square and strictly positive.") | |
| fs = tuple(sp.Matrix(r.numerator) for r in seeds) | |
| for r in seeds: | |
| if r.word: | |
| raise ValueError("Initial readouts must have empty provenance words.") | |
| if r.numerator.shape != (1,n) or r.denominator.shape != (1,n): | |
| raise ValueError("Readout rows have wrong dimensions.") | |
| if any(x<=0 for x in r.denominator): | |
| raise ValueError("Denominator must be positive on the full simplex.") | |
| e = sp.ones(1,n) | |
| ratios: list[Ratio] = [] | |
| R = sp.zeros(0,n*(n-1)//2) | |
| def admit(beta,alpha,word): | |
| nonlocal R | |
| r=wedge(beta,alpha) | |
| if sp.Matrix.vstack(R,r).rank() > R.rows: | |
| R=sp.Matrix.vstack(R,r) | |
| ratios.append(Ratio(beta,alpha,word)) | |
| for r in seeds: | |
| admit(r.numerator,r.denominator,r.word) | |
| cursor=0 | |
| while cursor < len(ratios): | |
| r=ratios[cursor]; cursor+=1 | |
| for a,T in enumerate(Ts): | |
| admit(r.numerator*T,r.denominator*T,(a,)+r.word) | |
| Hs=[] | |
| for T in Ts: | |
| target=R*compound2(T) | |
| if R.rows: | |
| hrows=[R.T.gauss_jordan_solve(target[i,:].T)[0].T | |
| for i in range(R.rows)] | |
| H=sp.Matrix.vstack(*hrows) | |
| else: | |
| H=sp.zeros(0,0) | |
| Hs.append(H) | |
| cert=ExteriorCertificate(e,fs,tuple(seeds),Ts,ratios,R,Hs, | |
| max((len(r.word) for r in ratios),default=0)) | |
| if not cert.verify(): | |
| raise ArithmeticError("Internal closure verification failed.") | |
| return cert | |
| def snapshot_space(cert: ExteriorCertificate) -> sp.Matrix: | |
| """Least affine initial-information space for the conditional contract. | |
| Unlike affine_closure, these coordinates need not update from themselves. | |
| """ | |
| rows=[cert.normalizer] | |
| for r in cert.ratios: | |
| rows.extend([r.numerator,r.denominator]) | |
| return row_basis(sp.Matrix.vstack(*rows)) | |
| def factor_two_fixture(r: int): | |
| """r independent ratios, exactly 2r affine snapshot scalars, reset future.""" | |
| if r<1: raise ValueError("Positive rank required.") | |
| n=2*r+1; e=sp.ones(1,n); E=sp.eye(n) | |
| beta=[E[2*j,:]-E[n-1,:] for j in range(r)] | |
| alpha=[e+sp.Rational(1,4)*(E[2*j+1,:]-E[n-1,:]) for j in range(r)] | |
| seeds=[Ratio(b,a,()) for b,a in zip(beta,alpha)] | |
| return compile_ratios([sp.ones(n)/n],seeds) | |
| def affine_closure(branches: Sequence[sp.Matrix], initial: sp.Matrix) -> sp.Matrix: | |
| """Least fixed affine self-updating space, using reset-or-invariance.""" | |
| W=row_basis(initial) | |
| n=W.cols | |
| if sp.Matrix.vstack(W,sp.ones(1,n)).rank()!=W.rows: | |
| raise ValueError("Normalizer is missing.") | |
| while True: | |
| extra=[W*T for T in branches if (W*T).rank()>1] | |
| new=row_basis(sp.Matrix.vstack(W,*extra)) | |
| if new.rows==W.rows: | |
| return W | |
| W=new | |
| def hadamard_exact(n: int) -> sp.Matrix: | |
| if n<4 or n & (n-1): | |
| raise ValueError("Use a power of two n >= 4.") | |
| H=sp.Matrix([[1]]) | |
| while H.rows<n: | |
| H=sp.Matrix.vstack(sp.Matrix.hstack(H,H),sp.Matrix.hstack(H,-H)) | |
| return H | |
| class Family: | |
| n: int | |
| F: sp.Matrix | |
| LA: sp.Matrix | |
| LB: sp.Matrix | |
| A: sp.Matrix | |
| B: sp.Matrix | |
| delta: sp.Rational | |
| c: sp.Rational = sp.Rational(1,2) | |
| tau: sp.Rational = sp.Rational(1,4) | |
| gamma: sp.Rational = sp.Rational(1,8) | |
| kappa: sp.Rational = sp.Rational(1,8) | |
| def signature(self,x: sp.Matrix) -> sp.Matrix: | |
| z=self.F*sp.Matrix(x) | |
| if z[0]!=1: | |
| raise ValueError("Not normalized.") | |
| return sp.Matrix([z[1], z[2]/(1+self.tau*z[3])]) | |
| def compact_step(self, state: Sequence, label: int) -> sp.Matrix: | |
| if label==0: | |
| return sp.Matrix([self.gamma*state[1],self.kappa*state[1]]) | |
| if label==1: | |
| return sp.zeros(2,1) | |
| raise ValueError("Unknown label.") | |
| def separation_family(n: int, delta=0) -> Family: | |
| F=hadamard_exact(n) | |
| c,tau,g,k=map(sp.Rational,[sp.Rational(1,2),sp.Rational(1,4), | |
| sp.Rational(1,8),sp.Rational(1,8)]) | |
| delta=sp.Rational(delta) | |
| if not (0<=delta<sp.Rational(1,8)): | |
| raise ValueError("Require 0 <= delta < 1/8.") | |
| lam=sp.Rational(1,8*n) | |
| LA=sp.zeros(n); LB=sp.zeros(n) | |
| LA[0,0]=c; LA[0,3]=c*tau | |
| LA[1,2]=c*g; LA[2,2]=c*k | |
| LB[0,0]=1-c; LB[0,3]=-c*tau | |
| LB[1,3]=delta | |
| for j in range(3,n-1): LB[j,j+1]=lam | |
| A=F.T*LA*F/n; B=F.T*LB*F/n | |
| return Family(n,F,LA,LB,A,B,delta,c,tau,g,k) | |
| def normalize(T: sp.Matrix,x: sp.Matrix) -> sp.Matrix: | |
| y=T*x; p=sum(y) | |
| if p<=0: raise ValueError("Nonpositive branch mass.") | |
| return y/p | |
| def jacobian_rank(cert: ExteriorCertificate, x: sp.Matrix) -> int: | |
| z=cert.signature_exact(x) | |
| return cert.fiber_matrix(z).rank() | |
| def reconstruct_hidden_from_B_readouts(n: int, observations: Sequence, | |
| delta) -> sp.Matrix: | |
| """Recover initial coordinates z3..z(n-1) after the rank-one rewrite. | |
| observation[t] = mandatory f after t+1 consecutive B outcomes. | |
| Exact arithmetic; small delta/late observations can be ill-conditioned. | |
| """ | |
| delta=sp.sympify(delta) | |
| if delta<=0 or len(observations)!=n-3: | |
| raise ValueError("Need positive delta and n-3 successive B readouts.") | |
| d0=sp.Rational(1,2); d1=sp.Rational(1,8); lam=sp.Rational(1,8*n) | |
| P=sp.Integer(1); out=[] | |
| for t,y in enumerate(observations): | |
| a=sp.simplify(d0*y/(delta+d1*y)) | |
| out.append(sp.simplify(a*P/lam**t)) | |
| P=sp.simplify(P*(d0-d1*a)) | |
| return sp.Matrix(out) | |