#!/usr/bin/env python3
"""Original sparse CSS [[32,12,4]] construction. MIT license.

The 10x32 binary S has six unit columns, the 24 incidence columns of
K_{6,4}, and two triple columns partitioning the six left vertices.
Every row has weight six; every column has weight <=3.  The matching P
below makes S P S^T=0.  Its first discovery was matching_search.cpp,
mt19937_64 seed=1, --max-degree 4, 29520 attempted moves.  The fixed P is the mathematical
construction parameter; no search or external packages are needed to replay.

S has rank 10.  Its columns are nonzero, distinct, and have odd overlap
with the first six coordinates.  Hence ker(S) has distance at least 4.
Both checks are S up to a column permutation, so the CSS distance is >=4.
The explicit nontrivial weight-four logical below proves equality.
"""
import argparse
import itertools
import json
from pathlib import Path

PERMUTATION = [30,11,5,19,31,2,13,21,14,18,22,1,23,6,8,29,
               17,16,9,3,25,7,10,12,26,20,24,28,27,15,0,4]


def basis(rows):
    pivots = {}
    for v in rows:
        while v:
            b = v.bit_length()-1
            if b in pivots:
                v ^= pivots[b]
            else:
                pivots[b] = v
                break
    return pivots


def residual(v, pivots):
    while v:
        b = v.bit_length()-1
        if b not in pivots:
            break
        v ^= pivots[b]
    return v


def construct():
    cols = [1 << i for i in range(6)]
    cols += [(1 << i) | (1 << (j+6)) for i in range(6) for j in range(4)]
    cols += [7, 56]
    p = PERMUTATION
    assert sorted(p) == list(range(32))
    assert all(p[p[i]] == i and p[i] != i for i in range(32))
    hx = [sum(1 << q for q, c in enumerate(cols) if c >> r & 1) for r in range(10)]
    hz = [sum(1 << q for q in range(32) if cols[p[q]] >> r & 1) for r in range(10)]
    assert len(basis(hx)) == len(basis(hz)) == 10
    assert all((a & b).bit_count() % 2 == 0 for a in hx for b in hz)
    assert all(r.bit_count() == 6 for r in hx+hz)
    assert all(sum(r >> q & 1 for r in hx+hz) <= 4 for q in range(32))
    assert len(set(cols)) == 32 and all(c != 0 for c in cols)
    assert all((c & 63).bit_count() % 2 == 1 for c in cols)
    # Enumerate all classical syndromes through weight 3 independently.
    checked = 0
    for cc in (cols, [cols[p[q]] for q in range(32)]):
        for w in (1,2,3):
            for support in itertools.combinations(range(32), w):
                syndrome = 0
                for q in support:
                    syndrome ^= cc[q]
                assert syndrome
                checked += 1
    # A K_{6,4} rectangle is a classical weight-four codeword.
    rectangle = [6,7,10,11]
    logical = sorted(p[q] for q in rectangle)
    v = sum(1 << q for q in logical)
    assert all((c & v).bit_count() % 2 == 0 for c in hz)
    assert residual(v, basis(hx))
    # Independently enumerate all 2^10 stabilizers on both sides.
    min_stabilizer = []
    for checks in (hx,hz):
        words = [0]
        for r in checks:
            words += [v ^ r for v in words]
        assert len(set(words)) == 1024
        min_stabilizer.append(min(v.bit_count() for v in words if v))
    assert min_stabilizer == [6,6]
    rows = lambda checks: [[q for q in range(32) if c >> q & 1] for c in checks]
    art = {"n":32,"HX":rows(hx),"HZ":rows(hz),"d":4,
           "logical":{"type":"X","support":logical}}
    proof = {"n":32,"rank_HX":10,"rank_HZ":10,"k":12,"d":4,
             "efficiency":"6/1","maxdeg":max(sum(r >> q & 1 for r in hx+hz) for q in range(32)),
             "max_check_weight":6,"independent_supports_tested":checked,
             "classical_kernel_no_words_below":4,"min_nonzero_stabilizer_weights":min_stabilizer,
             "upper_witness":art["logical"],"permutation":p}
    return art, proof


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("output")
    parser.add_argument("--proof")
    args = parser.parse_args()
    artifact, proof = construct()
    Path(args.output).write_text(json.dumps(artifact,separators=(",",":"))+"\n")
    if args.proof:
        Path(args.proof).write_text(json.dumps(proof,indent=2)+"\n")
