File size: 5,283 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
"""Yeonxiru II. Construct an unsigned reduction and exact example signings.
Positive triples may have repeated slots. Variables are nonnegative integers.
The default signing is the all-true fallback; construction uses no oracle.
"""
from collections import defaultdict
from dataclasses import dataclass
from itertools import combinations
import json


@dataclass(frozen=True)
class Port:
    rows: tuple
    cols: tuple


class Support:
    def __init__(self):
        self.nrows = 0
        self.columns = []
        self.clause_pairs = []

    def rows(self, count):
        start = self.nrows
        self.nrows += count
        return tuple(range(start, start + count))

    def column(self, values):
        self.columns.append(dict(values))
        return len(self.columns) - 1

    def entry(self, row, col, value):
        assert row not in self.columns[col] and value in (-1, 1)
        self.columns[col][row] = value

    def overlaps(self):
        by_pair = defaultdict(list)
        for col, entries in enumerate(self.columns):
            for pair in combinations(sorted(entries), 2):
                by_pair[pair].append(col)
        return by_pair

    def pair_columns(self, rows, products):
        a, b = rows
        return tuple(self.column({a: 1, b: product}) for product in products)

    def clause(self, values, parity):
        rows = self.rows(2)
        self.clause_pairs.append(rows)
        h0, h1, h2 = values
        if h0 * h1 * h2 != 1:
            raise ValueError("Canonical signing requires odd truth parity in each triangle.")
        products = [1, h0, h0 * h1]
        total = sum(products)
        fourth = -total if abs(total) == 1 else (1 if parity else -1)
        cols = self.pair_columns(rows, [*products, fourth])
        return [Port(rows, (cols[i], cols[(i + 1) % 3])) for i in range(3)]

    def occurrence(self, value):
        rows = self.rows(4)
        t = [1, -value, -1, value]
        self.column({row: 1 for row in rows})
        self.column(dict(zip(rows, t)))
        ports = []
        for a, b in ((0, 1), (1, 2), (2, 3), (0, 3)):
            pair = rows[a], rows[b]
            cols = self.pair_columns(pair, (-1, -t[a] * t[b]))
            ports.append(Port(pair, cols))
        return ports[:3]

    def relay(self, value):
        rows = self.rows(2)
        return (Port(rows, self.pair_columns(rows, (1, value))),
                Port(rows, self.pair_columns(rows, (-1, -value))))

    def cube(self, left, right):
        def mixed(i, j):
            a = self.columns[left.cols[j]][left.rows[i]]
            b = self.columns[right.cols[i]][right.rows[j]]
            return -a * b
        y = (mixed(0, 0), mixed(0, 1))
        x = (1, mixed(1, 0) * y[0])
        assert all(x[i] * y[j] == mixed(i, j) for i in range(2) for j in range(2))
        for i in range(2):
            self.entry(left.rows[i], right.cols[i], x[i])
            self.entry(right.rows[i], left.cols[i], y[i])

    def connect(self, left, right, value):
        first, second = self.relay(value)
        self.cube(left, first)
        self.cube(right, second)

    def complete(self):
        for (a, b), cols in self.overlaps().items():
            if len(cols) == 1:
                old = self.columns[cols[0]]
                self.pair_columns((a, b), (-old[a] * old[b],))
            else:
                assert len(cols) in (2, 4)
        degrees = [0] * self.nrows
        for column in self.columns:
            assert len(column) <= 4
            for row in column:
                degrees[row] += 1
        assert max(degrees) <= 8
        for row, degree in enumerate(degrees):
            for _ in range(8 - degree):
                self.column({row: 1})

    def unsigned(self):
        return [tuple(sorted(column)) for column in self.columns]

    def serialise(self):
        return {"rows": self.nrows, "signed_columns": [
            [[r, c[r]] for r in sorted(c)] for c in self.columns]}


def build(clauses, assignment=None, parity=False):
    if not clauses or any(len(c) != 3 for c in clauses):
        raise ValueError("Supply at least one triple.")
    values = {v: (1 if assignment is None or assignment[v] else -1)
              for cl in clauses for v in cl}
    support = Support()
    chains = defaultdict(list)
    for clause in clauses:
        ports = support.clause([values[v] for v in clause], parity)
        for var, terminal in zip(clause, ports):
            left, middle, right = support.occurrence(values[var])
            support.connect(terminal, middle, values[var])
            if chains[var]:
                support.connect(chains[var][-1], left, -values[var])
            chains[var].append(right)
    support.complete()
    return support


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("formula", help='JSON array such as [[0,0,1]]')
    parser.add_argument("--assignment", help="JSON Boolean or 0/1 list by variable ID")
    parser.add_argument("--parity", action="store_true", help="parity-constrained fallback")
    args = parser.parse_args()
    model = None if args.assignment is None else json.loads(args.assignment)
    print(json.dumps(build(json.loads(args.formula), model, args.parity).serialise()))