#!/usr/bin/env python3 """Find a small circuit with a SAT solver, or write the CNF whose refutation is a lower bound. python3 scripts/circuit.py cnf FUNCTION S OUT.cnf the approved encoding of "size(FUNCTION) <= S" (checks/circuits.py) python3 scripts/circuit.py find FUNCTION S OUT.ckt solve it with PySAT (pip install python-sat) and write the circuit FUNCTION is an id: mod3__, sum, maj, thr_. A lower bound "size(F) > S" is a proof that the CNF has no model, which a solver writes as LRAT, for example CaDiCaL: cadical --lrat=true --binary=false F.cnf F.gtS.lrat (gzip it if it is large: the check reads F.gtS.lrat.gz). The check regenerates the CNF itself, so hand in the proof only. Finding is the hard direction here too: SLIM (Kulikov, Pechenev and Slezkin, 2022) report seconds for 6 gates and days for 7 to 12; their local improvement (github.com/alexanderskulikov/circuit_improvement) goes further. """ import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "checks")) from circuits import computes, dimacs, encode, function # noqa: E402 def circuit(names, model, fid): """The circuit a model describes, as .ckt text: gate i reads the pair its selector picks and computes the normal function its three bits give; an output that must be negated has its gate's table flipped and every reader of that gate rewired, so the circuit keeps its size.""" true = {v for v in model if v > 0} n, s = names["n"], names["s"] node = [f"x{i + 1}" for i in range(n)] + [f"g{i + 1}" for i in range(s)] gates = {} for (i, j, k), v in names["sel"].items(): if v in true: bits = ["0"] + ["1" if names["fun"][(i, a, b)] in true else "0" for a, b in ((0, 1), (1, 0), (1, 1))] gates[i] = [node[j], node[k], bits] outs = sorted((h, i) for (h, i), v in names["out"].items() if v in true) flip = {i for h, i in outs if names["neg"][h]} if any(not names["neg"][h] and i in flip for h, i in outs): raise SystemExit("an output and its negation share a gate; try again with S + 1") for i in sorted(flip): gates[i][2] = ["1" if b == "0" else "0" for b in gates[i][2]] for g in gates.values(): # a reader sees the flipped node: index its table by the negated input a, b = g[0] == node[i], g[1] == node[i] if a or b: tt = g[2] g[2] = [tt[2 * (x ^ a) + (y ^ b)] for x in (0, 1) for y in (0, 1)] lines = [f"{n} {s} {len(outs)}", " ".join(node[:n])] lines += [f"{node[i]} {a} {b} {''.join(tt)}" for i, (a, b, tt) in sorted(gates.items())] lines.append(" ".join(node[i] for h, i in outs)) text = "\n".join(lines) + "\n" assert computes(fid, text, "the circuit read back") == s return text def main(cmd, fid, s, out): function(fid) nv, clauses, names = encode(fid, int(s)) if cmd == "cnf": Path(out).write_text(dimacs(nv, clauses, f"{fid}: some circuit of at most {s} gates over B2")) return print(f"{out}: {nv} variables, {len(clauses)} clauses") from pysat.solvers import Solver t = time.time() with Solver(name="cadical195", bootstrap_with=clauses) as solver: if not solver.solve(): return print(f"no circuit of at most {s} gates computes {fid} ({time.time() - t:.1f} s): a lower bound, if a proof says so") Path(out).write_text(circuit(names, solver.get_model(), fid)) print(f"{out}: {fid} in {s} gates, found in {time.time() - t:.1f} s") if __name__ == "__main__": if len(sys.argv) != 5 or sys.argv[1] not in ("cnf", "find"): sys.exit(__doc__) main(*sys.argv[1:])