File size: 13,021 Bytes
0dd9df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""Independent rational elimination, counting and threshold checks. Standard library."""
from collections import deque, Counter
from fractions import Fraction as F
from itertools import combinations, permutations, product
from random import Random
import json
from spectral_lift import (SignedGraph, base_from_support, coefficients, cubic_lift,
                           padded_subdivision, path_polys, transfer_polynomial, validate, integer_lift)
from fiber_count import balance_model_weights, formula_count, matching_formula, orthogonal_count
from signings import build


def raw_matrix(graph, t):
    diag = [t]*graph.order
    adj = [{} for _ in range(graph.order)]
    for u,v,s in graph.edges:
        adj[u][v] = adj[v][u] = F(-s)
    return diag,adj


def eliminate(diag,adj,v):
    pivot = diag[v]
    assert pivot, "An integer adjacency cannot have noninteger rational eigenvalue."
    links = list(adj[v].items())
    for u, value in links:
        del adj[u][v]
        diag[u] -= value*value/pivot
    for (u,a),(w,b) in combinations(links,2):
        cross = adj[u].get(w,0) - a*b/pivot
        if cross:
            adj[u][w] = adj[w][u] = cross
        elif w in adj[u]:
            del adj[u][w],adj[w][u]
    adj[v].clear()
    return pivot


def condense_raw(graph, keep, t=F(5,2)):
    diag,adj = raw_matrix(graph,t)
    hidden = set(range(graph.order))-set(keep)
    q=deque(sorted(v for v in hidden if len(adj[v]) <= 2))
    eliminated = 0
    while q:
        v=q.popleft()
        if v not in hidden or len(adj[v])>2:
            continue
        ns=list(adj[v])
        assert eliminate(diag,adj,v)>0
        hidden.remove(v)
        eliminated += 1
        q.extend(w for w in ns if w in hidden and len(adj[w])<=2)
    assert not hidden
    return diag,adj,eliminated


def exact_inertia(diag,adj,keep):
    # Eliminate minimum current degree, so small illustrative graphs stay sparse.
    active=set(keep)
    negative=0
    while active:
        v=min(active,key=lambda w:(len(adj[w]),w))
        negative += eliminate(diag,adj,v)<0
        active.remove(v)
    return negative


def bipartite(graph):
    ns=validate(graph,3)
    color={}
    for start in range(graph.order):
        if start in color:
            continue
        color[start]=0
        q=deque([start])
        while q:
            v=q.popleft()
            for w in ns[v]:
                if w not in color:
                    color[w]=1-color[v]
                    q.append(w)
                elif color[w]==color[v]:
                    return False
    return True


def graph_schur_check(base, length, seed, exact=False):
    graph,cores=cubic_lift(base,length)
    assert bipartite(graph)
    rng=Random(seed)
    switch=[rng.choice((-1,1)) for _ in range(graph.order)]
    switched=SignedGraph(graph.order,[(u,v,s*switch[u]*switch[v]) for u,v,s in graph.edges])
    keep=list(range(15*base.order))
    diag,adj,eliminated=condense_raw(switched,keep)
    scale,r,rshort,c=coefficients(length)
    expected=[{} for _ in keep]
    occupied=[0]*base.order
    for u,v,sgn in base.edges:
        a,b=cores[u][2*occupied[u]],cores[v][2*occupied[v]]
        occupied[u]+=1
        occupied[v]+=1
        expected[a][b]=expected[b][a]=-sgn
    for sites in cores:
        for a,b in zip(sites,sites[1:]):
            expected[a][b]=expected[b][a]=-scale
        for j,u in enumerate(sites):
            endpoint=j in (0,14)
            coeff=(1 if endpoint else 2)*scale + F(1,2**length)
            coeff+= (1-c)*scale if endpoint else 0
            coeff+= int(j in (1,3,5))
            assert diag[u]*scale==coeff
            got={v:value*scale*switch[u]*switch[v] for v,value in adj[u].items()}
            assert got==expected[u]
    outcome=exact_inertia(diag,adj,keep) if exact else None
    return dict(vertices=graph.order,edges=len(graph.edges),eliminated=eliminated,
                exact_negative_pivots=outcome)


def integer_checks():
    base=SignedGraph(4,[(0,1,-1),(1,2,1),(2,3,-1),(3,0,1)])
    tests=0
    for t in range(3,10):
        graph=integer_lift(base,t)
        # From the tips inward, delete all pendant trees.
        d,adj,eliminated=condense_raw(graph,list(range(base.order)),F(t))
        assert d[:base.order]==[F(5,2)]*base.order
        assert {(v,w):adj[v][w] for v in range(base.order) for w in adj[v] if v<w}=={
            (min(v,w),max(v,w)):-s for v,w,s in base.edges}
        assert eliminated==graph.order-base.order
        tests+=1
    return tests


def exact_girth(graph):
    """Prune leaves, suppress maximal degree-two paths, use edge-deleted shortest paths."""
    from heapq import heappush, heappop
    ns=[set() for _ in range(graph.order)]
    for a,b,_ in graph.edges:
        ns[a].add(b)
        ns[b].add(a)
    q=deque(i for i,ne in enumerate(ns) if len(ne)<=1)
    while q:
        v=q.popleft()
        for w in list(ns[v]):
            ns[w].remove(v)
            ns[v].remove(w)
            if len(ns[w])==1:
                q.append(w)
    branch=[i for i,ne in enumerate(ns) if len(ne)>2]
    seen=set()
    joint={i:[] for i in branch}
    paths=[]
    for v in branch:
        for u in ns[v]:
            key=tuple(sorted((v,u)))
            if key in seen:
                continue
            seen.add(key)
            a,b,dist=v,u,1
            while len(ns[b])==2:
                c=next(x for x in ns[b] if x!=a)
                seen.add(tuple(sorted((b,c))))
                a,b,dist=b,c,dist+1
            i=len(paths)
            paths.append((v,b,dist))
            joint[v].append((b,dist,i))
            joint[b].append((v,dist,i))
    best=float('inf')
    for i,(a,b,w) in enumerate(paths):
        distances={a:0}
        heap=[(0,a)]
        while heap:
            d,u=heappop(heap)
            if d!=distances[u]:
                continue
            if u==b:
                best=min(best,d+w)
                break
            for v,length,index in joint[u]:
                nd=d+length
                if index!=i and nd+w<best and nd<distances.get(v,float('inf')):
                    distances[v]=nd
                    heappush(heap,(nd,v))
    # Cycles that have no branch vertex also survive pruning.
    for a,ne in enumerate(ns):
        for b in ne:
            if tuple(sorted((a,b))) in seen:
                continue
            v,u,dist=a,b,0
            while True:
                seen.add(tuple(sorted((v,u))))
                dist+=1
                if u==a:
                    break
                w=next(x for x in ns[u] if x!=v)
                v,u=u,w
            best=min(best,dist)
    return best


def test_local():
    for L in range(2,66,2):
        scale,r,short,c=coefficients(L)
        assert scale*(r-short)==1 and scale*(F(1,2)-r)==F(1,2**L)
        assert 0<scale*(1-c)<=F(17,8*2**L)
        if L>=14:
            assert (scale*F(4,225)-1-F(1,1000))*(F(1,90)-F(1,1000))>1
            assert 15*F(1,2**L)+2*scale*(1-c)<F(1,100)
    assert path_polys(F(5,2),1)==[1,F(5,2)]
    return 32


def subdivision_checks():
    base=SignedGraph(5,[(0,1,-1),(1,2,1),(0,2,1),(1,3,-1),(3,4,1)])
    nodes=list(range(base.order))
    tests=0
    for j in range(1,11):
        graph=padded_subdivision(base,j)
        for t in (F(9,4),F(5,2),F(8,3)):
            diag,adj,_=condense_raw(graph,nodes,t)
            p=path_polys(t,j)[j-1]
            f=transfer_polynomial(t,j)
            assert all(diag[v]*p==f for v in nodes)
            got={ (u,v):adj[u][v]*p for u in nodes for v in adj[u] if u<v }
            assert got=={(min(u,v),max(u,v)):-s for u,v,s in base.edges}
            tests+=1
    # Certified rational isolating intervals on the increasing branch.
    intervals=[]
    for j in (1,2,3,4,8,16,32,64):
        lo,hi=F(2121320343559642573202,10**21),F(5,2)
        # lo is a rigorous lower bound for 3/sqrt(2).
        assert lo*lo<F(9,2) and transfer_polynomial(lo,j)<F(5,2)
        for _ in range(62):
            mid=(lo+hi)/2
            if transfer_polynomial(mid,j)<F(5,2):
                lo=mid
            else:
                hi=mid
        assert transfer_polynomial(lo,j)<F(5,2)<=transfer_polynomial(hi,j)
        intervals.append(dict(index=j,approx=round(float(hi),12)))
    return {"exact_Schur_tests":tests,"thresholds":intervals}


def raw_sign_test():
    # K_2,k: the positive squared singular values are k ± |sum_j s_j|.
    tests=[]
    for k,patterns in ((4,[[1]*4,[-1,1,1,1]]),(5,[[1]*5,[-1,1,1,1,1]]),
                       (6,[[1]*6,[-1,-1,1,1,1,1]])):
        for i,pat in enumerate(patterns):
            base=SignedGraph(k+2,[(a,2+j,1 if a==0 else pat[j]) for a in range(2) for j in range(k)])
            sq=k+abs(sum(pat))
            result=graph_schur_check(base,14,k+i,True)
            assert (result['exact_negative_pivots']==0)==(sq<=8)
            tests.append(dict(k=k,squared_base_radius=sq,**result))
    return tests


def exact_one_solutions(formula):
    """Use private deterministic unit propagation for count tests including prefix bits."""
    variables={x for cl in formula for x in cl}
    def find(fixed):
        while True:
            progress=False
            for cl in formula:
                ones=sum(fixed.get(v,0) for v in cl)
                left=[x for x in cl if x not in fixed]
                if ones>1 or (not left and ones!=1):
                    return []
                force={}
                if ones:
                    force=dict.fromkeys(left,0)
                elif len(left)==1:
                    force[left[0]]=1
                else:
                    force={v:0 for v,k in Counter(left).items() if k>1}
                if force:
                    fixed.update(force)
                    progress=True
            if not progress:
                break
        if len(fixed)==len(variables):
            return [sum(fixed.values())]
        v=min(variables-fixed.keys())
        return find({**fixed,v:0})+find({**fixed,v:1})
    return find({})


def count_checks():
    cl=list(combinations(range(4),3))+[(0,0,0),(0,0,1),(2,3,3)]
    tests=0
    for width in (1,2,3):
        for f in combinations(cl,width):
            g=build(f)
            assert orthogonal_count(g.unsigned())==formula_count(f,len(g.columns))
            tests+=1
    pm=0
    for n in (1,2,3):
        for mask in range(1<<(n*n)):
            mat=[[(mask>>(n*i+j))&1 for j in range(n)] for i in range(n)]
            perm=sum(all(mat[i][col] for i,col in enumerate(cols)) for cols in permutations(range(n)))
            f=matching_formula(mat)
            balanced,wt=balance_model_weights(f)
            models=exact_one_solutions(balanced)
            assert len(models)==perm and all(k==wt for k in models)
            pm+=1
    return dict(raw_graph_counts=tests,permanent_encodings=pm)


def shortest_cycle_offsets():
    """Enumerate base four-cycles and lift their lengths symbolically for all L."""
    counts = {}
    for label, assignment in (("witness", [0, 1]), ("fallback", None)):
        support = build([(0, 0, 1)], assignment)
        base = base_from_support(support)
        port = [{} for _ in range(base.order)]
        for u, v, sign in base.edges:
            port[u][v] = (2 * len(port[u]), sign)
            port[v][u] = (2 * len(port[v]), sign)
        cycles = []
        for a, c in combinations(range(support.nrows), 2):
            for b, d in combinations(sorted(port[a].keys() & port[c].keys()), 2):
                offset = 0
                product_sign = 1
                for prev, cur, nxt in ((d, a, b), (a, b, c), (b, c, d), (c, d, a)):
                    offset += abs(port[cur][prev][0] - port[cur][nxt][0])
                    product_sign *= port[cur][nxt][1]
                cycles.append((offset, product_sign))
        shortest = min(offset for offset, sign in cycles)
        products = [sign for offset, sign in cycles if offset == shortest]
        counts[label] = dict(offset=shortest, cycles=len(products), sign_sum=sum(products))
    assert counts["witness"] == dict(offset=8, cycles=39, sign_sum=-3)
    assert counts["fallback"] == dict(offset=8, cycles=39, sign_sum=3)
    return counts


def main():
    result={"shortest_four_cycle_offsets":shortest_cycle_offsets(),"integer_promotions":integer_checks(),"cap_length_tests":test_local(),"padded_subdivision":subdivision_checks(),
            "raw_inertia":raw_sign_test(),"counting":count_checks()}
    examples={}
    for name,f,assignment in (("yes",[(0,0,1)],[0,1]),("yes_bad_sign",[(0,0,1)],None),
                              ("no",[(0,0,0)],None)):
        s=build(f,assignment)
        b=base_from_support(s)
        g,_=cubic_lift(b,14)
        girth=exact_girth(g)
        assert girth>=56
        sample=graph_schur_check(b,14,717,exact=True)
        assert (sample['exact_negative_pivots']==0)==(name=="yes")
        examples[name]=dict(base_order=b.order,girth=girth,**sample)
    result["full_formula_graphs"]=examples
    print(json.dumps(result,indent=2,sort_keys=True))

if __name__=="__main__":
    main()