File size: 18,720 Bytes
1f85192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env python3
"""Finite SDP checks for minimax recovery of complex Schur channels.

These floating-point checks supplement proofs and do not prove a universal
theorem or certify novelty. Primal, dual, and direct diamond SDPs are solved
independently. Rounded primal/dual witnesses are checked by eigenvalues; these
are numerical residual checks, not interval-arithmetic certificates.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import cvxpy as cp
import numpy as np


SEED = 20261103
TOLERANCE = 3e-6
SOLVER_STATUS_COUNTS: dict[str, int] = {}


def hermitian(matrix: np.ndarray) -> np.ndarray:
    return (matrix + matrix.conj().T) / 2


def minimum_eigenvalue(matrix: np.ndarray) -> float:
    return float(np.linalg.eigvalsh(hermitian(matrix))[0])


def solve(problem: cp.Problem) -> float:
    value = problem.solve(solver="CLARABEL", tol_gap_abs=2e-9,
                          tol_gap_rel=2e-9, tol_feas=2e-9, max_iter=250)
    assert problem.status in (cp.OPTIMAL, cp.OPTIMAL_INACCURATE), problem.status
    SOLVER_STATUS_COUNTS[problem.status] = SOLVER_STATUS_COUNTS.get(problem.status, 0) + 1
    return float(np.real(value))


def correlation_kraus(correlation: np.ndarray) -> list[np.ndarray]:
    eigenvalues, eigenvectors = np.linalg.eigh(hermitian(correlation))
    coefficients = (eigenvectors * np.sqrt(np.maximum(eigenvalues, 0.0))).T
    kraus = [np.diag(row) for row in coefficients]
    assert np.linalg.norm(sum(k.conj().T @ k for k in kraus)
                          - np.eye(len(correlation))) < 1e-9
    reconstructed = sum(np.diag(k)[:, None] * np.diag(k).conj()[None, :]
                        for k in kraus)
    assert np.linalg.norm(reconstructed - correlation) < 1e-9
    return kraus


def round_correlation(matrix: np.ndarray, ridge: float = 1e-7) -> np.ndarray:
    eigenvalues, eigenvectors = np.linalg.eigh(hermitian(matrix))
    positive = (eigenvectors * np.maximum(eigenvalues, 0.0)) @ eigenvectors.conj().T
    diagonal = np.sqrt(np.maximum(np.real(np.diag(positive)), 1e-15))
    positive = positive / diagonal[:, None] / diagonal[None, :]
    return hermitian((1 - ridge) * positive + ridge * np.eye(len(matrix)))


def solve_state_cap(correlation: np.ndarray) -> dict:
    """Independently solve the rank-sized state cap, dual, and packing SDPs."""
    dimension = len(correlation)
    eigenvalues, eigenvectors = np.linalg.eigh(hermitian(correlation))
    active = eigenvalues > 1e-9
    vectors = np.sqrt(eigenvalues[active])[:, None] * eigenvectors[:, active].conj().T
    assert np.linalg.norm(vectors.conj().T @ vectors - correlation) < 1e-8
    rank = len(vectors)
    projectors = [np.outer(vectors[:, i], vectors[:, i].conj())
                  for i in range(dimension)]
    sigma = cp.Variable((rank, rank), hermitian=True)
    t = cp.Variable()
    state = cp.Problem(cp.Maximize(t),
                       [sigma >> 0, cp.trace(sigma) == 1]
                       + [cp.real(cp.trace(sigma @ pi)) >= t for pi in projectors])
    state_value = solve(state)
    q = cp.Variable(dimension)
    z = cp.Variable()
    mixture = sum(q[i] * projectors[i] for i in range(dimension))
    dual = cp.Problem(cp.Minimize(z),
                      [q >= 0, cp.sum(q) == 1, z * np.eye(rank) - mixture >> 0])
    state_dual = solve(dual)
    weights = cp.Variable(dimension)
    packing = cp.Problem(cp.Maximize(cp.sum(weights)),
                         [weights >= 0, np.eye(rank)
                          - sum(weights[i] * projectors[i] for i in range(dimension)) >> 0])
    packing_value = solve(packing)
    assert abs(state_value - state_dual) < TOLERANCE
    assert abs(packing_value - 1 / state_value) < 5 * TOLERANCE
    sigma_eigenvalues, sigma_eigenvectors = np.linalg.eigh(hermitian(sigma.value))
    sigma_rounded = ((sigma_eigenvectors * np.maximum(sigma_eigenvalues, 0))
                     @ sigma_eigenvectors.conj().T)
    sigma_rounded /= np.trace(sigma_rounded).real
    m = hermitian(vectors.conj().T @ sigma_rounded @ vectors)
    f = np.real(np.diag(m))
    lower = float(np.min(f)) * (1 - 1e-9)
    assert lower > 0
    explicit_a = lower * m.conj() / f[:, None] / f[None, :]
    explicit_a += np.diag(1 - lower / f)
    psd_violation = max(0.0, -minimum_eigenvalue(explicit_a),
                        -minimum_eigenvalue(correlation * explicit_a
                                            - lower * np.ones((dimension, dimension))))
    assert psd_violation < 1e-8
    assert np.max(np.abs(np.diag(explicit_a) - 1)) < 1e-9
    assert abs(state_value - lower) < TOLERANCE
    return {
        "state_cap_rank": rank, "state_cap_value": state_value,
        "state_cap_dual_value": state_dual,
        "state_cap_duality_gap": abs(state_value - state_dual),
        "packing_value": packing_value,
        "packing_reciprocity_error": abs(packing_value - 1 / state_value),
        "explicit_decoder_lower_value": lower,
        "explicit_decoder_value_gap": abs(state_value - lower),
        "explicit_decoder_psd_violation": psd_violation,
    }


def solve_recovery(correlation: np.ndarray) -> dict:
    dimension = len(correlation)
    ones = np.ones((dimension, dimension))
    a = cp.Variable((dimension, dimension), hermitian=True)
    lam = cp.Variable()
    primal = cp.Problem(cp.Maximize(lam),
                        [a >> 0, cp.diag(a) == 1,
                         cp.multiply(correlation, a) - lam * ones >> 0])
    value = solve(primal)
    a_value = hermitian(a.value)
    z = cp.Variable((dimension, dimension), hermitian=True)
    y = cp.Variable(dimension)
    dual = cp.Problem(cp.Minimize(cp.sum(y)),
                      [z >> 0, cp.real(cp.sum(z)) == 1,
                       cp.diag(y) - cp.multiply(correlation.conj(), z) >> 0])
    dual_value = solve(dual)
    z_value = hermitian(z.value)
    y_value = np.asarray(y.value, dtype=float)
    direct_a = cp.Variable((dimension, dimension), hermitian=True)
    direct_y = cp.Variable((dimension, dimension), hermitian=True)
    s = cp.Variable()
    direct = cp.Problem(cp.Minimize(2 * s),
                        [direct_a >> 0, cp.diag(direct_a) == 1,
                         direct_y >> 0,
                         direct_y + cp.multiply(correlation, direct_a) - ones >> 0,
                         cp.real(cp.diag(direct_y)) <= s])
    direct_value = solve(direct)
    assert abs(dual_value - value) < TOLERANCE
    assert abs(direct_value - 2 * (1 - value)) < TOLERANCE
    raw_violations = [
        max(0.0, -minimum_eigenvalue(a_value)),
        max(0.0, -minimum_eigenvalue(correlation * a_value - value * ones)),
        max(0.0, -minimum_eigenvalue(z_value)),
        max(0.0, -minimum_eigenvalue(np.diag(y_value) - correlation.conj() * z_value)),
    ]
    assert max(raw_violations) < TOLERANCE
    a_rounded = round_correlation(a_value)
    b_rounded = hermitian(correlation * a_rounded)
    # The ridge in A makes C o A positive definite, so this expression is stable.
    inverse_quadratic = float(np.real(np.ones(dimension) @ np.linalg.solve(
        b_rounded, np.ones(dimension))))
    rounded_lower = (1 - 1e-8) / inverse_quadratic
    rounded_primal_violation = max(0.0, -minimum_eigenvalue(
        b_rounded - rounded_lower * ones))
    z_eigenvalues, z_eigenvectors = np.linalg.eigh(z_value)
    z_rounded = (z_eigenvectors * np.maximum(z_eigenvalues, 0)) @ z_eigenvectors.conj().T
    z_rounded /= float(np.real(np.sum(z_rounded)))
    dual_slack = hermitian(np.diag(y_value) - correlation.conj() * z_rounded)
    y_rounded = y_value + max(0.0, -minimum_eigenvalue(dual_slack)) + 1e-8
    rounded_upper = float(np.sum(y_rounded))
    rounded_dual_violation = max(0.0, -minimum_eigenvalue(
        np.diag(y_rounded) - correlation.conj() * z_rounded))
    assert rounded_lower <= rounded_upper + TOLERANCE
    assert rounded_upper - rounded_lower < 5e-6
    assert rounded_primal_violation < 1e-9
    assert rounded_dual_violation < 1e-9
    recovery_kraus = correlation_kraus(a_rounded)
    noise_kraus = correlation_kraus(correlation)
    product_kraus = [r @ e for r in recovery_kraus for e in noise_kraus]
    gaussian = np.arange(1, dimension * dimension + 1).reshape(dimension, dimension)
    rho = gaussian @ gaussian.T
    rho = rho / np.trace(rho)
    recovered = sum(k @ rho @ k.conj().T for k in product_kraus)
    kraus_composition_error = float(np.linalg.norm(recovered - b_rounded * rho))
    assert kraus_composition_error < 1e-9
    state_cap = solve_state_cap(correlation)
    assert abs(state_cap["state_cap_value"] - value) < TOLERANCE
    return {
        "dimension": dimension, "primal_value": value, "dual_value": dual_value,
        "primal_dual_gap": abs(dual_value - value),
        "direct_diamond_value": direct_value,
        "diamond_formula_error": abs(direct_value - 2 * (1 - value)),
        "largest_raw_psd_violation": max(raw_violations),
        "rounded_primal_lower": float(rounded_lower),
        "rounded_dual_upper": rounded_upper,
        "rounded_gap": rounded_upper - rounded_lower,
        "rounded_primal_psd_violation": rounded_primal_violation,
        "rounded_dual_psd_violation": rounded_dual_violation,
        "kraus_composition_error": kraus_composition_error,
        "state_cap_hadamard_value_error": abs(state_cap["state_cap_value"] - value),
        **state_cap,
        "a_rounded": a_rounded,
    }


def random_correlation(dimension: int, rank: int,
                       rng: np.random.Generator, positive: bool = False) -> np.ndarray:
    coefficients = rng.uniform(0.05, 1, (rank, dimension)) if positive else (
        rng.normal(size=(rank, dimension)) + 1j * rng.normal(size=(rank, dimension)))
    coefficients /= np.linalg.norm(coefficients, axis=0, keepdims=True)
    return hermitian(coefficients.T @ coefficients.conj())


def nonnegative_minimum(correlation: np.ndarray) -> float:
    dimension = len(correlation)
    q = cp.Variable(dimension)
    return solve(cp.Problem(cp.Minimize(cp.quad_form(q, cp.psd_wrap(correlation.real))),
                            [q >= 0, cp.sum(q) == 1]))


def minimum_entanglement_fidelity(kraus: list[np.ndarray], dimension: int) -> float:
    rho = cp.Variable((dimension, dimension), hermitian=True)
    objective = sum(cp.square(cp.abs(cp.trace(rho @ k))) for k in kraus)
    return solve(cp.Problem(cp.Minimize(objective), [rho >> 0, cp.trace(rho) == 1]))


def run_checks() -> dict:
    SOLVER_STATUS_COUNTS.clear()
    rng = np.random.default_rng(SEED)
    checks = []
    examples = []
    for d in (2, 3, 4, 5):
        phases = np.exp(1j * rng.uniform(-np.pi, np.pi, d))
        examples.append((f"phase_unitary_{d}", np.outer(phases, phases.conj()), 1.0))
    for d in (2, 3, 4, 5):
        examples.append((f"complete_dephasing_{d}", np.eye(d), 1 / d))
    nonnegative_examples = []
    for repetition in range(4):
        d = 2 + repetition
        correlation = random_correlation(d, 3, rng, positive=True)
        nonnegative_examples.append(correlation)
        examples.append((f"nonnegative_{d}", correlation, nonnegative_minimum(correlation)))
    for repetition, base in enumerate(nonnegative_examples):
        phases = np.exp(1j * rng.uniform(-np.pi, np.pi, len(base)))
        correlation = np.outer(phases, phases.conj()) * base
        examples.append((f"gauge_positive_{repetition}", correlation, nonnegative_minimum(base)))
    random_examples = []
    for repetition in range(8):
        d = 2 + repetition % 4
        correlation = random_correlation(d, 2 + repetition % 3, rng)
        random_examples.append(correlation)
        examples.append((f"random_complex_{repetition}", correlation, None))
    s = 1 / np.sqrt(3)
    g = np.array([[1, s, s, s], [s, 1, 1j * s, -1j * s],
                  [s, -1j * s, 1, 1j * s], [s, 1j * s, -1j * s, 1]], dtype=complex)
    assert np.linalg.norm(g @ g - 2 * g) < 1e-12
    for t in (0.0, 0.2, 0.65, 1.0):
        correlation = (1 - t) * np.eye(4) + t * g.conj()
        expected = (1 + t) / 4
        z = np.ones((4, 4)) / 16
        y = np.full(4, (1 + t) / 16)
        assert minimum_eigenvalue(correlation * g - expected * np.ones((4, 4))) > -1e-12
        assert minimum_eigenvalue(np.diag(y) - correlation.conj() * z) > -1e-12
        examples.append((f"sic_analytic_t_{t}", correlation, expected))
    frame_dimension, frame_rank = 5, 2
    harmonic_vectors = np.exp(2j * np.pi * np.arange(frame_rank)[:, None]
                              * np.arange(frame_dimension)[None, :] / frame_dimension)
    harmonic_vectors /= np.sqrt(frame_rank)
    frame_correlation = harmonic_vectors.conj().T @ harmonic_vectors
    assert np.linalg.norm(frame_correlation @ frame_correlation
                          - (frame_dimension / frame_rank) * frame_correlation) < 1e-12
    for t in (0.0, 0.35, 1.0):
        correlation = (1 - t) * np.eye(frame_dimension) + t * frame_correlation
        expected = (1 - t) / frame_dimension + t / frame_rank
        assert minimum_eigenvalue(correlation * frame_correlation.conj()
                                  - expected * np.ones((frame_dimension, frame_dimension))) > -1e-12
        examples.append((f"harmonic_tight_frame_t_{t}", correlation, expected))
    solved = {}
    for name, correlation, expected in examples:
        result = solve_recovery(correlation)
        a = result.pop("a_rounded")
        if expected is not None:
            result["analytic_value"] = expected
            result["analytic_value_error"] = abs(result["primal_value"] - expected)
            assert result["analytic_value_error"] < TOLERANCE
        checks.append({"kind": "independent_primal_dual_direct_sdp", "name": name, **result})
        solved[name] = (correlation, result, a)
    for repetition, indices in enumerate(((0, 1), (0, 2), (1, 2))):
        c = random_examples[indices[0]]
        d = random_examples[indices[1]]
        left = solve_recovery(c)
        right = solve_recovery(d)
        joint = solve_recovery(np.kron(c, d))
        expected = left["primal_value"] * right["primal_value"]
        error = abs(joint["primal_value"] - expected)
        assert error < TOLERANCE
        checks.append({"kind": "complex_tensorization", "dimensions": [len(c), len(d)],
                       "joint_value": joint["primal_value"], "product_value": expected,
                       "tensorization_error": error,
                       "primal_dual_gap": joint["primal_dual_gap"],
                       "largest_raw_psd_violation": joint["largest_raw_psd_violation"],
                       "diamond_formula_error": joint["diamond_formula_error"]})
    for repetition in range(4):
        correlation = random_examples[repetition]
        dimension = len(correlation)
        optimal = solved[f"random_complex_{repetition}"][1]["dual_value"]
        gaussian = rng.normal(size=(3 * dimension, dimension))
        gaussian = gaussian + 1j * rng.normal(size=gaussian.shape)
        isometry, _ = np.linalg.qr(gaussian, mode="reduced")
        recovery = [isometry[i * dimension:(i + 1) * dimension] for i in range(3)]
        noise = correlation_kraus(correlation)
        composed = [r @ e for r in recovery for e in noise]
        fidelity = minimum_entanglement_fidelity(composed, dimension)
        assert fidelity <= optimal + TOLERANCE
        checks.append({"kind": "arbitrary_cptp_recovery_worst_fidelity_upper_check",
                       "dimension": dimension, "random_recovery_worst_fidelity": fidelity,
                       "optimal_recovery_upper": optimal,
                       "fidelity_upper_violation": max(0.0, fidelity - optimal)})
    for repetition in range(4):
        correlation, values, rounded_a = solved[f"random_complex_{repetition}"]
        recovered_kraus = correlation_kraus(correlation * rounded_a)
        fidelity = minimum_entanglement_fidelity(recovered_kraus, len(correlation))
        error = abs(fidelity - values["primal_value"])
        assert error < TOLERANCE
        checks.append({"kind": "optimal_recovery_worst_fidelity_equality",
                       "dimension": len(correlation), "optimized_worst_fidelity": fidelity,
                       "sdp_value": values["primal_value"], "fidelity_equality_error": error})
    phase = np.array([1, 1j])
    correlation = np.outer(phase, phase.conj())
    corrected = correlation * correlation.conj()
    assert np.linalg.norm(corrected - np.ones((2, 2))) < 1e-12
    checks.append({"kind": "phase_unitary_recovery_contrast",
                   "uncorrected_diamond_error": float(np.sqrt(2)),
                   "optimal_corrected_diamond_error": 0.0,
                   "recovered_correlation_residual": float(np.linalg.norm(corrected - 1))})
    return {
        "label": "Finite floating-point SDP checks; not a universal proof or novelty certificate.",
        "seed": SEED, "numpy_version": np.__version__, "cvxpy_version": cp.__version__,
        "solver": "CLARABEL", "tolerance": TOLERANCE,
        "solver_status_counts": dict(SOLVER_STATUS_COUNTS),
        "all_checks_passed": True, "check_count": len(checks),
        "maximum_primal_dual_gap": max(x.get("primal_dual_gap", 0) for x in checks),
        "maximum_direct_diamond_formula_error": max(x.get("diamond_formula_error", 0) for x in checks),
        "maximum_raw_psd_violation": max(x.get("largest_raw_psd_violation", 0) for x in checks),
        "maximum_rounded_primal_dual_gap": max(x.get("rounded_gap", 0) for x in checks),
        "maximum_analytic_value_error": max(x.get("analytic_value_error", 0) for x in checks),
        "maximum_complex_tensorization_error": max(x.get("tensorization_error", 0) for x in checks),
        "maximum_optimal_recovery_fidelity_error": max(x.get("fidelity_equality_error", 0) for x in checks),
        "maximum_state_cap_hadamard_value_error": max(x.get("state_cap_hadamard_value_error", 0) for x in checks),
        "maximum_state_cap_duality_gap": max(x.get("state_cap_duality_gap", 0) for x in checks),
        "maximum_packing_reciprocity_error": max(x.get("packing_reciprocity_error", 0) for x in checks),
        "maximum_explicit_decoder_psd_violation": max(x.get("explicit_decoder_psd_violation", 0) for x in checks),
        "checks": checks,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path,
                        default=Path(__file__).with_name("complex_recovery_results.json"))
    arguments = parser.parse_args()
    result = run_checks()
    arguments.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({key: value for key, value in result.items() if key != "checks"}, indent=2))


if __name__ == "__main__":
    main()