File size: 13,073 Bytes
d1c6c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Exact third-deficit classification and witnesses for m >= 6.

The analytic theorem concerns complex germs q_ij=-exp(theta_ij) at theta=0.
The executable witness routine deliberately accepts only real rational q with
abs(q+1)<1/20, a certified neighborhood where its unique-matching factors
cannot vanish. No floating-point zero threshold is used.
"""
from __future__ import annotations
from dataclasses import dataclass
from itertools import combinations, permutations
from math import comb, ceil
from typing import Mapping, Iterable
import sympy as sp
from .algebra import TwistedAlgebra, bits

Pair = tuple[int, int]
Component = tuple[str, tuple[int, ...]]


def pairs(m: int) -> tuple[Pair, ...]:
    return tuple(combinations(range(m), 2))


def directed_q(q: Mapping[Pair, sp.Expr], i: int, j: int) -> sp.Expr:
    if i == j:
        raise ValueError('distinct channel indices required')
    return q[i, j] if i < j else 1 / q[j, i]


def support_edges(m: int, q: Mapping[Pair, sp.Expr]) -> set[Pair]:
    return {e for e in pairs(m) if sp.simplify(q[e] + 1) != 0}


def all_components(m: int) -> tuple[Component, ...]:
    if m < 6:
        raise ValueError('the third-deficit classification requires m >= 6')
    return (tuple(('star', (v,)) for v in range(m))
            + tuple(('triangle', t) for t in combinations(range(m), 3))
            + tuple(('twin', p) for p in pairs(m)))


def component_membership(m: int, q: Mapping[Pair, sp.Expr]) -> tuple[Component, ...]:
    """Return every component containing a point; intersections are not collapsed."""
    E = support_edges(m, q)
    answer: list[Component] = []
    for kind, labels in all_components(m):
        if kind == 'star':
            valid = all(labels[0] in e for e in E)
        elif kind == 'triangle':
            valid = all(set(e) <= set(labels) for e in E)
        else:
            core = tuple(i for i in range(m) if i not in labels)
            valid = all(e[0] in labels or e[1] in labels for e in E)
            if valid:
                valid = all(sp.simplify(directed_q(q, i, p)
                                        - directed_q(q, core[0], p)) == 0
                            for p in labels for i in core[1:])
        if valid:
            answer.append((kind, labels))
    return tuple(answer)


def component_equations(m: int, component: Component) -> sp.Matrix:
    """Linear equations in ascending theta_ij coordinates over Q."""
    es = pairs(m); index = {e: k for k, e in enumerate(es)}
    n = len(es)
    def row(i: int, j: int) -> sp.Matrix:
        v = sp.zeros(1, n)
        v[0, index[min(i, j), max(i, j)]] = 1 if i < j else -1
        return v
    kind, labels = component
    if component not in all_components(m):
        raise ValueError('unknown component')
    rows = []
    if kind == 'star':
        rows = [row(i, j) for i, j in es if labels[0] not in (i, j)]
    elif kind == 'triangle':
        rows = [row(i, j) for i, j in es if not {i, j} <= set(labels)]
    else:
        core = tuple(i for i in range(m) if i not in labels)
        rows += [row(i, j) for i, j in combinations(core, 2)]
        rows += [row(i, p) - row(core[0], p) for p in labels for i in core[1:]]
    return sp.Matrix.vstack(*rows) if rows else sp.zeros(0, n)


def intersection_dimension(m: int, components: Iterable[Component]) -> int:
    rows = [component_equations(m, c) for c in components]
    return comb(m, 2) - (sp.Matrix.vstack(*rows).rank() if rows else 0)


def _small_shuffle(alg: TwistedAlgebra, vertices: Iterable[int]) -> sp.Expr:
    return alg.shuffle_bruteforce(sum(1 << i for i in vertices))


def complete_multipartite_parts(m: int, E: set[Pair]) -> tuple[tuple[tuple[int, ...], ...], tuple[int, ...]]:
    """Find the single nontrivial complete-multipartite component plus isolates.

    Raises ValueError unless this structure holds. This is a graph routine,
    not a replacement for checking the quartet cancellation hypothesis.
    """
    adj = [set() for _ in range(m)]
    for i, j in E:
        adj[i].add(j); adj[j].add(i)
    active = {i for i in range(m) if adj[i]}
    isolates = tuple(i for i in range(m) if not adj[i])
    if not active:
        return (), isolates
    remaining = set(active); groups = []
    while remaining:
        v = min(remaining)
        group = tuple(sorted(active - adj[v]))
        if v not in group or not set(group) <= remaining:
            raise ValueError('support is not complete multipartite plus isolates')
        groups.append(group); remaining -= set(group)
    part_of = {i: k for k, g in enumerate(groups) for i in g}
    if any(((i, j) in E) != (part_of[i] != part_of[j])
           for i, j in combinations(sorted(active), 2)):
        raise ValueError('support is not complete multipartite plus isolates')
    return tuple(groups), isolates


def multipartite_matching(groups: Iterable[Iterable[int]]) -> tuple[Pair, ...]:
    """Maximum matching: repeatedly take vertices from two largest parts."""
    work = [list(g) for g in groups if g]; out = []
    while len(work) >= 2:
        work.sort(key=lambda g: (-len(g), tuple(g)))
        a, b = work[0].pop(), work[1].pop()
        out.append(tuple(sorted((a, b))))
        work = [g for g in work if g]
    return tuple(out)


@dataclass(frozen=True)
class VisibilityCertificate:
    visible: bool
    motif: tuple[tuple[int, ...], ...] = ()
    normalized_response: sp.Expr = sp.S.Zero
    components: tuple[Component, ...] = ()

    def full_partition(self, m: int) -> tuple[int, ...]:
        if not self.visible:
            raise ValueError('an invisible point has no nonzero witness')
        used = {i for block in self.motif for i in block}
        blocks = tuple(sum(1 << i for i in block) for block in self.motif)
        return blocks + tuple(1 << i for i in range(m) if i not in used)


def certify_scalar(m: int, q: Mapping[Pair, sp.Expr]) -> VisibilityCertificate:
    """O(m^4) rational ring operations; excludes coefficient bit complexity.

    Returns a nonzero raw algebraic word coefficient up to its known crossing unit,
    or all containing components of the proved reduced resonance arrangement.
    """
    if m < 6:
        raise ValueError('m must be >= 6')
    alg = TwistedAlgebra(m, q)
    if any(not v.is_Rational or abs(v + 1) >= sp.Rational(1, 20) for v in alg.q.values()):
        raise ValueError('certified implementation requires rational |q_ij+1| < 1/20')
    q = alg.q
    for four in combinations(range(m), 4):
        value = _small_shuffle(alg, four)
        if value != 0:
            return VisibilityCertificate(True, (four,), value)
    E = support_edges(m, q)
    groups, isolates = complete_multipartite_parts(m, E)
    matching = multipartite_matching(groups)
    if len(matching) <= 1:
        memberships = component_membership(m, q)
        if not memberships:
            raise AssertionError('proved matching-one classification was violated')
        return VisibilityCertificate(False, components=memberships)
    if isolates:
        edge, other = matching[:2]
        triple = tuple(sorted((*other, isolates[0])))
        value = sp.expand((1 + q[edge]) * _small_shuffle(alg, triple))
        if value == 0:
            raise AssertionError('single-edge triple coefficient unexpectedly vanished')
        return VisibilityCertificate(True, (edge, triple), value)
    if len(matching) >= 3:
        motif = matching[:3]
        value = sp.prod(1 + q[e] for e in motif)
        return VisibilityCertificate(True, motif, value)
    core = max(groups, key=len)
    if len(core) != m - 2:
        raise AssertionError('multipartite matching bound failed')
    outliers = tuple(i for i in range(m) if i not in core)
    for p in outliers:
        other = next(v for v in outliers if v != p)
        for i, j in combinations(core, 2):
            if sp.simplify(directed_q(q, i, p) - directed_q(q, j, p)) != 0:
                k = next(v for v in core if v not in (i, j))
                triple = tuple(sorted((i, j, p)))
                edge = tuple(sorted((other, k)))
                value = sp.expand(_small_shuffle(alg, triple) * (1 + q[edge]))
                if value == 0:
                    raise AssertionError('nonuniform twin coefficient unexpectedly vanished')
                return VisibilityCertificate(True, (triple, edge), value)
    memberships = component_membership(m, q)
    if not memberships:
        raise AssertionError('proved twin classification was violated')
    return VisibilityCertificate(False, components=memberships)


def scalar_second_on_subset(q: Mapping[Pair, sp.Expr], vertices: Iterable[int]) -> bool:
    vertices = tuple(vertices)
    for p in vertices:
        core = tuple(i for i in vertices if i != p)
        if all(q[min(i,j), max(i,j)] == -1 for i,j in combinations(core, 2)):
            if all(sp.simplify(directed_q(q, i, p) - directed_q(q, core[0], p)) == 0
                   for i in core[1:]):
                return True
    return False


def predicted_rank(m: int, q: Mapping[Pair, sp.Expr]) -> int:
    """Exact full-state formula at deficit three, in the theorem's neighborhood."""
    if m < 6:
        raise ValueError('m must be >=6')
    E = support_edges(m, q)
    pair_losses = sum(all(i in cover or j in cover for i,j in E) for cover in pairs(m))
    singleton_losses = sum(scalar_second_on_subset(q, (i for i in range(m) if i != v))
                           for v in range(m))
    scalar_loss = bool(component_membership(m, q))
    return 2**m - pair_losses - singleton_losses - int(scalar_loss)


def direct_block_rank(m: int, q: Mapping[Pair, sp.Expr], r: int) -> int:
    """Independent all-subset shuffle DP, not the component classification."""
    if not 0 <= r <= m:
        raise ValueError('invalid block budget')
    P = TwistedAlgebra(m, q).shuffle_table()
    cost = [m+1] * (1 << m); cost[0] = 0
    for S in range(1, 1 << m):
        pivot = S & -S; B = S
        while B:
            if B & pivot and P[B] != 0:
                cost[S] = min(cost[S], 1 + cost[S ^ B])
            B = (B - 1) & S
    return sum(c <= r for c in cost)


def calibration_classes(m: int, selected_twins: Iterable[Pair]) -> tuple[tuple[Pair, ...], ...]:
    """Connected classes of edge rescalings forced equal by selected twins."""
    es = pairs(m); parent = {e: e for e in es}
    def root(e):
        while parent[e] != e:
            parent[e] = parent[parent[e]]; e = parent[e]
        return e
    def union(a,b):
        a,b = root(a),root(b)
        if a != b: parent[b] = a
    for pair in selected_twins:
        if pair not in es:
            raise ValueError('selected outlier pairs must be ascending valid pairs')
        for p in pair:
            group = [tuple(sorted((p, i))) for i in range(m) if i not in pair]
            for e in group[1:]: union(group[0], e)
    result: dict[Pair, list[Pair]] = {}
    for e in es: result.setdefault(root(e), []).append(e)
    return tuple(sorted((tuple(v) for v in result.values()), key=lambda v: v[0]))


def optimal_calibration_subfamily(m: int) -> tuple[Pair, ...]:
    """Attains ceil(2(m-1)/3); counts component constraints, not detector outputs."""
    if m < 6:
        raise ValueError('the proved sharp bound requires m >= 6')
    n = m - 1
    sizes = ([] if n % 3 == 0 else [4 if n % 3 == 1 else 5])
    sizes += [3] * ((n - sum(sizes)) // 3)
    start = 0; answer = []
    for size in sizes:
        group = range(start, start + size)
        answer.extend((i, i+1) for i in list(group)[:-1])
        start += size
    assert start == n and len(answer) == ceil(2*n/3)
    return tuple(answer)


def q_from_exponents(exponents: Iterable[Iterable[int]], base=sp.Rational(1001,1000)) -> dict[Pair, sp.Expr]:
    d = [list(row) for row in exponents]; m=len(d)
    if any(len(row) != m for row in d) or any(d[i][j] != -d[j][i] for i in range(m) for j in range(m)):
        raise ValueError('a square antisymmetric exponent array is required')
    return {(i,j): -sp.sympify(base)**d[i][j] for i,j in pairs(m)}


def example_point(m: int, kind: str, permutation: Iterable[int] | None = None) -> dict[Pair, sp.Expr]:
    d = [[0]*m for _ in range(m)]
    def put(i,j,v): d[i][j]=v;d[j][i]=-v
    if kind in ('star','uniform_star','star_twin'):
        for j in range(1,m):
            put(0,j,j if kind=='star' else (3 if kind=='star_twin' and j==m-1 else 2))
    elif kind=='triangle':
        for e,v in zip([(0,1),(0,2),(1,2)],[1,3,4]): put(*e,v)
    elif kind=='twin':
        for i in range(m-2): put(i,m-2,2);put(i,m-1,3)
        put(m-2,m-1,4)
    elif kind=='edge': put(0,1,2)
    elif kind=='double_star':
        for j in range(2,m): put(0,j,j);put(1,j,j+1)
        put(0,1,4)
    elif kind=='generic':
        for i,j in pairs(m): put(i,j,(3*i+2*j)%7+1)
    elif kind!='origin': raise ValueError('unknown example kind')
    if permutation is not None:
        p=tuple(permutation)
        if sorted(p)!=list(range(m)):raise ValueError('invalid permutation')
        d=[[d[p[i]][p[j]] for j in range(m)] for i in range(m)]
    return q_from_exponents(d)