File size: 5,353 Bytes
52fc221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse,csv,json,math,platform,sys,time
from pathlib import Path
import numpy as np
import scipy
from scipy.stats import binom
from genome import make_target,compile_target,canonical
from local_growth import Config,simulate
from theory import *
from functionality import conductance

ROOT=Path(__file__).resolve().parents[1]

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--reps',type=int,default=8)
    args=parser.parse_args();out=ROOT/'results';out.mkdir(exist_ok=True)
    allres=[];genomes=[];start=time.time()
    cases=[('reference',{}),('no_repair',{'repair':0.}),
           ('early_lock',{'dwell':0.2}),('no_internal_supply',{'channel_spacing':0}),
           ('common_mode',{'common_mode':0.08}),('conversion_damage',{'transduction_error':0.10})]
    for dim,n,op in [(2,32,'paired_path'),(3,16,'braced_shell')]:
        target=make_target({'op':op,'n':n},dim)
        g,meta=compile_target(target,[{'op':op,'n':n}]);genomes.append({'dim':dim,**meta})
        (ROOT/'genomes'/f'target_{dim}d.json').write_bytes(canonical(g))
        gref=conductance(target) if dim==2 else None
        for label,changes in cases:
            for k in range(args.reps):
                cfg=Config(n=n,dim=dim,seed=20260919+1000*dim+k,steps=1000,**changes)
                res,arrays=simulate(g,cfg);res['case']=label;res['dim']=dim;res['replicate']=k
                if gref is not None:
                    value=conductance(arrays['final'])
                    res.update(conductance=value,target_conductance=gref,
                               conductance_relative_error=abs(value/gref-1),
                               functional_pass=bool(abs(value/gref-1)<=0.10))
                allres.append(res)
                if k==0: np.savez_compressed(out/f'snapshot_{dim}d_{label}.npz',**arrays)
            vals=allres[-args.reps:]
            print(dim,label, 'fidelity',round(np.mean([r['material_fidelity'] for r in vals]),4),
                  'complete',round(np.mean([r['completed_fraction'] for r in vals]),4),flush=True)
    (out/'growth_runs.json').write_text(json.dumps(allres,indent=2))
    keys=['dim','case','replicate','material_fidelity','structural_iou','defect_density',
          'completed_fraction','growth_time','repair_overhead','feed_consumed','feed_supplied',
          'mass_balance_residual','program_bytes','fuel_turnover_kBT_proxy',
          'conductance_relative_error','functional_pass']
    with (out/'growth_runs.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=keys,extrasaction='ignore');w.writeheader();w.writerows(allres)
    summary=[]
    for dim in [2,3]:
        for label,_ in cases:
            vals=[r for r in allres if r['dim']==dim and r['case']==label]
            row={'dim':dim,'case':label,'n_replicates':len(vals)}
            for key in ['material_fidelity','structural_iou','completed_fraction','growth_time','repair_overhead','feed_consumed']:
                a=np.array([r[key] for r in vals]);row[key+'_mean']=float(a.mean());row[key+'_sd']=float(a.std(ddof=1)) if len(a)>1 else 0.
            if dim==2:
                row['functional_passes']=sum(r['functional_pass'] for r in vals)
                row['conductance_relative_error_mean']=float(np.mean([r['conductance_relative_error'] for r in vals]))
            summary.append(row)
    (out/'growth_summary.json').write_text(json.dumps(summary,indent=2))
    # Isolated theorem benchmark, distinct from coupled lattice model.
    rng=np.random.default_rng(9062026); rows=[]
    rho=.20;regions=10_000;delta=.05;p0=.12;birth=.01;mu0=.3;u=.005
    for b in range(5,1601,5):
        mu=depletion_repair(b,mu0,.01)
        p=raw_error(p0,birth,mu,1000.,u)
        pe=raw_error(p0,birth,mu0,1000.,u)
        E=b*kl_bernoulli(rho,p) if p<rho else 0.
        rows.append({'b':b,'repair':mu,'raw_error':p,'exponent':E,
                     'channel_exponent':b*kl_bernoulli(rho,pe),
                     'module_failure':exact_module_failure(b,rho,p),
                     'channel_module_failure':exact_module_failure(b,rho,pe)})
    with (out/'access_redundancy.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
    best=max(rows,key=lambda r:r['exponent'])
    p=.08;mc=[]
    for b in [10,20,40,80,160]:
        ns=200000;sample=rng.binomial(b,p,ns);count=int(np.sum(sample>=math.ceil(rho*b)))
        mc.append({'b':b,'p':p,'rho':rho,'trials':ns,'failures':count,
                   'empirical':count/ns,'exact':exact_module_failure(b,rho,p),
                   'chernoff':math.exp(-b*kl_bernoulli(rho,p))})
    nums={'genomes':genomes,'best_no_channel_exponent_grid':best,
          'certified_region_ceiling_grid':delta*math.exp(best['exponent']),
          'redundancy_example':{'regions':10**6,'delta':.05,'rho':.2,'p':.04,
                                'required_b':needed_redundancy(10**6,.05,.2,.04)},
          'monte_carlo':mc,'max_mass_residual':max(abs(r['mass_balance_residual']) for r in allres),
          'python':platform.python_version(),'numpy':np.__version__,'scipy':scipy.__version__,
          'wall_seconds':time.time()-start,'seed_base':20260919}
    (out/'numerical_summary.json').write_text(json.dumps(nums,indent=2))
    print(json.dumps(nums,indent=2),flush=True)
if __name__=='__main__':main()