hive-not-swarm
aien-dev/hive-not-swarm
Brought by drakestapleton
hive-not-swarm / verify_model.py
| 1 | from fractions import Fraction as F |
| 2 | from pathlib import Path |
| 3 | import csv,json,math |
| 4 | ROOT=Path(__file__).resolve().parent |
| 5 | base={'A':F(120),'S':F(10),'b':F(4,5),'c':F(3,20),'r0':F(3),'r':F(1,2),'H':F(6),'p':F(1,100),'eps':F(2,25),'P':16} |
| 6 | def calc(n,d): |
| 7 | T=d['S']+d['A']/n+d['b']*(n-1)+d['c']*n*(n-1)/2+d['r0']+d['r']*n |
| 8 | review=d['r0']+d['r']*n;risk=1-(1-d['p'])**n |
| 9 | return T,review,risk |
| 10 | |
| 11 | def solve(d): |
| 12 | rows=[(n,*calc(n,d)) for n in range(1,d['P']+1)];f=[x for x in rows if x[2]<=d['H'] and x[3]<=d['eps']] |
| 13 | return min(f,key=lambda x:x[1]) if f else None |
| 14 | expected=[('base',{},6,F(169,4)),('H10',{'H':F(10)},7,F(5823,140)),('p002',{'p':F(1,50)},4,F(483,10)),('P4',{'P':4},4,F(483,10)),('c06',{'c':F(3,5)},5,F(487,10)),('A30',{'A':F(30)},4,F(129,5)),('A240H10',{'A':F(240),'H':F(10)},8,F(284,5))] |
| 15 | report={} |
| 16 | for name,changes,n,t in expected: |
| 17 | d=base|changes;ans=solve(d);assert ans[0]==n and ans[1]==t,(name,ans) |
| 18 | report[name]={'n':ans[0],'T_exact':str(ans[1]),'T_minutes':float(ans[1]),'review_minutes':float(ans[2]),'risk_probability':float(ans[3])} |
| 19 | with open(ROOT/'model_grid.csv') as f: |
| 20 | for row in csv.DictReader(f): |
| 21 | n=int(row['agents']);t,rev,risk=calc(n,base) |
| 22 | assert math.isclose(float(row['minutes']),float(t),abs_tol=1e-10) |
| 23 | assert math.isclose(float(row['review_minutes']),float(rev),abs_tol=1e-10) |
| 24 | assert math.isclose(float(row['failure_probability']),float(risk),abs_tol=1e-12) |
| 25 | assert (row['feasible']=='True') == (rev<=base['H'] and risk<=base['eps']) |
| 26 | with open(ROOT/'sensitivity_grid.csv') as f: |
| 27 | rows=list(csv.reader(f));hs=[F(x) for x in rows[0][1:]] |
| 28 | for row in rows[1:]: |
| 29 | cc=F(row[0]) |
| 30 | for h,n in zip(hs,row[1:]):assert solve(base|{'c':cc,'H':h})[0]==int(n) |
| 31 | for n in range(1,16): |
| 32 | d=base;delta=calc(n+1,d)[0]-calc(n,d)[0] |
| 33 | assert delta==d['b']+d['r']+d['c']*n-d['A']/F(n*(n+1)) |
| 34 | assert [n for n in range(1,17) if calc(n,base)[1]<=base['H'] and calc(n,base)[2]<=base['eps']]==list(range(1,7)) |
| 35 | report['checks']={'model_grid':'PASS 16 rows','sensitivity_grid':'PASS 77 cells','discrete_difference':'PASS 15 transitions','all_inputs':'hypothetical not fitted'} |
| 36 | (ROOT/'model_verification.json').write_text(json.dumps(report,indent=2)+'\n') |
| 37 | print(json.dumps(report,indent=2)) |