Research Atlas

Home / The cost of writing parity / Enumerating parity inputs

Python program

Enumerating parity inputs

The cost of writing parity

Python programcomplexity_parity.py
#!/usr/bin/env python3
"""Exact audit of a tempting but invalid P != NP proof step.

No external dependencies. Run from any directory. All finite verification uses
integer/Boolean operations. The all-n theorem is proved in notes/complexity.txt;
finite tests verify this implementation, not P versus NP.
"""
import argparse
import hashlib
import itertools
import json
from pathlib import Path
import platform
import time


def parity(bits):
    return sum(bits) % 2


def xor_circuit(n):
    # Wire indices 0,...,n-1 are inputs. AND/OR have fan-in two, NOT one.
    gates = []
    acc = 0
    for b in range(1, n):
        or_wire = n + len(gates)
        gates.append(("OR", acc, b))
        and_wire = n + len(gates)
        gates.append(("AND", acc, b))
        neg_wire = n + len(gates)
        gates.append(("NOT", and_wire))
        acc = n + len(gates)
        gates.append(("AND", or_wire, neg_wire))
    return gates, acc


def eval_circuit(bits, gates, output):
    values = list(map(bool, bits))
    for gate in gates:
        if gate[0] == "AND":
            values.append(values[gate[1]] and values[gate[2]])
        elif gate[0] == "OR":
            values.append(values[gate[1]] or values[gate[2]])
        elif gate[0] == "NOT":
            values.append(not values[gate[1]])
        else:
            raise ValueError(gate)
    return int(values[output])


def xor_cnf(n):
    # DIMACS indexing: x1,...,xn, then z2,...,zn.
    clauses = []
    acc = 1
    for j in range(2, n + 1):
        z = n + j - 1
        clauses.extend(((acc, j, -z), (acc, -j, z),
                        (-acc, j, z), (-acc, -j, -z)))
        acc = z
    clauses.append((acc,))
    return clauses


def eval_cnf(bits, clauses):
    return all(any(bits[abs(lit) - 1] == (lit > 0) for lit in clause)
               for clause in clauses)


def count_implicants_exhaustively(n):
    # -1 means that a coordinate is free. Explicitly enumerate every cube and
    # every compatible assignment, independently of the all-n proof.
    count = 0
    non_full = 0
    tested_cubes = 0
    tested_extensions = 0
    for cube in itertools.product((-1, 0, 1), repeat=n):
        tested_cubes += 1
        free = [i for i, value in enumerate(cube) if value == -1]
        is_implicant = True
        for extension in itertools.product((0, 1), repeat=len(free)):
            bits = list(cube)
            for i, value in zip(free, extension):
                bits[i] = value
            tested_extensions += 1
            if parity(bits) != 1:
                is_implicant = False
            # Deliberately no early exit: every compatible assignment checked.
        if is_implicant:
            count += 1
            non_full += bool(free)
    assert count == 2 ** (n - 1)
    assert non_full == 0
    assert tested_cubes == 3 ** n
    assert tested_extensions == 4 ** n
    return {"n": n, "cubes_tested": tested_cubes,
            "compatible_assignments_tested": tested_extensions,
            "implicants": count, "implicants_with_free_variables": non_full,
            "minimum_dnf_terms": count,
            "minimum_is_certified_because_each_implicant_is_a_singleton": True}


def verify_cnf_projection(n):
    clauses = xor_cnf(n)
    checked = 0
    positive_inputs = 0
    for x in itertools.product((0, 1), repeat=n):
        satisfying_extensions = 0
        for z in itertools.product((0, 1), repeat=n - 1):
            checked += 1
            satisfying_extensions += eval_cnf(x + z, clauses)
        assert satisfying_extensions == parity(x)
        positive_inputs += parity(x)
    assert len(clauses) == 4 * (n - 1) + 1
    return {"n": n, "variables": 2 * n - 1,
            "clauses": len(clauses), "maximum_clause_width": max(map(len, clauses)),
            "assignments_checked": checked,
            "positive_inputs": positive_inputs,
            "projection_matches_parity": True,
            "extension_is_unique_for_each_positive_input": True}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--max-cube-n", type=int, default=8)
    parser.add_argument("--max-cnf-n", type=int, default=8)
    parser.add_argument("--max-circuit-n", type=int, default=12)
    parser.add_argument("--output", type=Path,
                        default=Path(__file__).with_name("complexity_parity_results.json"))
    args = parser.parse_args()
    started = time.monotonic()
    circuits = []
    for n in range(1, args.max_circuit_n + 1):
        gates, output = xor_circuit(n)
        for bits in itertools.product((0, 1), repeat=n):
            assert eval_circuit(bits, gates, output) == parity(bits)
        circuits.append({"n": n, "ordinary_circuit_gates": len(gates),
                         "assignments_checked": 2 ** n,
                         "minimum_dnf_terms_from_all_n_lemma": 2 ** (n - 1)})
    result = {
        "experiment": "parity_representation_and_false_lower_bound_audit",
        "status": "P versus NP not solved; known restricted lower bound reproduced",
        "python": platform.python_version(),
        "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "cube_enumeration": [count_implicants_exhaustively(n)
                             for n in range(1, args.max_cube_n + 1)],
        "existential_3cnf_projection": [verify_cnf_projection(n)
                                       for n in range(1, args.max_cnf_n + 1)],
        "ordinary_circuit_verification": circuits,
        "falsified_claim": "every ordinary circuit computing f has at least minDNF(f) gates",
        "counterexample": next(row for row in circuits
                               if row["ordinary_circuit_gates"] > 0
                               and row["ordinary_circuit_gates"]
                               < row["minimum_dnf_terms_from_all_n_lemma"]),
        "interpretation": "This is a counterexample to a proof step, not a counterexample to P != NP.",
        "elapsed_seconds": time.monotonic() - started,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"output": str(args.output),
                      "counterexample": result["counterexample"],
                      "all_checks_passed": True,
                      "elapsed_seconds": result["elapsed_seconds"]}, indent=2))


if __name__ == "__main__":
    main()

The original records reflect the work at the time of writing. The article gives the final interpretation and scope.

Original file checksum · SHA-256da16ce114b9da8c91735bc5520e6115bc361d31b7864c1c2d411370da0a82509