File size: 10,307 Bytes
860030d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""UPMV: falsifiable, uncalibrated kinetic assembly model. Python 3.10+.
No molecular-dynamics, free-cluster geometry, or experimental claims are implied.
All six protocols use the SAME transient continuous-time Markov chain.
"""
from __future__ import annotations
import argparse, csv, json, math, platform
from pathlib import Path
from dataclasses import dataclass, asdict
import numpy as np
import scipy
from scipy.linalg import expm

ROOT=Path(__file__).resolve().parents[1]
MODES=('random','coded','hierarchical','proofreading','proofreading_hierarchy','locking')
@dataclass(frozen=True)
class Parameters:
    kon: float=1e6             # M^-1 s^-1, illustrative
    c_total: float=1e-7        # M primary component concentration
    koff_correct: float=0.01  # s^-1
    progress_rate: float=0.1  # s^-1, fuel-driven checking/capture
    gap_kbt: float=6.0        # total WRONG-CORRECT energy gap, not per base
    checks: int=2
    b: int=4
    hold_loss: float=1e-6     # s^-1, metastable retained-module loss
    fusion_error: float=1e-4 # per accepted join, illustrative
    fusion_delay: float=60.0 # s per level, counted inside total deadline
    dilution_exponent: float=1.0 # c(level)=c0*b^(-alpha*(level-1))
    deadline: float=20000.0  # s


def generator(lc,lw,dc,dw,mu,checks):
    """E <-> C_j/W_j; C_j/W_j -> next checkpoint -> AC/AW.
    Final capture = metastable retention. AC/AW absorbing during this local assay.
    Reverse checkpoint paths neglected: driven, NOT equilibrium proofreading.
    """
    ns=checks+1; ac=1+2*ns; aw=ac+1
    Q=np.zeros((aw+1,aw+1)); Q[0,1]=lc; Q[0,1+ns]=lw
    for start,dest,d in ((1,ac,dc),(1+ns,aw,dw)):
        for j in range(ns):
            Q[start+j,0]=d
            Q[start+j,(start+j+1 if j+1<ns else dest)]=mu
    Q[np.diag_indices_from(Q)]=-Q.sum(1)
    return Q,ac,aw


def local_stats(lc,lw,dc,dw,mu,checks,time):
    Q,ac,aw=generator(lc,lw,dc,dw,mu,checks)
    p=expm(Q*max(time,0))[0]
    # Floating point roundoff only; normalization checked in test_model.py.
    p=np.clip(p,0,1); p/=p.sum()
    aC=(mu/(mu+dc))**(checks+1); aW=(mu/(mu+dw))**(checks+1)
    wrong_inf=lw*aW/(lc*aC+lw*aW)
    transient=Q[:ac,:ac]
    mean=float(np.linalg.solve(-transient,np.ones(ac))[0])
    # Expected number of progress transitions before capture, including rejected trials.
    reward=np.zeros(ac); reward[1:]=mu
    fuel=float(np.linalg.solve(-transient,reward)[0])
    return float(p[ac]),float(p[aw]),wrong_inf,mean,fuel


def level_plan(N,mode,p):
    hier=mode in ('hierarchical','proofreading_hierarchy','locking')
    if not hier:
        return [(N-1,N,p.c_total,1)]
    L=round(math.log(N,p.b))
    if p.b**L!=N: raise ValueError('Hierarchical N must be an exact power of b')
    return [((p.b-1)*N//(p.b**l),p.b,p.c_total*p.b**(-p.dilution_exponent*(l-1)),l) for l in range(1,L+1)]


def evaluate(N,mode,p):
    levels=level_plan(N,mode,p)
    checks=p.checks if mode in ('proofreading','proofreading_hierarchy','locking') else 0
    gap=0.0 if mode=='random' else p.gap_kbt
    dc=p.koff_correct; dw=dc*math.exp(gap)
    lock=mode=='locking'; delay=p.fusion_delay if lock else 0.0
    usable=max(0,p.deadline-delay*len(levels))
    # Time allocation compensates dilution, with same total wall-clock deadline.
    weights=np.array([1/(p.kon*c/n) for _,n,c,_ in levels]); weights/=weights.sum()
    elapsed=0.; logperfect=0.; ec=0.; ew=0.; em=0.; total_mean=0.; work=0.; records=[]
    for (joins,n,c,l),w in zip(levels,weights):
        tau=float(usable*w); lc=p.kon*c/n; lw=p.kon*c*(n-1)/n
        pc,pw,pinf,mean,fuel=local_stats(lc,lw,dc,dw,p.progress_rate,checks,tau)
        elapsed+=tau+delay
        age=p.deadline-elapsed
        # No hidden repair of old internal joins at the next hierarchy level.
        survive=math.exp(-p.hold_loss*(delay if lock else max(age,0)))
        if lock:
            pw=(pw+pc*p.fusion_error)*survive
            pc=pc*(1-p.fusion_error)*survive
        else:
            pc*=survive; pw*=survive
        missing=max(0,1-pc-pw)
        ec+=joins*pc; ew+=joins*pw; em+=joins*missing
        logperfect+=joins*math.log(max(pc,1e-300))
        total_mean+=mean+delay; work+=joins*fuel
        records.append(dict(level=l,joins=joins,active_variants=n,c_M=c,
                            allotted_s=tau,correct=pc,wrong=pw,missing=missing,
                            mean_capture_s=mean,asymptotic_wrong=pinf))
    # Acquisition of all independent joins <= P(each correct); this model omits gate failures.
    # Its product is conditional on ideal provision of competent children, not a real-device forecast.
    log10=logperfect/math.log(10)
    observed=ew/(ec+ew) if ec+ew else 1.
    hier=len(levels)>1
    # Template instruction format defined in docs; not Kolmogorov complexity or physical work.
    control_bits=64+32*len(levels) if hier else 64+math.ceil(math.log2(max(N,2)))*(N-1)
    return dict(mode=mode,N=N,gap_kbt=p.gap_kbt,progress_rate=p.progress_rate,
                dilution_exponent=p.dilution_exponent,fusion_error=p.fusion_error,
                deadline_s=p.deadline,levels=len(levels),correct_fraction=ec/(N-1),
                wrong_fraction=ew/(N-1),missing_fraction=em/(N-1),
                wrong_among_captured=observed,log10_perfect_yield=log10,
                perfect_yield=math.exp(logperfect) if logperfect>-745 else 0.,
                sum_mean_local_capture_s=total_mean,
                expected_progress_events_complete=work,
                material_families=6,active_decorated_variants=max(r['active_variants'] for r in records),
                recognition_symbols=4,code_slots=16,template_control_bits=control_bits,
                detail=records)


def gillespie(lc,lw,dc,dw,mu,checks,tmax,reps,seed):
    rng=np.random.default_rng(seed); Q,ac,aw=generator(lc,lw,dc,dw,mu,checks)
    counts=np.zeros(3,dtype=int); times=[]
    for _ in range(reps):
        s=0;t=0.
        while s<ac:
            rate=-Q[s,s]
            if rate<=0: break
            t+=rng.exponential(1/rate)
            if t>tmax: break
            probs=Q[s].copy();probs[s]=0;probs/=rate
            s=int(rng.choice(len(probs),p=probs))
        outcome=0 if s==ac else (1 if s==aw else 2)
        counts[outcome]+=1
        if s>=ac:times.append(t)
    return dict(counts=counts.tolist(),reps=reps,seed=seed,
                fractions=(counts/reps).tolist(),mean_completed_s=float(np.mean(times)))


def volume(q,m,t): return sum(math.comb(q,i)*(m-1)**i for i in range(t+1))
def code_bounds(q,m,d):
    return dict(q=q,m=m,d=d,raw=m**q,
                greedy_lower=math.ceil(m**q/volume(q,m,d-1)),
                hamming_upper=math.floor(m**q/volume(q,m,(d-1)//2)))

def greedy_code(q=8,m=4,d=3,limit=128,seed=809):
    rng=np.random.default_rng(seed);words=[]
    for candidate in rng.integers(0,m,size=(30000,q)):
        if not words or np.min(np.sum(np.array(words)!=candidate,axis=1))>=d:
            words.append(candidate)
            if len(words)==limit:break
    return np.array(words,dtype=int)


def write_csv(path,rows):
    rows=[{k:v for k,v in row.items() if k!='detail'} for row in rows]
    with path.open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=rows[0].keys());w.writeheader();w.writerows(rows)

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--output',type=Path,default=ROOT/'results');ap.add_argument('--quick',action='store_true');a=ap.parse_args()
    out=a.output;out.mkdir(parents=True,exist_ok=True);p=Parameters()
    baseline=[evaluate(N,m,p) for N in (16,64,256,1024,4096) for m in MODES]
    write_csv(out/'baseline.csv',baseline)
    (out/'baseline_details.json').write_text(json.dumps(baseline,indent=2))
    sweep=[]
    for N in ((64,256) if a.quick else (16,64,256,1024,4096)):
      for gap in (2.,4.,6.,8.):
       for mu in (0.03,0.1,0.3):
        for alpha in (0.,1.):
         pp=Parameters(gap_kbt=gap,progress_rate=mu,dilution_exponent=alpha)
         sweep.extend(evaluate(N,m,pp) for m in MODES)
    write_csv(out/'sweep.csv',sweep)
    # Floor sweep exposes fusion limits; not rare-event experimental evidence.
    floors=[]
    for pf in (0.,1e-8,1e-6,1e-4,1e-2):
      for N in (16,64,256,1024,4096):
       floors.append(evaluate(N,'locking',Parameters(fusion_error=pf)))
    write_csv(out/'fusion_sweep.csv',floors)
    cases=[(0.03,0.09,.01,.2,.1,0,1000.),(.03,.09,.01,.2,.1,2,1000.),(.03,.09,.01,.2,.1,2,30.)]
    validation=[]
    for i,case in enumerate(cases):
        exact=local_stats(*case)
        mc=gillespie(*case,reps=2000 if a.quick else 10000,seed=915+i)
        validation.append(dict(parameters=list(case),exact=[exact[0],exact[1],1-exact[0]-exact[1]],monte_carlo=mc))
    (out/'gillespie_validation.json').write_text(json.dumps(validation,indent=2))
    code=greedy_code(); np.savetxt(out/'example_codebook.csv',code,fmt='%d',delimiter=',')
    distances=np.sum(code[:,None,:]!=code[None,:,:],axis=-1);distances+=np.eye(len(code),dtype=int)*99
    codes=dict(bounds=[code_bounds(*x) for x in [(8,4,3),(16,4,4),(24,4,8)]],
               constructed=dict(words=len(code),q=8,m=4,minimum_distance=int(distances.min())))
    (out/'code_bounds.json').write_text(json.dumps(codes,indent=2))
    threshold=[]
    for eta in (0.,1e-8,1e-5,1e-3):
      for p0 in (.001,.01,.02,.04,.08):
       prob=p0
       for l in range(7):
        threshold.append(dict(eta=eta,p0=p0,level=l,p=prob,C=28,q=2))
        prob=min(1.,28*prob**2+eta)
    write_csv(out/'threshold.csv',threshold)
    manifest=dict(seed_policy='fixed explicit PCG64 seeds 915..917 and 809',
        default_parameters=asdict(p),baseline_rows=len(baseline),sweep_rows=len(sweep),
        gillespie_trajectories=sum(x['monte_carlo']['reps'] for x in validation),
        python=platform.python_version(),numpy=np.__version__,scipy=scipy.__version__,
        limitations=['Independent local sockets, ideal child provisioning, no free-cluster geometry',
                     'Parameters are illustrative, not experimentally fitted',
                     'Hierarchy does not repair hidden internal bonds',
                     'Code-symbol kinetics not inferred from DNA sequence'])
    (out/'run_manifest.json').write_text(json.dumps(manifest,indent=2))
    print(json.dumps(manifest,indent=2))
if __name__=='__main__':main()