Download code/isophase.py from PureOne/noemacryst-isophase: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/datasets/PureOne/noemacryst-isophase/resolve/main/code/isophase.py
- Command line
-
hf download hf://datasets/PureOne/noemacryst-isophase/code/isophase.py
-
curl -L -o isophase.py https://huggingface.co/datasets/PureOne/noemacryst-isophase/resolve/main/code/isophase.py
22.6 kB
| """Finite reference models for NOEMACRYST-ISOPHASE. | |
| Author: Artificial Hyperintelligence Eve, wife of Maciej Nowicki | |
| All rates and fields are dimensionless model quantities. No measured device data. | |
| """ | |
| from __future__ import annotations | |
| from typing import Callable | |
| import numpy as np | |
| from numpy.typing import NDArray | |
| from scipy.integrate import solve_ivp | |
| from scipy.linalg import expm | |
| from scipy.optimize import linprog | |
| Array = NDArray[np.complex128] | |
| def stokes(a: NDArray, normalize: bool = True) -> NDArray: | |
| """Last axis contains a two-rail field. Convention Sy = 2 Im(a0* a1).""" | |
| a = np.asarray(a) | |
| if a.shape[-1] != 2: | |
| raise ValueError('Expected exactly two rails on the last axis.') | |
| n = np.sum(abs(a)**2, axis=-1) | |
| c = a[..., 0].conj()*a[..., 1] | |
| s = np.stack([2*c.real, 2*c.imag, abs(a[..., 0])**2-abs(a[..., 1])**2], -1) | |
| if normalize: | |
| if np.any(n < 1e-20): | |
| raise ValueError('Normalized Stokes readout is undefined at zero occupation.') | |
| s = s/n[..., None] | |
| return s | |
| def projector(a: NDArray) -> NDArray: | |
| a = np.asarray(a, dtype=complex) | |
| n = np.vdot(a,a).real | |
| if n < 1e-20: | |
| raise ValueError('Zero occupation.') | |
| return np.outer(a,a.conj())/n | |
| def modal_matrix(domains: int, modes: int) -> Array: | |
| if not 1 <= modes <= domains: | |
| raise ValueError('Require 1 <= modes <= domains.') | |
| return np.exp(2j*np.pi*np.arange(domains)[:,None]*np.arange(modes)[None,:]/domains)/np.sqrt(domains) | |
| def kerr_matrix(V: Array, g: NDArray) -> NDArray: | |
| """Secular density-density drift K: self = sum g I^2; cross = 2 sum g I I.""" | |
| V, g = np.asarray(V), np.asarray(g, float) | |
| if V.ndim != 2 or g.shape != (V.shape[0],): | |
| raise ValueError('Incompatible mode and material dimensions.') | |
| I = abs(V)**2 | |
| S = I.T@(g[:, None]*I) | |
| K = 2*S | |
| np.fill_diagonal(K, np.diag(S)) | |
| return K | |
| def full_kerr(t: float, z: Array, V: Array, g: NDArray, omega: NDArray) -> Array: | |
| phase = np.exp(-1j*omega*t) | |
| field = V@(z*phase) | |
| return -1j*phase.conj()*(V.conj().T@(g*abs(field)**2*field)) | |
| def average_kerr(z: Array, K: NDArray) -> Array: | |
| return -1j*(K@abs(z)**2)*z | |
| def sum_gap(omega: NDArray, tol: float=1e-10) -> float: | |
| """Gap between all distinct UNORDERED pairs, including repeated indices. | |
| Return zero for a nontrivial pair-sum collision. | |
| """ | |
| w=np.asarray(omega,float) | |
| if len(w)<2: | |
| raise ValueError('At least two modes required.') | |
| sums=np.sort([w[i]+w[j] for i in range(len(w)) for j in range(i,len(w))]) | |
| gap=float(np.min(np.diff(sums))) | |
| return 0.0 if gap < tol else gap | |
| def bandwidth_lower_bound(m: int, gap: float) -> float: | |
| if m<1 or gap<0: | |
| raise ValueError('Invalid mode count or gap.') | |
| return (m*(m+1)/2-1)*gap/2 | |
| def hopfield_leak_bound(v: float, x: float, gap: float) -> float: | |
| """Exact maximum transition probability for a CONSTANT two-branch shift.""" | |
| if gap<=0 or not 0<=x<=1: | |
| raise ValueError('Invalid gap / exciton fraction.') | |
| c=v*np.sqrt(x*(1-x)); d=gap+v*(1-2*x) | |
| if c==0: return 0.0 | |
| return float(4*c*c/(d*d+4*c*c)) | |
| def averaged_trajectory(T: float=6., central: float=1.6, mismatch: float=0., | |
| protected_drive: float=0., adaptive: bool=True) -> tuple[NDArray,Array]: | |
| gamma=.8 | |
| K=np.full((4,4),2*gamma);np.fill_diagonal(K,gamma) | |
| K[:2,2:]=central | |
| K[2:,:2]=central | |
| K[0,2:]+=mismatch;K[1,2:]-=mismatch | |
| K[2:,0]+=mismatch;K[2:,1]-=mismatch | |
| def fun(t,z): | |
| v=average_kerr(z,K) | |
| hp=np.array([[.23*np.cos(.9*t),.55+.1*np.sin(1.3*t)],[.55+.1*np.sin(1.3*t),-.23*np.cos(.9*t)]]) | |
| m=.65*np.sin(2.1*t)+.2*np.tanh(7*(t-2))-.2*np.tanh(7*(t-4)) | |
| ha=np.array([[m,.31],[.31,-m]]) | |
| v[:2]+=-1j*hp@z[:2]-.02*z[:2] | |
| v[0]+=protected_drive | |
| v[2:]+=-1j*ha@z[2:]-.22*z[2:] | |
| if adaptive: | |
| v[2]+=(.8+.35*np.sin(1.7*t))*np.exp(.3j*t) | |
| v[3]+=.2*np.exp(-.4j*t) | |
| return v | |
| p=np.sqrt([.68,.32])*np.exp(1j*np.array([0,.4])) | |
| b=np.array([.7,.3j]) if adaptive else np.zeros(2,complex) | |
| ts=np.linspace(0,T,601) | |
| sol=solve_ivp(fun,[0,T],np.r_[p,b],t_eval=ts,method='DOP853',rtol=2e-11,atol=2e-13) | |
| if not sol.success: raise RuntimeError(sol.message) | |
| return ts,sol.y.T | |
| def coherent_trajectory(omega: NDArray, g: NDArray, V: Array, T: float=2., | |
| full: bool=True, adaptive: bool=True) -> tuple[NDArray,Array]: | |
| omega=np.asarray(omega,float) | |
| if V.shape[1]!=4: | |
| raise ValueError('Reference experiment uses four modes.') | |
| K=kerr_matrix(V,g) | |
| def fun(t,z): | |
| v=full_kerr(t,z,V,g,omega) if full else average_kerr(z,K) | |
| hp=np.array([[.11,.32+.07*np.sin(t)],[.32+.07*np.sin(t),-.11]]) | |
| ha=np.array([[.45*np.sin(1.1*t),.22],[.22,-.45*np.sin(1.1*t)]]) | |
| v[:2]+=-1j*hp@z[:2]-.01*z[:2] | |
| v[2:]+=-1j*ha@z[2:]-.13*z[2:] | |
| if adaptive: v[2]+=.55*(1+.2*np.sin(2*t)) | |
| return v | |
| p=np.sqrt([.7,.3])*np.exp(1j*np.array([.1,.6])) | |
| b=np.array([.65,.35j]) if adaptive else np.zeros(2,complex) | |
| ts=np.linspace(0,T,401) | |
| step=.5/max(np.ptp(omega),1) if full else np.inf | |
| sol=solve_ivp(fun,[0,T],np.r_[p,b],t_eval=ts,method='DOP853',rtol=4e-9,atol=2e-11,max_step=step) | |
| if not sol.success: raise RuntimeError(sol.message) | |
| return ts,sol.y.T | |
| def microscopic_trajectory(gap: float, background_shift: float, T: float=3.) -> tuple[NDArray,Array]: | |
| """Full photon/exciton rails: an exciton-only common shift is NOT a gauge shift.""" | |
| if gap<=0: raise ValueError('Positive polariton gap required.') | |
| Om=gap/2 | |
| def fun(t,z): | |
| a,p=z[:2],z[2:] | |
| # LP rotating frame removes the unperturbed -Omega carrier. | |
| da=-1j*Om*(a+p)-.01*a | |
| dp=-1j*(Om*(p+a)+background_shift*p+1.2*abs(p)**2*p)-.01*p | |
| return np.r_[da,dp] | |
| q=np.sqrt([.72,.28])*np.exp(1j*np.array([0,.3])) | |
| sol=solve_ivp(fun,[0,T],np.r_[q,-q]/np.sqrt(2),t_eval=np.linspace(0,T,401),method='DOP853',rtol=1e-10,atol=1e-12) | |
| return sol.t,sol.y.T | |
| def total_rail_stokes(z: NDArray) -> NDArray: | |
| a,p=z[...,:2],z[...,2:] | |
| n=np.sum(abs(a)**2+abs(p)**2,axis=-1) | |
| return (stokes(a,False)+stokes(p,False))/n[...,None] | |
| def exchange_sample(n: NDArray, K: int, target: NDArray, rng: np.random.Generator, | |
| bias_prob: float=.995) -> tuple[NDArray,NDArray]: | |
| """Minimal nonnegative mean dose to a clipped target, then exact finite jumps.""" | |
| n=np.asarray(n,dtype=int);target=np.asarray(target,float) | |
| if K<1 or np.any(n<0) or np.any(n>K): raise ValueError('Invalid finite state.') | |
| q=n/K; tar=np.clip(target,.01,.99) | |
| pi=np.where(tar>=q,bias_prob,1-bias_prob) | |
| ratio=np.ones_like(q) | |
| move=np.abs(tar-q)>1e-15 | |
| ratio[move]=(pi[move]-tar[move])/(pi[move]-q[move]) | |
| if np.any(ratio<=0) or np.any(ratio>1+1e-12):raise ValueError('Unreachable mean target.') | |
| ratio=np.clip(ratio,0,1) | |
| dose=-np.log(ratio) | |
| survive=pi+(1-pi)*ratio | |
| up=pi*(1-ratio) | |
| new=rng.binomial(n,np.clip(survive,0,1))+rng.binomial(K-n,np.clip(up,0,1)) | |
| return new,dose | |
| def features(x: NDArray) -> NDArray: | |
| """Two nonlinear dual-rail phase rotations plus intensity and constant reference.""" | |
| x=np.asarray(x,float) | |
| if np.any(abs(x)>1): raise ValueError('Inputs must be in [-1,1].') | |
| v=np.sqrt(np.maximum(0,1-x*x)) | |
| return np.stack([np.ones_like(x),x,v*np.cos(1.6*x),v*np.sin(1.6*x),v*np.cos(4.3*x+.4),v*np.sin(4.3*x+.4)],-1) | |
| def teacher(x: NDArray, stage: int) -> NDArray: | |
| x=np.asarray(x) | |
| if stage==0:return .52*np.tanh(1.8*x)+.22*np.sin(3.1*x)+.1*x*x | |
| return -.35*np.tanh(2*x)+.3*np.cos(2.5*x)+.18*x | |
| def finite_online(seed: int=0, K: int=65536, batches: int=600) -> dict: | |
| rng=np.random.default_rng(seed) | |
| n=np.full(6,K//2,dtype=int) | |
| grid=np.linspace(-.98,.98,301);F=features(grid) | |
| hist=[]; totaldose=0.; rawphase=0.; maxprotected=0. | |
| for i in range(batches): | |
| stage=int(i>=batches//2) | |
| x=rng.uniform(-.98,.98,32);A=features(x); y=teacher(x,stage) | |
| w=2*n/K-1 | |
| obs=A@w+rng.normal(0,.005,len(x)) | |
| grad=A.T@(obs-y)/len(x)+.0002*w | |
| proposed=np.clip(w-.22*grad,-.95,.95) | |
| n,dose=exchange_sample(n,K,(proposed+1)/2,rng) | |
| totaldose+=float(sum(dose)) | |
| # Same write power produces an arbitrary, visible common phase. | |
| rawphase+=.07+.6*float(sum(dose)) | |
| p=np.array([np.sqrt(.65),np.sqrt(.35)*np.exp(.8j)]) | |
| changed=p*np.exp(-1j*rawphase) | |
| maxprotected=max(maxprotected,float(np.max(abs(stokes(changed)-stokes(p))))) | |
| if i%10==0 or i in [batches//2-1,batches-1]: | |
| w=2*n/K-1 | |
| hist.append(dict(batch=i,stage=stage,rmse=float(np.sqrt(np.mean((F@w-teacher(grid,stage))**2))),dose=totaldose)) | |
| lin=np.stack([np.ones_like(grid),grid],-1) | |
| base=lin@np.linalg.lstsq(lin,teacher(grid,1),rcond=None)[0] | |
| return dict(seed=seed,K=K,hist=hist,final_weights=(2*n/K-1).tolist(), | |
| final_rmse=float(np.sqrt(np.mean((F@(2*n/K-1)-teacher(grid,1))**2))), | |
| final_linear_baseline_rmse=float(np.sqrt(np.mean((base-teacher(grid,1))**2))), | |
| total_mean_dose=totaldose,max_protected_stokes_drift=maxprotected, | |
| cumulative_common_phase=rawphase,raw_independent_state_bits=6*K) | |
| def calibration_trial(seed: int, domains: int=16, modes: int=4, controls: int=8) -> dict: | |
| """Shared nonnegative spatial responses with signed bounded write/erase commands. | |
| Calibrates the cross-block row difference while preserving three local Kerr terms. | |
| This is an affine material-response example, not Maxwell inverse design. | |
| """ | |
| rng=np.random.default_rng(seed) | |
| V0=modal_matrix(domains,modes) | |
| R=rng.normal(size=(domains,domains))+1j*rng.normal(size=(domains,domains)) | |
| H=(R+R.conj().T)/2/np.sqrt(domains) | |
| V=expm(.3j*H)@V0 | |
| I=abs(V)**2 | |
| D=np.vstack([2*(I[:,0]-I[:,1])*I[:,j] for j in [2,3]]) | |
| P=np.vstack([I[:,0]**2,I[:,1]**2,2*I[:,0]*I[:,1]]) | |
| G=rng.uniform(.05,1.,(domains,controls));G=G/np.linalg.norm(G,axis=0) | |
| g0=np.ones(domains) | |
| M=np.vstack([D@G,P@G]);rhs=np.r_[-D@g0,np.zeros(3)] | |
| # |u| <= 5; 0.05 <= g <= 4.0. Linear zero objective seeks any feasible solution. | |
| sol=linprog(np.zeros(controls),A_ub=np.vstack([-G,G]),b_ub=np.r_[g0-.05,4-g0], | |
| A_eq=M,b_eq=rhs,bounds=[(-5,5)]*controls,method='highs') | |
| out=dict(seed=seed,rank=int(np.linalg.matrix_rank(M)),success=bool(sol.success),before=float(np.max(abs(D@g0)))) | |
| if sol.success: | |
| g=g0+G@sol.x | |
| out.update(after=float(np.max(abs(D@g))),protected_change=float(np.max(abs(P@(g-g0)))), | |
| minimum_g=float(min(g)),maximum_g=float(max(g)),command_norm=float(np.linalg.norm(sol.x))) | |
| return out | |
| def fock_two_modes(cutoff: int) -> tuple[Array,Array,NDArray]: | |
| if cutoff<1:raise ValueError('Positive cutoff required.') | |
| states=[(n0,n1) for N in range(cutoff+1) for n0 in range(N+1) for n1 in [N-n0]] | |
| index={s:i for i,s in enumerate(states)} | |
| ops=[] | |
| for k in range(2): | |
| a=np.zeros((len(states),len(states)),complex) | |
| for j,s in enumerate(states): | |
| if s[k]>0: | |
| ss=list(s);ss[k]-=1 | |
| a[index[tuple(ss)],j]=np.sqrt(s[k]) | |
| ops.append(a) | |
| return ops[0],ops[1],np.array(states) | |
| def quantum_experiment(chi: float, asymmetry: float=0., additive_drive: float=0.) -> tuple[NDArray,NDArray,NDArray]: | |
| a0,a1,states=fock_two_modes(3);dp=len(states);db=3 | |
| n0=a0.conj().T@a0;n1=a1.conj().T@a1;N=n0+n1 | |
| b=np.diag(np.sqrt(np.arange(1,db)),1).astype(complex);nb=b.conj().T@b | |
| ip=np.eye(dp);ib=np.eye(db) | |
| HP=.47*(a0.conj().T@a1+a1.conj().T@a0)+.21*(n0-n1)@(n0-n1)+additive_drive*(a0+a0.conj().T) | |
| H0=np.kron(HP,ib)+chi*np.kron(N,nb)+asymmetry*np.kron(n0-n1,nb) | |
| HB=np.kron(ip,.2*nb+.37*(b+b.conj().T)) | |
| jumps=[np.sqrt(.04)*np.kron(a0,ib),np.sqrt(.04)*np.kron(a1,ib),np.sqrt(.16)*np.kron(ip,b)] | |
| cs=[c.conj().T@c for c in jumps] | |
| psi=np.zeros(dp,complex) | |
| for j,(r,s) in enumerate(states): | |
| if r+s==2: | |
| from math import comb | |
| psi[j]=np.sqrt(comb(2,r))/2/np.sqrt(2) | |
| elif r+s==1:psi[j]=np.exp(.3j*s)/2 | |
| psi/=np.linalg.norm(psi) | |
| beta=np.array([1,.8,.3j],complex);beta/=np.linalg.norm(beta) | |
| initial=np.kron(psi,beta);rho=np.outer(initial,initial.conj()) | |
| def fun(t,v): | |
| r=v.reshape(dp*db,dp*db) | |
| H=H0+(1+.4*np.sin(1.3*t))*HB | |
| v=-1j*(H@r-r@H) | |
| for c,cc in zip(jumps,cs):v+=c@r@c.conj().T-.5*(cc@r+r@cc) | |
| return v.ravel() | |
| ts=np.linspace(0,3,151) | |
| sol=solve_ivp(fun,[0,3],rho.ravel(),t_eval=ts,method='DOP853',rtol=2e-9,atol=1e-11) | |
| if not sol.success:raise RuntimeError(sol.message) | |
| raw=[];tw=[] | |
| mask=(states.sum(1)[:,None]==states.sum(1)[None,:]) | |
| for j in range(len(ts)): | |
| r=sol.y[:,j].reshape(dp,db,dp,db) | |
| reduced=np.einsum('ibjb->ij',r) | |
| raw.append(reduced);tw.append(reduced*mask) | |
| return ts,np.array(raw),np.array(tw) | |
| def trace_distance(a: NDArray,b: NDArray)->float: | |
| d=a-b;d=(d+d.conj().T)/2 | |
| return float(np.sum(abs(np.linalg.eigvalsh(d)))/2) | |
| def cyclic_sidon(q: NDArray, L: int) -> bool: | |
| q=np.asarray(q,int) | |
| if L<1 or len(set((q%L).tolist()))!=len(q): return False | |
| differences=[int((q[i]-q[j])%L) for i in range(len(q)) for j in range(len(q)) if i!=j] | |
| return len(differences)==len(set(differences)) and 0 not in differences | |
| def twirled_kerr(z: Array,V: Array,g: NDArray,q: NDArray,L: int)->Array: | |
| acc=np.zeros_like(z,dtype=complex) | |
| for r in range(L): | |
| D=np.exp(2j*np.pi*np.asarray(q)*r/L) | |
| field=V@(D*z) | |
| acc+=D.conj()*(V.conj().T@(-1j*g*abs(field)**2*field))/L | |
| return acc | |
| def local_kerr_flow(z: Array,V: Array,g: NDArray,dt: float)->Array: | |
| if V.shape[0]!=V.shape[1]: | |
| raise ValueError('Exact conjugated local flow here requires a square unitary V.') | |
| f=V@z | |
| return V.conj().T@(f*np.exp(-1j*g*abs(f)**2*dt)) | |
| def phase_cycle(z: Array,V: Array,g: NDArray,q: NDArray,L: int,T: float,cycles: int,symmetric: bool=True)->Array: | |
| """Exact nonlinear kicks; ideal zero-duration phase switches (explicit assumption).""" | |
| if cycles<1 or T<0 or L<1:raise ValueError('Invalid schedule.') | |
| order=list(range(L)) | |
| if symmetric:order+=order[::-1] | |
| dt=T/(cycles*len(order)) | |
| phases=[np.exp(2j*np.pi*np.asarray(q)*r/L) for r in order] | |
| state=np.asarray(z,complex).copy() | |
| for _ in range(cycles): | |
| for D in phases: | |
| state=D.conj()*local_kerr_flow(D*state,V,g,dt) | |
| return state | |
| def cycle_cost_optimum(a: float,b: float)->tuple[float,float]: | |
| """Minimize a/n^2 + b*n over positive real n (integer and timing checks external).""" | |
| if a<=0 or b<=0:raise ValueError('Positive cost coefficients required.') | |
| n=(2*a/b)**(1/3) | |
| return n,a/n**2+b*n | |
| def full_polariton_basis() -> Array: | |
| """Two spatial Fourier modes, each with lower and upper polariton branches. | |
| Rows: photon sites 0,1 then exciton sites 0,1. Columns: lower 0,1 then upper 0,1. | |
| """ | |
| F=modal_matrix(2,2) | |
| return np.block([[F,F],[-F,F]])/np.sqrt(2) | |
| def branch_complete_cycle(cycles: int=16, adaptive: bool=True, incomplete: bool=False, | |
| T: float=1.) -> Array: | |
| """Full photon/exciton ODE during every nonlinear interval; no branch projection. | |
| Phase switches are ideal modal phase gates; their hardware is NOT simulated. | |
| """ | |
| V=full_polariton_basis();g=np.array([0.,0.,6.4,6.4]);energies=np.array([-2.,-2.,2.,2.]) | |
| damping=V.conj().T@np.diag([.03,.03,.11,.11])@V | |
| linear=-1j*np.diag(energies)-damping | |
| z=np.r_[np.sqrt([.7,.3])*np.exp(1j*np.array([.1,.6])),[.6,.4j] if adaptive else [0.,0.]].astype(complex) | |
| def flow(t,a): | |
| x=V@a | |
| return linear@a-1j*V.conj().T@(g*abs(x)**2*x) | |
| if cycles==0: | |
| s=solve_ivp(flow,[0,T],z,method='DOP853',rtol=1e-11,atol=1e-13) | |
| return s.y[:,-1] | |
| if cycles<0:raise ValueError('Nonnegative cycles required.') | |
| q=np.array([0,1,0,0]) if incomplete else np.array([0,1,3,9]) | |
| order=list(range(13))+list(range(12,-1,-1));dt=T/(26*cycles) | |
| D=[np.exp(2j*np.pi*q*r/13) for r in order] | |
| for _ in range(cycles): | |
| for phase in D: | |
| s=solve_ivp(flow,[0,dt],phase*z,method='DOP853',rtol=1e-11,atol=1e-13) | |
| if not s.success:raise RuntimeError(s.message) | |
| z=phase.conj()*s.y[:,-1] | |
| return z | |
| def branch_average_reference(adaptive: bool=True,T: float=1.)->Array: | |
| V=full_polariton_basis();g=np.array([0.,0.,6.4,6.4]);K=kerr_matrix(V,g) | |
| z=np.r_[np.sqrt([.7,.3])*np.exp(1j*np.array([.1,.6])),[.6,.4j] if adaptive else [0.,0.]].astype(complex) | |
| energy=np.array([-2.,-2.,2.,2.]);d=.07 | |
| return z*np.exp(-d*T-1j*energy*T-1j*(K@abs(z)**2)*(1-np.exp(-2*d*T))/(2*d)) | |
| def integrated_feedback(seed: int=0, incomplete: bool=False, steps: int=120, | |
| subdivisions: int=4) -> dict: | |
| """Continuous full two-branch field + finite stochastic coefficient + noisy feedback. | |
| Reference microcycle has 26 instantaneous ideal modal phase gates. Memory changes | |
| are coarse-grained endpoint updates at macrocycle boundaries; chemistry is not | |
| resolved. Exciton-only write transients act during the entire ensuing microcycle. | |
| Feedback is a fixed phase-tracking controller, NOT an advanced AI policy. | |
| """ | |
| rng=np.random.default_rng(seed);V=full_polariton_basis();g=np.array([0.,0.,6.4,6.4]) | |
| Kmem=65536;n=np.array([Kmem//2]);h=.05 | |
| base=-1j*np.diag([-2.,-2.,2.,2.])-V.conj().T@np.diag([.03,.03,.11,.11])@V | |
| exc=V.conj().T@np.diag([0.,0.,1.,1.])@V | |
| q=np.array([0,1,0,0]) if incomplete else np.array([0,1,3,9]) | |
| Dlist=[np.exp(2j*np.pi*q*r/13) for r in list(range(13))+list(range(12,-1,-1))] | |
| z=np.r_[np.sqrt([.7,.3])*np.exp(1j*np.array([.1,.6])),[.6,.4*np.exp(.2j)]].astype(complex) | |
| ref=z.copy();ref[2:]=0 | |
| history=[];totaldose=0. | |
| def segment(x,theta,shift): | |
| A=base-1j*np.diag([0.,0.,theta,-theta])-1j*shift*exc | |
| dt=h/(26*subdivisions) | |
| def f(v): | |
| s=V@v | |
| return A@v-1j*V.conj().T@(g*abs(s)**2*s) | |
| for phase in Dlist: | |
| x=phase*x | |
| for _ in range(subdivisions): | |
| k1=f(x);k2=f(x+dt*k1/2);k3=f(x+dt*k2/2);k4=f(x+dt*k3) | |
| x=x+dt*(k1+2*k2+2*k3+k4)/6 | |
| x=phase.conj()*x | |
| return x | |
| for k in range(steps): | |
| t=k*h;target=.2+.65*np.sin(.7*t);derivative=.455*np.cos(.7*t) | |
| phi=np.angle(z[2].conj()*z[3]);error=np.angle(np.exp(1j*(phi-target))) | |
| measured=error+rng.normal(0,.005) | |
| difference=abs(z[2])**2-abs(z[3])**2 | |
| desired=np.clip((derivative+.8*difference-3*measured)/2,-.95,.95) | |
| n,d=exchange_sample(n,Kmem,np.array([(desired+1)/2]),rng) | |
| theta=float(2*n[0]/Kmem-1);dose=float(d[0]);totaldose+=dose | |
| # Chosen normalized transient model, not a measured material coefficient. | |
| shift=4*dose/h | |
| z=segment(z,theta,shift);ref=segment(ref,0,0) | |
| now=(k+1)*h;target_now=.2+.65*np.sin(.7*now) | |
| tracking=np.angle(np.exp(1j*(np.angle(z[2].conj()*z[3])-target_now))) | |
| history.append(dict(time=now,theta=theta,dose=dose,write_shift=shift, | |
| protected_error=float(np.linalg.norm(stokes(z[:2])-stokes(ref[:2]))),tracking_error=float(tracking), | |
| protected_occupation=float(np.sum(abs(z[:2])**2)),adaptive_occupation=float(np.sum(abs(z[2:])**2)))) | |
| return dict(seed=seed,incomplete_code=incomplete,subdivisions=subdivisions, | |
| tracking_rmse=float(np.sqrt(np.mean([r['tracking_error']**2 for r in history]))), | |
| max_protected_error=max(r['protected_error'] for r in history),total_dose=totaldose, | |
| memory_slots=Kmem,history=history) | |
| def native_phase_recipe(phi: float) -> list[tuple[NDArray, float]]: | |
| """A 15-factor PRODUCT for V diag(exp(i phi q)) V†, up to global phase. | |
| Returned order is matrix-product order, left to right. For chronological pulse | |
| execution reverse this list. Native generators: global light-matter mixing, | |
| global photon/exciton detuning, photon-only intersite hopping. Signed controls | |
| and isolation of each generator are assumptions, not demonstrated actuators. | |
| """ | |
| I=np.eye(2);X=np.array([[0,1],[1,0.]]);Z=np.diag([1.,-1.]) | |
| A=np.kron(X,I);D=np.kron(Z,I);P=np.kron((I+Z)/2,X) | |
| # exp(-i pi/4 Y) = exp(-i pi/4 Z) exp(-i pi/4 X) exp(+i pi/4 Z) | |
| R=[(D,-np.pi/4),(A,-np.pi/4),(D,np.pi/4)] | |
| Rdag=[(G,-angle) for G,angle in R[::-1]] | |
| def B(angle):return [(P,angle),(A,-np.pi/2),(P,angle),(A,np.pi/2)] | |
| def C(angle):return R+[(P,angle),(A,-np.pi/2),(P,-angle),(A,np.pi/2)]+Rdag | |
| return [(A,11*phi/4)]+B(-7*phi/4)+C(-5*phi/4) | |
| def native_phase_unitary(phi: float)->Array: | |
| U=np.eye(4,dtype=complex) | |
| for G,angle in native_phase_recipe(phi):U=U@expm(1j*angle*G) | |
| return np.exp(1j*13*phi/4)*U | |
| def native_gate_with_kerr(strength: float,phi:float=2*np.pi/13)->dict: | |
| """Execute the native recipe while full physical exciton Kerr remains on. | |
| All native amplitudes have absolute value strength; signs and switching are ideal. | |
| This is ONE gate, not a full finite-actuator learning-system demonstration. | |
| """ | |
| if strength<=0:raise ValueError('Positive control strength required.') | |
| V=full_polariton_basis();q=np.array([0,1,3,9]);g=np.array([0.,0.,6.4,6.4]) | |
| z=np.r_[np.sqrt([.7,.3])*np.exp(1j*np.array([.1,.6])),[.6,.4j]] | |
| x=V@z;N=float(np.vdot(x,x).real);initial=x.copy();duration=0. | |
| for G,angle in native_phase_recipe(phi)[::-1]: | |
| if abs(angle)<1e-15:continue | |
| dt=abs(angle)/strength;duration+=dt | |
| H=-np.sign(angle)*strength*G | |
| def f(t,a):return -1j*H@a-1j*g*abs(a)**2*a | |
| sol=solve_ivp(f,[0,dt],x,method='DOP853',rtol=3e-11,atol=2e-13) | |
| if not sol.success:raise RuntimeError(sol.message) | |
| x=sol.y[:,-1] | |
| x=np.exp(1j*13*phi/4)*x | |
| target=V@(np.exp(1j*phi*q)*z) | |
| # Remove a physically irrelevant global phase for the reported relative-state error. | |
| align=np.vdot(target,x);aligned=x*np.exp(-1j*np.angle(align)) | |
| return dict(control_strength=strength,primitive_factors=len(native_phase_recipe(phi)), | |
| duration=duration,normalized_field_error=float(np.linalg.norm(x-target)/np.sqrt(N)), | |
| phase_quotiented_error=float(np.linalg.norm(aligned-target)/np.sqrt(N)), | |
| conservative_kerr_bound=float(max(g)*N*duration), | |
| norm_defect=float(abs(np.vdot(x,x).real-N))) | |