#!/usr/bin/env python3
"""Reproduce the shutter companion from the ten embedded capture matrices.

Run: python3 shutter-check.py           (NumPy)
     python3 shutter-check.py --exact   (also requires SymPy)
Entries use the archived |reference, receiver> order 00, 01, 10, 11.
The four-site records are at t=22.5 and the eighteen-site records at t=62.
Only the eighteen-site study's original fixed receiver phase is needed.

For a state J, let g = Tr(J_B²) - Tr(J²). Chen et al. (PRA 90, 032318)
give the exact margin g + 4 sqrt(det J) for a symmetric extension on B.
For J' = J + E, K = I ⊗ J_B - J and D = ||E||_1/2, direct expansion gives
g(J') - g(J) = 2 Tr(K E) + Tr(E_B²) - Tr(E²). The positive and negative
parts of E each have trace D, so Tr(K E) >= -width(K) D and Tr(E²) <= 2 D².
The positive root of g - 2 width(K) D - 2 D² thus gives a sufficient radius.
In the exact check a Bell-projector probability exceeds 1/2 throughout
the certified ball, so every state there is also entangled.
"""

import json
import sys

import numpy as np


def materialize(record):
    raw = np.array(record["real"]) + 1j * np.array(record["imag"])
    state = (raw + raw.conj().T) / (2 * raw.trace().real)
    assert np.linalg.norm(raw - state, ord="nuc") / 2 < 3e-13
    assert np.linalg.eigvalsh(state)[0] > 0
    return raw, state


def extension_test(state):
    indices = state.reshape(2, 2, 2, 2)
    receiver = indices.trace(axis1=0, axis2=2)
    gap = np.vdot(receiver, receiver).real - np.vdot(state, state).real
    determinant = np.linalg.det(state).real
    margin = gap + 4 * np.sqrt(determinant)
    pt = indices.transpose(0, 3, 2, 1).reshape(4, 4)
    negativity = -np.minimum(np.linalg.eigvalsh(pt), 0).sum()
    return receiver, negativity, gap, margin


def exact_checks():
    """Work over the exact printed decimals. No eigensolver is used here."""
    import sympy as sp

    records = json.loads(INPUTS, parse_float=sp.Rational)
    def positive_definite(matrix):
        # Sylvester's criterion for a Hermitian matrix.
        return all(matrix[:k, :k].det(method="domain-ge") > 0
                   for k in range(1, matrix.rows + 1))

    for label, record in records.items():
        raw = sp.Matrix(record["real"]) + sp.I * sp.Matrix(record["imag"])
        state = ((raw + raw.H) / (2 * sp.re(raw.trace()))).applyfunc(sp.expand)
        assert state == state.H and positive_definite(state) and state.trace() == 1
        receiver = state[:2, :2] + state[2:, 2:]
        gap = sp.expand((receiver**2).trace() - (state**2).trace())
        determinant = state.det(method="domain-ge")
        extendible = (gap >= 0) or (16 * determinant >= gap**2)
        assert bool(extendible) == (not label.startswith("4/open/"))
        if label == "18/combined":
            witness = sp.kronecker_product(sp.eye(2), receiver) - state
            lo, hi = sp.Rational("-0.21955"), sp.Rational("0.49865")
            assert positive_definite(witness - lo * sp.eye(4))
            assert positive_definite(hi * sp.eye(4) - witness)
            d = sp.Rational("0.0357")
            assert gap > sp.Rational("0.0538695")
            assert gap - 2 * (hi - lo) * d - 2 * d**2 > sp.Rational("0.000041")
            bell_minus = (state[0, 0] + state[3, 3] - 2 * sp.re(state[0, 3])) / 2
            assert bell_minus - d > sp.Rational(1, 2)
    print("Exact decimal checks passed: 10 positive states, 10 extension signs, radius 0.0357.")


def main():
    matrices = {name: materialize(r) for name, r in json.loads(INPUTS).items()}
    print("capture             negativity       purity gap    extension margin")
    for label, (_, state) in matrices.items():
        _, neg, gap, margin = extension_test(state)
        print(f"{label:17} {neg:15.12f} {gap:15.12f} {margin:18.12f}")

    raw, state = matrices["18/combined"]
    receiver, _, gap, _ = extension_test(state)
    reference = state.reshape(2, 2, 2, 2).trace(axis1=1, axis2=3)
    reference_distance = np.linalg.norm(reference - np.eye(2) / 2, ord="nuc") / 2
    print(f"primary reference trace distance from I/2: {reference_distance:.12f}")
    width = np.ptp(np.linalg.eigvalsh(np.kron(np.eye(2), receiver) - state))
    radius = gap / (width + np.sqrt(width**2 + 2 * gap))
    print(f"primary spectral width: {width:.12f}, sufficient radius: {radius:.12f}")

    # Reproduce the recorded, fixed-decoder mean on the stored raw matrix.
    phase = -2.8871788591935865
    fe = (raw[0, 0].real + raw[3, 3].real + 2 * (raw[0, 3] * np.exp(-1j * phase)).real) / 2
    mean_fidelity = (2 * fe + 1) / 3
    p = 1.5 * (1 - mean_fidelity)
    dephasing = np.zeros((4, 4))
    dephasing[0, 0] = dephasing[3, 3] = 0.5
    dephasing[0, 3] = dephasing[3, 0] = 0.5 - p
    _, _, _, phase_margin = extension_test(dephasing)
    assert abs(phase_margin + 2 * (0.5 - p)**2) < 2e-14
    print(f"primary mean fidelity: {mean_fidelity:.15f}")
    print(f"matched phase-flip probability: {p:.15f}, extension margin: {phase_margin:.15f}")
    # Exact memoryless examples at the saved fidelity. The universal 1-to-2
    # cloner gives each output fidelity 5/6. Mix each with the same amount
    # of white noise and the two marginals still agree for every input.
    phase_capacity = 1 + p * np.log2(p) + (1 - p) * np.log2(1 - p)
    keep = (mean_fidelity - 0.5) / (5 / 6 - 0.5)
    assert 0 < p < 0.5 and 0 <= keep <= 1
    bell = np.array([1, 0, 0, 1]) / np.sqrt(2)
    mixed = np.eye(4) / 4
    clone = (2 * np.outer(bell, bell) + mixed) / 3
    noisy_clone = keep * clone + (1 - keep) * mixed
    for example in (dephasing, noisy_clone):
        fidelity = (2 * (bell @ example @ bell) + 1) / 3
        assert abs(fidelity - mean_fidelity) < 1e-14
        assert extension_test(example)[1] > 0
    assert extension_test(noisy_clone)[3] > 0
    print(f"matched phase-flip capacity: {phase_capacity:.9f} qubits/use")
    print(f"matched noisy-clone retention: {keep:.9f}; single-output capacity: 0")
    difference = matrices["18/anchor"][0] - matrices["18/cutoff"][0]
    cutoff_distance = np.linalg.norm(difference, ord="nuc") / 2
    print(f"original cutoff comparison: {cutoff_distance:.15f} > 0.005")
    if sys.argv[1:] == ["--exact"]:
        exact_checks()
    elif sys.argv[1:]:
        raise SystemExit("Usage: python3 shutter-check.py [--exact]")


# Original decimal entries from October 24 and 25, 2026. Basis labels above.
INPUTS = r'''{
  "4/shutter/d5": {
    "real": [
      [0.49948299737173496, 0.0, 0.0, 0.13609648091473237],
      [0.0, 0.0005170026283067043, 0.0016166101228702423, 0.0],
      [0.0, 0.0016166101228702423, 0.2529289086353547, 0.0],
      [0.13609648091473237, 0.0, 0.0, 0.24707109136436964]
    ],
    "imag": [
      [0.0, 0.0, 0.0, -0.25292946573145075],
      [0.0, 0.0, 0.0018372614305134306, 0.0],
      [0.0, -0.0018372614305134354, 0.0, 0.0],
      [0.2529294657314511, 0.0, 0.0, 0.0]
    ]
  },
  "4/open/d5": {
    "real": [
      [0.4993877493612799, 0.0, 0.0, 0.19879901830523675],
      [0.0, 0.0006122506391040596, 0.0028080909525108194, 0.0],
      [0.0, 0.0028080909525108194, 0.14307628612266177, 0.0],
      [0.19879901830523675, 0.0, 0.0, 0.3569237138771636]
    ],
    "imag": [
      [0.0, 0.0, 0.0, -0.37162211301094816],
      [0.0, 0.0, 0.007151197035044224, 0.0],
      [0.0, -0.0071511970350442424, 0.0, 0.0],
      [0.37162211301094933, 0.0, 0.0, 0.0]
    ]
  },
  "4/shutter/d4": {
    "real": [
      [0.49956136966242326, 0.0, 0.0, 0.13735091259904042],
      [0.0, 0.0004386303373221282, 0.0019062105091394673, 0.0],
      [0.0, 0.0019062105091394673, 0.2528109737775931, 0.0],
      [0.13735091259904042, 0.0, 0.0, 0.24718902622217548]
    ],
    "imag": [
      [0.0, 0.0, 0.0, -0.25224454001720936],
      [0.0, 0.0, 0.0007756532555037894, 0.0],
      [0.0, -0.0007756532555037885, 0.0, 0.0],
      [0.2522445400172091, 0.0, 0.0, 0.0]
    ]
  },
  "4/open/d4": {
    "real": [
      [0.4994406570694753, 0.0, 0.0, 0.20143668359347586],
      [0.0, 0.000559342930264443, 0.0038155906663062135, 0.0],
      [0.0, 0.0038155906663062135, 0.14318662644504287, 0.0],
      [0.20143668359347586, 0.0, 0.0, 0.35681337355475523]
    ],
    "imag": [
      [0.0, 0.0, 0.0, -0.3703119260529769],
      [0.0, 0.0, 0.005547264130285174, 0.0],
      [0.0, -0.005547264130285172, 0.0, 0.0],
      [0.3703119260529781, 0.0, 0.0, 0.0]
    ]
  },
  "18/combined": {
    "real": [
      [0.49864477981878913, 1.1852041768327766e-07, -2.707253335634006e-07, -0.31857925435333695],
      [1.185204176831789e-07, 0.0013591422571286676, -0.00034119197139485433, 2.662014809209851e-07],
      [-2.707253335633756e-07, -0.0003411919713948576, 0.27046871681523843, 2.1203205274337092e-07],
      [-0.31857925435333745, 2.6620148092099466e-07, 2.1203205274337783e-07, 0.22952736110885896]
    ],
    "imag": [
      [2.081668151835266e-17, -1.0531516223641178e-06, 7.804931289255749e-07, -0.082169367036351],
      [1.0531516223641297e-06, -7.047314121155779e-19, -0.0005867858615868805, -7.759808956161765e-07],
      [-7.804931289255422e-07, 0.0005867858615868905, -2.6346112824346845e-17, 3.8311759435384866e-08],
      [0.08216936703635032, 7.759808956161442e-07, -3.8311759435309546e-08, -9.71445146547012e-17]
    ]
  },
  "18/open": {
    "real": [
      [0.4985802753862592, 1.5965784492168228e-06, -3.943358526538181e-06, -0.33612900789392663],
      [1.5965784492165143e-06, 0.0014427062384175476, -0.001113410018433512, 3.8490749681146586e-06],
      [-3.943358526535252e-06, -0.0011134100184335056, 0.2565199026276912, -1.2755455472508892e-05],
      [-0.33612900789392636, 3.849074968115517e-06, -1.2755455472510398e-05, 0.24345711574763276]
    ],
    "imag": [
      [6.938905663171807e-18, 4.772775844744791e-06, 2.455548951033578e-06, -0.08583577664086978],
      [-4.772775844743905e-06, 0.0, 0.0008431775979221384, -2.6421911506848627e-06],
      [-2.45554895103333e-06, -0.0008431775979221361, 7.806208567169653e-18, -1.7337475780145506e-05],
      [0.08583577664086989, 2.6421911506837684e-06, 1.7337475780145045e-05, -2.7755575615628914e-17]
    ]
  },
  "18/anchor": {
    "real": [
      [0.4986602751743998, 3.130402842477443e-06, -1.3321798511880458e-06, -0.3185168702375958],
      [3.130402842477426e-06, 0.0013585115002571623, -0.00031086825776868076, 1.441051940665572e-06],
      [-1.332179851188378e-06, -0.0003108682577686808, 0.2704718797087281, -9.694078686374137e-06],
      [-0.31851687023759634, 1.4410519406654837e-06, -9.694078686373978e-06, 0.22950933361660894]
    ],
    "imag": [
      [-2.081668223742232e-17, -2.9237278473390656e-06, 2.7881521643927073e-06, -0.08228631327444832],
      [2.9237278473390236e-06, -1.5246593050577406e-18, -0.0004998770330215781, -2.8762579062593597e-06],
      [-2.788152164392689e-06, 0.0004998770330215673, -1.6479871660405302e-17, 2.668349828576348e-06],
      [0.08228631327444903, 2.8762579062597137e-06, -2.6683498285762427e-06, -1.3877787807814457e-17]
    ]
  },
  "18/bond": {
    "real": [
      [0.498649824693924, 4.3103659535467626e-07, 7.917752300039282e-07, -0.31855794503129087],
      [4.3103659535459675e-07, 0.0013568382067973765, -0.00034744333459868785, -8.04102482722197e-07],
      [7.917752300041107e-07, -0.00034744333459869653, 0.27046737250463393, 3.007731750889048e-08],
      [-0.31855794503128954, -8.041024827221964e-07, 3.007731750893924e-08, 0.22952596459465383]
    ],
    "imag": [
      [-1.9081958048384768e-17, 1.811623642430119e-06, -3.4161287686758615e-07, -0.08227268780303583],
      [-1.8116236424301063e-06, -1.6263032587282567e-19, -0.0005927917899302068, 3.3925264997090987e-07],
      [3.416128768675048e-07, 0.000592791789930188, 1.2576745036242583e-17, -4.696485285866587e-07],
      [0.0822726878030355, -3.3925264997095455e-07, 4.696485285867089e-07, 0.0]
    ]
  },
  "18/step": {
    "real": [
      [0.49864750394212737, 2.428875521524772e-06, -1.0502290577396382e-06, -0.31852310188874206],
      [2.4288755215253317e-06, 0.0013634493630936713, -0.0003019482770811117, 1.1002053012206234e-06],
      [-1.0502290577394777e-06, -0.0003019482770811094, 0.2704775361397713, -5.373556171738947e-06],
      [-0.3185231018887421, 1.1002053012206107e-06, -5.373556171738783e-06, 0.22951151055501506]
    ],
    "imag": [
      [-1.7347246612051328e-18, -8.054687721750319e-06, 4.191734441224413e-06, -0.08219948007503362],
      [8.054687721750285e-06, -2.710505431213761e-19, -0.0005073118758028754, -4.234322450981402e-06],
      [-4.191734441224261e-06, 0.0005073118758028677, 1.1275700169266659e-17, 9.011661805100463e-06],
      [0.08219948007503308, 4.234322450981254e-06, -9.011661805100853e-06, -1.3877787807814457e-17]
    ]
  },
  "18/cutoff": {
    "real": [
      [0.4986512022754123, -9.478285015647337e-06, -3.5859735917141712e-06, -0.31964831228310414],
      [-9.478285015647364e-06, 0.0013669208916194337, -0.00033073044703115786, 3.533466212993159e-06],
      [-3.5859735917138744e-06, -0.00033073044703115114, 0.270533138030966, 2.144494579432918e-06],
      [-0.3196483122831036, 3.533466212993442e-06, 2.14449457943282e-06, 0.22944873880199068]
    ],
    "imag": [
      [-6.938894057339784e-18, 8.322603999198486e-06, -4.384378419501709e-06, -0.07732766504834725],
      [-8.322603999198542e-06, -4.336808689942018e-19, -0.0004623838581753246, 4.212240525909674e-06],
      [4.384378419501469e-06, 0.00046238385817532515, 2.949029784055841e-17, 4.359623655971984e-06],
      [0.07732766504834711, -4.212240525909215e-06, -4.359623655972251e-06, -6.938893903907228e-17]
    ]
  }
}'''


if __name__ == "__main__":
    main()
