"""Boolean circuits over the full binary basis B2: the functions this project tables, the .ckt format, the encoder of "some circuit of at most S gates computes F" as CNF, and a checker of LRAT proofs that such a CNF is unsatisfiable. Standard library only, so the check runs in python:3.12-slim with no network. Functions, by id: mod3__ 1 when x1 + ... + xn = r mod 3 shown as MOD3_^ sum the binary representation of x1 + ... + xn, shown as SUM_ least significant bit first, ceil(log2(n + 1)) outputs maj 1 when more than half of the inputs are 1 shown as MAJ_ thr_ 1 when at least k inputs are 1 shown as THR_^ The .ckt format is circuit_improvement's (Kulikov et al.): a line "n s m"; a line of the n input names; s gate lines "name a b tttt", where a and b are earlier nodes and tttt the gate's outputs on (a, b) = (0,0), (0,1), (1,0), (1,1); a line of the m output node names. Any of the 16 binary functions is one gate. """ import gzip import itertools import re MAX_INPUTS = 16 # a truth table of 2^16 rows times a few hundred gates is seconds; past that the check would not end class Wrong(Exception): """What a route handed in that the check refuses; its text is what the author reads.""" def function(fid): """(inputs, f) for a function id: f maps a tuple of input bits to the list of output bits.""" m = re.fullmatch(r"mod3_(\d+)_([012])|sum(\d+)|maj(\d+)|thr(\d+)_(\d+)", fid) if not m: raise Wrong(f"{fid}: not a function this project tables (mod3__, sum, maj, thr_)") if m[1]: n, r = int(m[1]), int(m[2]) f = lambda x: [int(sum(x) % 3 == r)] elif m[3]: n = int(m[3]) f = lambda x: [(sum(x) >> b) & 1 for b in range(n.bit_length())] elif m[4]: n = int(m[4]) f = lambda x: [int(2 * sum(x) > n)] else: k, n = int(m[5]), int(m[6]) f = lambda x: [int(sum(x) >= k)] if not 2 <= n <= MAX_INPUTS: raise Wrong(f"{fid}: {n} inputs; this check tables functions of 2 to {MAX_INPUTS} inputs") return n, f def shown(fid): """The name a function goes by on the project's board, as the cards write mathematics: MOD3_6^1, SUM_5, SUM_{10}, MAJ_7, THR_8^4 (a subscript of two digits in braces, so a card sets it whole).""" m = re.fullmatch(r"mod3_(\d+)_(\d)|sum(\d+)|maj(\d+)|thr(\d+)_(\d+)", fid) sub = lambda n: n if len(n) == 1 else f"{{{n}}}" if m[1]: return f"MOD3_{sub(m[1])}^{m[2]}" if m[3]: return f"SUM_{sub(m[3])}" if m[4]: return f"MAJ_{sub(m[4])}" return f"THR_{sub(m[6])}^{sub(m[5])}" def rows(n): """Every input, as bits x1 .. xn, x1 the most significant bit of the row's number.""" return [tuple((t >> (n - 1 - i)) & 1 for i in range(n)) for t in range(2 ** n)] def read_ckt(text, where): """The circuit a .ckt file describes, as (inputs, gates, outputs), or Wrong naming the line to fix.""" lines = [(i + 1, l.split()) for i, l in enumerate(text.splitlines()) if l.strip() and not l.lstrip().startswith("#")] if not lines: raise Wrong(f"{where}: empty") head = lines[0][1] if len(head) != 3 or not all(h.isdigit() for h in head): raise Wrong(f"{where}:{lines[0][0]}: the first line is 'n s m' (inputs, gates, outputs)") n, s, m = map(int, head) if len(lines) != 3 + s: raise Wrong(f"{where}: the header says {s} gates, so {3 + s} lines (header, inputs, gates, outputs); the file has {len(lines)}") inputs, outputs = lines[1][1], lines[-1][1] if len(inputs) != n or len(set(inputs)) != n: raise Wrong(f"{where}:{lines[1][0]}: {n} distinct input names expected") known, gates = set(inputs), [] for line, g in lines[2:2 + s]: if len(g) != 4 or g[1] not in known or g[2] not in known or not re.fullmatch(r"[01]{4}", g[3]) or g[0] in known: raise Wrong(f"{where}:{line}: a gate is 'name a b tttt', a and b earlier nodes, tttt four bits, the name new") known.add(g[0]) gates.append(g) if len(outputs) != m or set(outputs) - known: raise Wrong(f"{where}:{lines[-1][0]}: {m} output names expected, each a node of the circuit") return inputs, gates, outputs def computes(fid, text, where): """The number of gates of a circuit that computes fid on all 2^n inputs, or Wrong at the first input it gets wrong.""" n, f = function(fid) inputs, gates, outputs = read_ckt(text, where) if len(inputs) != n: raise Wrong(f"{where}: {shown(fid)} has {n} inputs, the circuit {len(inputs)}") for x in rows(n): v = dict(zip(inputs, x)) for name, a, b, tt in gates: v[name] = tt[2 * v[a] + v[b]] == "1" got, want = [int(v[o]) for o in outputs], f(x) if got != want: raise Wrong(f"{where}: on input {''.join(map(str, x))} the circuit gives {got}, {shown(fid)} is {want}") return len(gates) def encode(fid, s): """The CNF "some circuit of at most s gates over B2 computes fid", as (variables, clauses, names); names holds the variables a model is read back through (see scripts/circuit.py). The encoding is Kojevnikov, Kulikov and Yaroslavtsev's (SAT 2009), simplified: gates n .. n+s-1, each reads an ordered pair j < k of earlier nodes and computes a normal function (0 on (0,0)) that is neither constant 0 nor a projection; v(i, t) is gate i's value on input t; every output is one gate, compared with the function, negated when the function is 1 on input 0. It is complete: a circuit can be made normal by pushing negations into later gates and the outputs, constant and projection gates can be dropped, and a smaller circuit is padded to exactly s gates with unused gates (n >= 2).""" n, f = function(fid) if not 1 <= s <= 40: raise Wrong(f"{shown(fid)}: lower bounds are certified here for at most 40 gates") table = rows(n) outs = [f(x) for x in table] nv = 0 def var(): nonlocal nv nv += 1 return nv gates = range(n, n + s) sel = {(i, j, k): var() for i in gates for j, k in itertools.combinations(range(i), 2)} fun = {(i, a, b): var() for i in gates for a, b in ((0, 1), (1, 0), (1, 1))} val = {(i, t): var() for i in gates for t in range(len(table))} out = {(h, i): var() for h in range(len(outs[0])) for i in gates} cls = [] def exactly_one(xs): cls.append(list(xs)) cls.extend([-a, -b] for a, b in itertools.combinations(xs, 2)) for i in gates: exactly_one([sel[(i, j, k)] for j, k in itertools.combinations(range(i), 2)]) f01, f10, f11 = fun[(i, 0, 1)], fun[(i, 1, 0)], fun[(i, 1, 1)] cls += [[f01, f10, f11], [f01, -f10, -f11], [-f01, f10, -f11]] # not 0000, not 0011, not 0101 for j, k in itertools.combinations(range(i), 2): c = sel[(i, j, k)] for t, x in enumerate(table): vj = val[(j, t)] if j >= n else bool(x[j]) vk = val[(k, t)] if k >= n else bool(x[k]) vi = val[(i, t)] for a, b in itertools.product((0, 1), repeat=2): pre, skip = [-c], False for v, want in ((vj, a), (vk, b)): if isinstance(v, bool): skip |= v != bool(want) else: pre.append(-v if want else v) if skip: continue if (a, b) == (0, 0): cls.append(pre + [-vi]) else: g = fun[(i, a, b)] cls.append(pre + [-vi, g]) cls.append(pre + [vi, -g]) for h in range(len(outs[0])): exactly_one([out[(h, i)] for i in gates]) for i in gates: for t in range(len(table)): want = outs[t][h] ^ outs[0][h] cls.append([-out[(h, i)], val[(i, t)] if want else -val[(i, t)]]) return nv, cls, {"n": n, "s": s, "sel": sel, "fun": fun, "out": out, "neg": outs[0]} def dimacs(nv, clauses, comment=""): return f"c {comment}\np cnf {nv} {len(clauses)}\n" + "".join(" ".join(map(str, c)) + " 0\n" for c in clauses) def unsat(clauses, proof, where): """Check an LRAT proof (Cruz-Filipe, Heule, Hunt, Kaufmann and Schneider-Kamp, 2017) that the clauses are unsatisfiable: each added clause follows from its hints by unit propagation in the order given; deletions free clauses. RAT steps (negative hints) are refused rather than checked: CaDiCaL's proofs of these formulas have none. Returns the number of steps checked, or raises Wrong at the first step that does not check.""" live = {i + 1: c for i, c in enumerate(clauses)} steps = 0 for number, line in enumerate(proof, 1): parts = line.split() if not parts or parts[0] == "c": continue try: if parts[1] == "d": for x in parts[2:-1]: live.pop(int(x), None) continue nums = list(map(int, parts)) z = nums.index(0, 1) except ValueError: raise Wrong(f"{where}:{number}: not an LRAT line") new, lits, hints = nums[0], nums[1:z], nums[z + 1:-1] if nums[-1] != 0 or new in live: raise Wrong(f"{where}:{number}: an added clause needs a new id and a closing 0") true, conflict = {-l for l in lits}, False # the literals assumed true: the new clause's, negated for h in hints: c = live.get(h) if h < 0 or c is None: raise Wrong(f"{where}:{number}: hint {h} is {'a RAT hint, which this checker does not take' if h < 0 else 'no live clause'}") if any(l in true for l in c): raise Wrong(f"{where}:{number}: hint {h} is satisfied, not unit") rest = [l for l in c if -l not in true] if not rest: conflict = True break if len(rest) > 1: raise Wrong(f"{where}:{number}: hint {h} is not unit") true.add(rest[0]) if not conflict: raise Wrong(f"{where}:{number}: the hints do not reach a conflict") live[new] = lits steps += 1 if not lits: return steps raise Wrong(f"{where}: the proof ends without the empty clause") def proof_lines(path): """The lines of an LRAT proof, plain or gzipped.""" opener = gzip.open if path.name.endswith(".gz") else open with opener(path, "rt") as fh: yield from fh if __name__ == "__main__": # self-check: a full adder computes sum3 in 5 gates, a wrong one is caught, and "sum2 in 1 gate" has no model the # encoder misses (two outputs need two gates, so the CNF has a clause set no assignment satisfies trivially) adder = "3 5 2\nx y z\na x y 0110\nb a z 0110\nc x y 0001\nd a z 0001\ne c d 0111\nb e\n" assert computes("sum3", adder, "adder") == 5 try: computes("sum3", adder.replace("e c d 0111", "e c d 0001"), "bad") raise AssertionError("a wrong adder passed") except Wrong as e: assert "on input" in str(e) nv, cls, _ = encode("mod3_3_0", 2) assert nv > 0 and all(cls) print("circuits.py: self-check passed")