File size: 6,020 Bytes
dc7349e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Neyaru minimal exact core. Python 3.10+, standard library only.
Run: python3 reference_core.py
The benchmark implementation is separate and reports full overhead.
"""
from dataclasses import dataclass
from math import inf


class Dihedral:
    """Elements r**a s**b encoded a + m*b; group order is 2*m."""
    def __init__(self, m):
        self.m, self.n = m, 2*m
        self.mul = [[((a % m) + (1 if a < m else -1)*(b % m)) % m
                     + m*((a // m) ^ (b // m))
                     for b in range(2*m)] for a in range(2*m)]
        self.inv = [next(b for b in range(self.n)
                         if self.mul[a][b] == 0) for a in range(self.n)]

    def closure(self, generators):
        found, queue = {0}, [0]
        for a in queue:
            for b in generators:
                c = self.mul[a][b]
                if c not in found:
                    found.add(c)
                    queue.append(c)
        return found


def stabilizer(G, values, left):
    """Rare-value filter, exact tests, and certified subgroup closure."""
    buckets = {}
    for x, v in enumerate(values):
        buckets.setdefault(v, []).append(x)
    if len(buckets) == 1:
        return frozenset(range(G.n))
    bucket = min(buckets.values(), key=len)
    anchor = bucket[0]
    candidates = [(G.mul[y][G.inv[anchor]] if left else
                   G.mul[G.inv[anchor]][y]) for y in bucket]
    known, generators = {0}, []
    for a in sorted(candidates):
        if a in known:
            continue
        if all(values[G.mul[a][x] if left else G.mul[x][a]] == values[x]
               for x in range(G.n)):
            generators.append(a)
            known = G.closure(generators)
    return frozenset(known)


@dataclass
class Kernel:
    values: tuple
    L: frozenset
    R: frozenset
    leaf: str = ""
    children: object = None
    choices: object = None

    def witness(self, boundary):
        if self.values[boundary] == inf:
            raise ValueError("infeasible boundary")
        if self.children is None:
            return [(self.leaf, boundary, self.values[boundary])]
        a, b = self.choices[boundary]
        u, v = self.children
        return u.witness(a) + v.witness(b)


def leaf(G, name, values):
    values = tuple(values)
    return Kernel(values, stabilizer(G, values, True),
                  stabilizer(G, values, False), leaf=name)


def compose(G, f, g, quotient=True, learn=True):
    """All role occurrences remain in the witness DAG.

    pairs counts only objective candidates, not total runtime.
    Complete symmetry and orbit costs are charged in the benchmark.
    """
    if quotient:
        H = f.R & g.L
        inner, covered = [], set()
        for a in range(G.n):
            if a not in covered:
                inner.append(a)
                covered.update(G.mul[a][h] for h in H)
        orbits, covered = [], set()
        for z in range(G.n):
            if z in covered:
                continue
            orbit = {}
            for l in sorted(f.L):
                for r in sorted(g.R):
                    x = G.mul[G.mul[l][z]][r]
                    orbit.setdefault(x, (l, r))
            covered.update(orbit)
            orbits.append((z, orbit))
    else:
        inner = list(range(G.n))
        orbits = [(z, {z: (0, 0)}) for z in range(G.n)]
    values, choices, pairs = [inf]*G.n, [None]*G.n, 0
    for z, orbit in orbits:
        best, arg = inf, None
        for a in inner:
            b = G.mul[G.inv[a]][z]
            score = f.values[a] + g.values[b]
            pairs += 1
            if score < best:
                best, arg = score, (a, b)
        for x, (l, r) in orbit.items():
            values[x] = best
            if arg is not None:
                a, b = arg
                # Retrieve child witnesses at NEW boundaries. Never edit
                # a primitive choice merely because aggregate costs agree.
                choices[x] = (G.mul[l][a], G.mul[b][r])
    values = tuple(values)
    L = stabilizer(G, values, True) if learn else f.L
    R = stabilizer(G, values, False) if learn else g.R
    out = Kernel(values, L, R, children=(f, g), choices=choices)
    for x, pair in enumerate(choices):
        if pair is not None:
            a, b = pair
            assert G.mul[a][b] == x
            assert f.values[a] + g.values[b] == values[x]
    return out, pairs


def verify_witness(G, kernel, boundary):
    # Enumerated positions distinguish repeated occurrences of a leaf type.
    product, cost = 0, 0
    for position, (leaf_type, action, action_cost) in enumerate(
            kernel.witness(boundary)):
        assert position >= 0 and leaf_type
        product = G.mul[product][action]
        cost += action_cost
    assert product == boundary and cost == kernel.values[boundary]


def demo():
    G = Dihedral(16)
    c, M = 3, 19

    def seed(j):
        step, size = G.m // (2**j), 2**j
        values = [M]*G.n
        for a in range(size//2 + 1):
            values[(a*step) % G.m] = 0
        values[G.m] = c
        return leaf(G, "f" + str(j), values)

    h, _ = compose(G, seed(1), seed(1))
    print("level  |L|  |R|  quotient_pairs  dense_pairs")
    for j in range(2, 5):
        f = seed(j)
        nxt, reduced_pairs = compose(G, h, f)
        dense, dense_pairs = compose(G, h, f, quotient=False, learn=False)
        assert nxt.values == dense.values and nxt.values != h.values
        expected_K = {a*(G.m//(2**j)) for a in range(2**j)}
        assert set(nxt.L) == expected_K == set(nxt.R)
        for boundary in range(G.n):
            verify_witness(G, nxt, boundary)
        print(j, len(nxt.L), len(nxt.R), reduced_pairs, dense_pairs)
        # Newly learned metadata changes the NEXT composition procedure.
        h = nxt
    assert h.values == tuple([0]*G.m + [c]*G.m)
    print("Exact table equality, new-kernel growth, and witnesses passed.")
    print("Pair counts exclude discovery/orbit overhead; see benchmark.")


if __name__ == "__main__":
    demo()