File size: 7,443 Bytes
fda6cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Public feedback solver audit against independently known exact models."""
from fractions import Fraction as F
from pathlib import Path
import json
import subprocess
import sys
import tempfile
from feedback_frontier import analyze

ROOT=Path(__file__).resolve().parent
checks=0
cases=[]

def check(ok,label):
    global checks
    if not ok:raise AssertionError(label)
    checks+=1

def matrix(d,terms):
    q=[[0 for _ in range(d)] for _ in range(d)]
    for i,j,value in terms:q[i-1][j-1]=value
    return q

def input_one(q,alpha=None):
    data={'generators':[q],'probabilities':['1']}
    if alpha is not None:data['alpha']=alpha
    return data

def basic(data,name,h,b,beta):
    result=analyze(data)
    check(result['nilpotent_base_certified'],(name,'base certified'))
    check(result['h']==h,(name,'height'))
    check(result['b']==b,(name,'spectral order'))
    check(result['beta']==beta,(name,'frontier'))
    check(result['M']==len(data['generators'][0])**2,(name,'operator dimension'))
    check(json.loads(json.dumps(result))==result,(name,'JSON roundtrip'))
    cases.append({'name':name,'h':h,'b':b,'beta':beta})
    return result

def zero_matrix(d):return [['0']*d for _ in range(d)]

def main():
    scalar=input_one(matrix(1,[(1,1,{'2':'1'})]),'4')
    result=basic(scalar,'scalar feedback',0,'4','4')
    check(result['critical']['initial_derivatives']==[[['1']]],'scalar initial value')
    check(result['critical']['ode_coefficients']==['-1'],'scalar exponential ODE')
    check(result['full_horizon_iff_N_t_beta_bounded'],'scalar all-horizon law')
    check(result['alpha_phase']['kind']=='entire_ode','scalar critical phase')
    for alpha,kind in [('2','polynomial'),('5','exponential')]:
        data=dict(scalar,alpha=alpha);phase=analyze(data)['alpha_phase']
        check(phase['kind']==kind,('scalar alpha phase',alpha))
        if kind=='exponential':check(phase['r']['polynomial_coefficients_descending']==['1','-1'],'exact spectral coefficient polynomial')

    cycle=input_one(matrix(3,[(1,2,1),(2,3,1),(3,1,{'1':'1'})]),'2/3')
    result=basic(cycle,'fractional three-cycle',2,'2/3','2/3')
    check(result['v_k']==[0,0,0,2,2,2,4,4,4],'cycle exact moment orders')
    check(result['critical']['ode_coefficients']==['0','0','-3','0','0','3','0','0','-1'],'cycle exact characteristic limit')
    E33=zero_matrix(3);E33[2][2]='1'
    for k,L in enumerate(result['critical']['initial_derivatives']):check(L==(E33 if k%3==2 else zero_matrix(3)),('cycle leading derivative',k))
    check(result['critical']['first_attaining_word_length']==5,'cycle first higher tie')
    check(result['alpha_phase']['gamma']=='4/3','spectral phase normalization')

    two_cycle=input_one(matrix(2,[(1,2,1),(2,1,{'1':'1'})]),'1/2')
    result=basic(two_cycle,'two-cycle feedback',1,'1','1')
    check(result['critical']['ode_coefficients']==['0','-2','0','1'],'two-cycle sinh ODE')
    check(result['alpha_phase']['kind']=='polynomial' and result['alpha_phase']['face_indices']==[1],'subcritical Newton face')

    protected=input_one(matrix(4,[(1,2,1),(1,3,1),(2,4,{'1':'1'}),(3,4,{'1':'-1'})]),'5')
    result=basic(protected,'protected signed cancellation',1,'infinity','infinity')
    check(result['all_horizons_baseline_bound'],'protected every horizon')
    check(result['critical'] is None,'no finite protected critical scale')
    check(result['alpha_phase']['gamma']=='5' and result['alpha_phase']['face_indices']==[1],'protected exact Newton profile')

    canceled_cycle=input_one(matrix(4,[(1,2,1),(1,3,1),(2,4,{'1':'1'}),(3,4,{'1':'-1'}),(4,1,{'2':'1'})]))
    result=basic(canceled_cycle,'graph feedback canceled exactly',1,'infinity','3')
    check(result['v_k'][:4]==[0,0,4,6],'canceled graph transient orders')
    check(result['critical']['first_attaining_word_length']==3,'canceled graph first tie')

    transient=input_one(matrix(4,[(1,2,1),(1,3,1),(2,4,{'1':'1'}),(3,4,{'1':'-2'}),(4,1,{'3':'1'})]),'8/3')
    result=basic(transient,'transient before spectral feedback',1,'8/3','2')
    check(result['full_horizon_iff_N_t_beta_bounded'],'transient exact arbitrary horizon law')
    check(result['alpha_phase']['kind']=='entire_ode' and result['alpha_phase']['gamma']=='10/3','later spectral ODE normalization')
    check(analyze(dict(transient,alpha='2'))['alpha_phase']['kind']=='polynomial','early critical scale is polynomial')

    logarithmic=input_one(matrix(3,[(1,2,1),(3,3,{'1':'1'})]),'3')
    result=basic(logarithmic,'logarithmic-window counterexample',1,'2','2')
    check(not result['full_horizon_iff_N_t_beta_bounded'],'full-horizon iff correctly rejected')
    check(result['critical']['first_attaining_word_length'] is None,'no higher critical tie')
    check(all(L==zero_matrix(3) for L in result['critical']['all_horizon_test_block']),'finite pure baseline certificate')
    check(result['alpha_phase']['kind']=='exponential','superspectral phase selected')

    zero=input_one([[0]],'7')
    result=basic(zero,'zero family',0,'infinity','infinity')
    check(result['alpha_phase']['limit_polynomial_coefficients']=={'0':[['1']]},'zero family identity profile')

    rejection=analyze(input_one([[1]]))
    check(rejection['status']=='rejected' and not rejection['nilpotent_base_certified'],'nonnilpotent base rejection')
    check('beta' not in rejection,'no unsupported frontier after rejection')

    invalid=[
        {'generators':[]},
        {'generators':[[[0,1]]]},
        {'generators':[[[{'-1':'1'}]]]},
        {'generators':[[[{'1/2':'1'}]]]},
        {'generators':[[[0]]],'probabilities':['0']},
        {'generators':[[[0]]],'probabilities':['1/2']},
        {'generators':[[[True]]]},
        {'generators':[[[0]]],'alpha':'0'}]
    for data in invalid:
        try:analyze(data)
        except (ValueError,TypeError,KeyError,ZeroDivisionError):check(True,'invalid input rejected')
        else:check(False,('invalid input accepted',data))

    # CLI bytes must reproduce the stored exact example and carry rejection exit 2.
    completed=subprocess.run([sys.executable,str(ROOT/'feedback_frontier.py'),str(ROOT/'feedback_input.json')],text=True,capture_output=True)
    check(completed.returncode==0,'example CLI successful')
    check(json.loads(completed.stdout)==json.loads((ROOT/'feedback_output.json').read_text()),'stored example exact CLI reproduction')
    with tempfile.TemporaryDirectory() as tmp:
        path=Path(tmp)/'input.json';path.write_text(json.dumps(input_one([[1]])))
        completed=subprocess.run([sys.executable,str(ROOT/'feedback_frontier.py'),str(path)],text=True,capture_output=True)
        check(completed.returncode==2 and json.loads(completed.stdout)['status']=='rejected','CLI nonnilpotent rejection status')
        # JSON decimal tokens retain their literal rational values at the CLI.
        path.write_text('{"generators":[[[0]],[[0]],[[0]]],"probabilities":[0.1,0.2,0.7]}')
        completed=subprocess.run([sys.executable,str(ROOT/'feedback_frontier.py'),str(path)],text=True,capture_output=True)
        check(completed.returncode==0 and json.loads(completed.stdout)['beta']=='infinity','exact decimal probability parsing')
    report={'method':'exact rational public API and JSON CLI checks','checks_passed':checks,'failures':0,'cases':cases}
    (ROOT/'feedback_api_results.json').write_text(json.dumps(report,indent=2)+'\n')
    print(json.dumps(report,indent=2))

if __name__=='__main__':main()