stabcert 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. hayden_preskill_toy/__init__.py +1 -0
  2. hayden_preskill_toy/channels.py +137 -0
  3. hayden_preskill_toy/dense_free_pipeline.py +128 -0
  4. hayden_preskill_toy/experiment.py +242 -0
  5. hayden_preskill_toy/gf2.py +244 -0
  6. hayden_preskill_toy/layout.py +50 -0
  7. hayden_preskill_toy/local.py +99 -0
  8. hayden_preskill_toy/parametric_architecture_routing.py +328 -0
  9. hayden_preskill_toy/parametric_certificate.py +380 -0
  10. hayden_preskill_toy/parametric_channels.py +106 -0
  11. hayden_preskill_toy/parametric_chi_correlations.py +153 -0
  12. hayden_preskill_toy/parametric_graph_routing.py +224 -0
  13. hayden_preskill_toy/parametric_petz.py +86 -0
  14. hayden_preskill_toy/parametric_petz_stabilizer.py +130 -0
  15. hayden_preskill_toy/parametric_routing.py +95 -0
  16. hayden_preskill_toy/parametric_stabilizer.py +52 -0
  17. hayden_preskill_toy/parametric_synthesis.py +185 -0
  18. hayden_preskill_toy/parametric_validation.py +103 -0
  19. hayden_preskill_toy/recovery_adversarial.py +668 -0
  20. hayden_preskill_toy/recovery_artifact.py +163 -0
  21. hayden_preskill_toy/recovery_cli.py +353 -0
  22. hayden_preskill_toy/recovery_compile.py +370 -0
  23. hayden_preskill_toy/recovery_exit_codes.py +13 -0
  24. hayden_preskill_toy/recovery_hayden_preskill_adapter.py +94 -0
  25. hayden_preskill_toy/recovery_problem.py +208 -0
  26. hayden_preskill_toy/recovery_pytket.py +188 -0
  27. hayden_preskill_toy/recovery_routing.py +230 -0
  28. hayden_preskill_toy/recovery_run_report.py +94 -0
  29. hayden_preskill_toy/recovery_sabre.py +206 -0
  30. hayden_preskill_toy/recovery_serialization.py +337 -0
  31. hayden_preskill_toy/recovery_stabilizer.py +478 -0
  32. hayden_preskill_toy/recovery_verifier_cli.py +178 -0
  33. hayden_preskill_toy/recovery_verify.py +484 -0
  34. hayden_preskill_toy/simulator.py +77 -0
  35. hayden_preskill_toy/stabilizer.py +133 -0
  36. hayden_preskill_toy/support_code.py +279 -0
  37. stabcert-0.1.0.data/data/share/stabcert/schemas/recovery_artifact.schema.json +85 -0
  38. stabcert-0.1.0.data/data/share/stabcert/schemas/recovery_problem.schema.json +111 -0
  39. stabcert-0.1.0.data/data/share/stabcert/schemas/recovery_run_report.schema.json +52 -0
  40. stabcert-0.1.0.dist-info/METADATA +138 -0
  41. stabcert-0.1.0.dist-info/RECORD +45 -0
  42. stabcert-0.1.0.dist-info/WHEEL +5 -0
  43. stabcert-0.1.0.dist-info/entry_points.txt +2 -0
  44. stabcert-0.1.0.dist-info/licenses/LICENSE +202 -0
  45. stabcert-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1 @@
1
+ """Exact finite-size Clifford-channel toy model; not a black-hole simulation."""
@@ -0,0 +1,137 @@
1
+ """Exact channel, decoupling, and Petz-recovery calculations for the toy model."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ import numpy as np
6
+
7
+ from .simulator import Gate, X, apply_1q, apply_circuit, bell_pair, zero_state
8
+ from .experiment import A, B, E, N_QUBITS, R, SCRAMBLED
9
+
10
+ PINV_RELATIVE_CUTOFF = 1e-12
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ChannelData:
15
+ kraus: tuple[np.ndarray, ...]
16
+ output: tuple[int, ...]
17
+ complement: tuple[int, ...]
18
+
19
+
20
+ def environment_state() -> np.ndarray:
21
+ """|0>_R |0>_A and the fixed pure B--E environment."""
22
+ state = zero_state(N_QUBITS)
23
+ for b, e in zip(B, E):
24
+ state = bell_pair(state, b, e, N_QUBITS)
25
+ return state
26
+
27
+
28
+ def channel_at_time(scrambler: list[Gate], t: int) -> ChannelData:
29
+ """Kraus representation of N_t: A -> E+D(t), with C(t) traced out."""
30
+ output = (*E, *SCRAMBLED[:t])
31
+ complement = SCRAMBLED[t:]
32
+ states = []
33
+ base = environment_state()
34
+ for bit in range(2):
35
+ source = base if bit == 0 else apply_1q(base, X, A, N_QUBITS)
36
+ states.append(apply_circuit(source, scrambler, N_QUBITS))
37
+ matrices = []
38
+ for state in states:
39
+ tensor = state.reshape((2,) * N_QUBITS)[0] # R is fixed to |0> for the channel.
40
+ axes = tuple(q - 1 for q in (*output, *complement))
41
+ matrices.append(np.transpose(tensor, axes).reshape(2**len(output), 2**len(complement)))
42
+ kraus = tuple(np.stack([mat[:, c] for mat in matrices], axis=1) for c in range(2**len(complement)))
43
+ return ChannelData(kraus, output, complement)
44
+
45
+
46
+ def reduced_density(state: np.ndarray, keep: tuple[int, ...], n: int = N_QUBITS) -> np.ndarray:
47
+ rest = tuple(q for q in range(n) if q not in keep)
48
+ view = np.transpose(state.reshape((2,) * n), (*keep, *rest)).reshape(2**len(keep), -1)
49
+ return view @ view.conj().T
50
+
51
+
52
+ def entropy(rho: np.ndarray) -> float:
53
+ vals = np.linalg.eigvalsh((rho + rho.conj().T) / 2)
54
+ vals = vals[vals > 1e-14]
55
+ return float(-np.sum(vals * np.log2(vals)))
56
+
57
+
58
+ def trace_distance(rho: np.ndarray, sigma: np.ndarray) -> float:
59
+ vals = np.linalg.eigvalsh((rho - sigma + (rho - sigma).conj().T) / 2)
60
+ return float(.5 * np.sum(np.abs(vals)))
61
+
62
+
63
+ def inverse_fractional_power(rho: np.ndarray, power: float, relative_cutoff: float = PINV_RELATIVE_CUTOFF) -> np.ndarray:
64
+ """Moore--Penrose rho**power on supp(rho); zero on its kernel."""
65
+ vals, vectors = np.linalg.eigh((rho + rho.conj().T) / 2)
66
+ cutoff = relative_cutoff * max(float(vals.max()), 1.0)
67
+ keep = vals > cutoff
68
+ return (vectors[:, keep] * vals[keep] ** power) @ vectors[:, keep].conj().T
69
+
70
+
71
+ def conditional_collision_entropy(rho_rc: np.ndarray, rho_c: np.ndarray, relative_cutoff: float = PINV_RELATIVE_CUTOFF) -> float:
72
+ """Sandwiched conditional collision entropy.
73
+
74
+ H_2(R|C)=-log2 Tr[(I_R⊗rho_C^-1/4 rho_RC I_R⊗rho_C^-1/4)^2].
75
+ The inverse is the Moore--Penrose inverse restricted to supp(rho_C).
76
+ """
77
+ dim_c = rho_c.shape[0]; dim_r = rho_rc.shape[0] // dim_c
78
+ factor = np.kron(np.eye(dim_r), inverse_fractional_power(rho_c, -.25, relative_cutoff))
79
+ sandwiched = factor @ rho_rc @ factor
80
+ collision = float(np.real(np.trace(sandwiched @ sandwiched)))
81
+ return float(-np.log2(collision))
82
+
83
+
84
+ def decoupling_metrics(scrambled_state: np.ndarray, t: int, include_early_radiation: bool) -> dict[str, float]:
85
+ """For E+D access use C; for D-only access use E+C as the inaccessible complement."""
86
+ complement = SCRAMBLED[t:]
87
+ inaccessible = complement if include_early_radiation else (*E, *complement)
88
+ rho_rc = reduced_density(scrambled_state, (R, *inaccessible))
89
+ rho_r = reduced_density(scrambled_state, (R,))
90
+ rho_c = reduced_density(scrambled_state, inaccessible) if inaccessible else np.ones((1, 1), complex)
91
+ mutual = entropy(rho_r) + entropy(rho_c) - entropy(rho_rc)
92
+ product = np.kron(rho_r, rho_c)
93
+ h2 = conditional_collision_entropy(rho_rc, rho_c)
94
+ eig_rc = np.linalg.eigvalsh((rho_rc + rho_rc.conj().T) / 2); eig_c = np.linalg.eigvalsh((rho_c + rho_c.conj().T) / 2)
95
+ nonzero_rc = eig_rc[eig_rc > 1e-12]; nonzero_c = eig_c[eig_c > 1e-12]
96
+ return {"mutual_information_bits": max(0.0, mutual), "trace_distance_product": trace_distance(rho_rc, product),
97
+ "conditional_collision_entropy_bits": h2, "rank_rho_RC": int(len(nonzero_rc)), "rank_rho_C": int(len(nonzero_c)),
98
+ "spectrum_rho_RC": ";".join(f"{x:.12g}" for x in nonzero_rc), "spectrum_rho_C": ";".join(f"{x:.12g}" for x in nonzero_c)}
99
+
100
+
101
+ def channel_validation(channel: ChannelData) -> dict[str, float | bool]:
102
+ complete = sum((k.conj().T @ k for k in channel.kraus), start=np.zeros((2, 2), complex))
103
+ # Complete positivity is constructive: rho -> sum_j K_j rho K_j^dagger.
104
+ return {"cp_by_kraus": True, "trace_preservation_error": float(np.linalg.norm(complete - np.eye(2))),
105
+ "minimum_completeness_eigenvalue": float(np.linalg.eigvalsh(complete).min())}
106
+
107
+
108
+ def apply_channel(channel: ChannelData, rho: np.ndarray) -> np.ndarray:
109
+ return sum((k @ rho @ k.conj().T for k in channel.kraus), start=np.zeros((2**len(channel.output),) * 2, complex))
110
+
111
+
112
+ def petz_recovery(channel: ChannelData, relative_cutoff: float = PINV_RELATIVE_CUTOFF) -> tuple[tuple[np.ndarray, ...], dict[str, float]]:
113
+ """Transpose/Petz channel for sigma=I/2, using only the support of N(sigma)."""
114
+ stacked = np.concatenate(channel.kraus, axis=1) / np.sqrt(2)
115
+ u, s, _ = np.linalg.svd(stacked, full_matrices=False)
116
+ cutoff = relative_cutoff * (s[0] if len(s) else 1.0)
117
+ kept = s > cutoff
118
+ support = u[:, kept]
119
+ invsqrt = (support / s[kept]) @ support.conj().T
120
+ recovery = tuple((k.conj().T @ invsqrt) / np.sqrt(2) for k in channel.kraus)
121
+ support_projector = support @ support.conj().T
122
+ recovered_identity = sum((r.conj().T @ r for r in recovery), start=np.zeros_like(support_projector))
123
+ return recovery, {"support_dimension": int(kept.sum()), "support_cutoff": float(cutoff),
124
+ "output_dimension": int(2**len(channel.output)), "choi_dimension": int(2 * 2**len(channel.output)),
125
+ "support_trace_preservation_error": float(np.linalg.norm(recovered_identity - support_projector))}
126
+
127
+
128
+ def petz_entanglement_fidelity(channel: ChannelData) -> tuple[float, dict[str, float]]:
129
+ recovery, info = petz_recovery(channel)
130
+ fidelity = 0.0
131
+ # (I_R \otimes R o N)(Phi): each composite Kraus is L_j K_i.
132
+ bell = np.array([1, 0, 0, 1], dtype=complex) / np.sqrt(2)
133
+ for k in channel.kraus:
134
+ for r in recovery:
135
+ op = r @ k
136
+ fidelity += abs(np.vdot(bell, np.kron(np.eye(2), op) @ bell)) ** 2
137
+ return float(np.real(fidelity)), info
@@ -0,0 +1,128 @@
1
+ """End-to-end pure-Clifford Petz pipeline with no dense quantum state objects."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ import time
6
+
7
+ import stim
8
+
9
+ from .layout import SystemLayout
10
+ from .parametric_certificate import (
11
+ canonical_signed_stabilizer_signature,
12
+ certify_routed_equivalence,
13
+ structural_validation,
14
+ )
15
+ from .parametric_petz_stabilizer import stabilizer_channel_at_time
16
+ from .parametric_routing import route_line, two_qubit_depth
17
+ from .parametric_synthesis import signed_dilation
18
+ from .simulator import Gate
19
+ from .stabilizer import pure_stabilizer_decoupling
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class DenseFreeResult:
24
+ metrics: dict[str, object]
25
+ gates: tuple[Gate, ...]
26
+ routed_gates: tuple[Gate, ...]
27
+
28
+
29
+ def structural_timeline(
30
+ layout: SystemLayout, scrambler: list[Gate] | tuple[Gate, ...]
31
+ ) -> list[dict[str, object]]:
32
+ rows = []
33
+ for t in range(len(layout.scrambled) + 1):
34
+ started = time.perf_counter()
35
+ channel = stabilizer_channel_at_time(layout, scrambler, t)
36
+ decoupling = pure_stabilizer_decoupling(
37
+ list(scrambler),
38
+ layout.n_qubits,
39
+ layout.R_register,
40
+ layout.A_register,
41
+ layout.B,
42
+ layout.E,
43
+ t,
44
+ )
45
+ support = channel.tau_support
46
+ rows.append(
47
+ {
48
+ "t": t,
49
+ "mutual_information_R_C_bits": decoupling[
50
+ "mutual_information_bits"
51
+ ],
52
+ "trace_distance_rhoRC_product": decoupling[
53
+ "trace_distance_product"
54
+ ],
55
+ "petz_fidelity": channel.petz_entanglement_fidelity,
56
+ "support_rank": support.rank,
57
+ "support_logical_qubits": support.logical_qubits,
58
+ "elapsed_seconds": time.perf_counter() - started,
59
+ }
60
+ )
61
+ return rows
62
+
63
+
64
+ def run_structural_instance(
65
+ layout: SystemLayout,
66
+ scrambler: list[Gate] | tuple[Gate, ...],
67
+ t: int,
68
+ ) -> DenseFreeResult:
69
+ """Synthesize, route and certify Petz using stabilizer objects only."""
70
+ started = time.perf_counter()
71
+ channel = stabilizer_channel_at_time(layout, scrambler, t)
72
+ support = channel.tau_support
73
+ choi = channel.petz_choi_tableau
74
+ gates, encoder, output, rows = signed_dilation(
75
+ layout, channel, list(scrambler), t
76
+ )
77
+ direct = structural_validation(
78
+ layout, channel, list(scrambler), t, gates, encoder, output, rows
79
+ )
80
+ routed = route_line(layout, t, gates)
81
+ routed_metrics = structural_validation(
82
+ layout,
83
+ channel,
84
+ list(scrambler),
85
+ t,
86
+ routed.gates,
87
+ encoder,
88
+ output,
89
+ rows,
90
+ )
91
+ routed_equal = certify_routed_equivalence(layout, t, gates, routed.gates)
92
+ choi_signature = canonical_signed_stabilizer_signature(
93
+ [choi.z_output(index) for index in range(len(choi))]
94
+ )
95
+ metrics = {
96
+ "message_qubits": layout.n_message,
97
+ "alphabet_size": 1 << layout.n_message,
98
+ "t": t,
99
+ "support_rank": support.rank,
100
+ "support_logical_qubits": support.logical_qubits,
101
+ "tau_signed_generator_count": len(support.signed_generators),
102
+ "choi_qubits": len(choi),
103
+ "choi_signed_generator_count": len(choi_signature),
104
+ "petz_fidelity": channel.petz_entanglement_fidelity,
105
+ "direct_fidelity": direct["circuit_fidelity"],
106
+ "routed_fidelity": routed_metrics["circuit_fidelity"],
107
+ "reduced_choi_equal": direct["reduced_choi_equal"],
108
+ "signed_phases_validated": direct[
109
+ "entanglement_phases_match_on_intersection"
110
+ ],
111
+ "logical_depth": two_qubit_depth(gates, layout.n_qubits),
112
+ "logical_cnot": sum(gate.name == "CNOT" for gate in gates),
113
+ "routed_depth": routed.two_qubit_depth,
114
+ "routed_cnot": routed.cnot_count,
115
+ "swap": routed.swap_count,
116
+ "environment_qubits": len(output) - support.logical_qubits,
117
+ "routed_clifford_equal": routed_equal,
118
+ "final_order_restored": routed.final_wire_at_site == layout.chain(t),
119
+ "dense_channel_constructed": False,
120
+ "dense_tau_constructed": False,
121
+ "dense_choi_constructed": False,
122
+ "dense_state_validation_constructed": False,
123
+ "elapsed_seconds": time.perf_counter() - started,
124
+ "validated": bool(direct["validated"])
125
+ and bool(routed_metrics["validated"])
126
+ and routed_equal,
127
+ }
128
+ return DenseFreeResult(metrics, tuple(gates), tuple(routed.gates))
@@ -0,0 +1,242 @@
1
+ """Experiment definition and statistically reproducible aggregation."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ import csv
7
+ from itertools import product
8
+ import numpy as np
9
+
10
+ from .simulator import Gate, apply_circuit, bell_fidelity, bell_pair, zero_state
11
+
12
+ # Register order. A is absorbed and, together with B, becomes five emitted slots D0..D4.
13
+ R, A = 0, 1
14
+ B = (2, 3, 4, 5)
15
+ E = (6, 7, 8, 9)
16
+ N_QUBITS = 10
17
+ SCRAMBLED = (A, *B)
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Config:
22
+ seed: int = 20260802
23
+ trials: int = 50
24
+ decoder_samples: int = 1
25
+ depths: tuple[int, ...] = (0, 1, 2, 3, 4, 5, 6, 8)
26
+ output_dir: str = "results"
27
+
28
+
29
+ def initial_state() -> np.ndarray:
30
+ state = bell_pair(zero_state(N_QUBITS), R, A, N_QUBITS)
31
+ for b, e in zip(B, E):
32
+ state = bell_pair(state, b, e, N_QUBITS)
33
+ return state
34
+
35
+
36
+ def random_scrambler(rng: np.random.Generator, layers: int) -> list[Gate]:
37
+ gates: list[Gate] = []
38
+ q = list(SCRAMBLED)
39
+ for _ in range(layers):
40
+ for x in q:
41
+ name = ("H", "S")[int(rng.integers(2))]
42
+ gates.append(Gate(name, x))
43
+ rng.shuffle(q)
44
+ for c, target in zip(q[::2], q[1::2]):
45
+ gates.append(Gate("CNOT", c, target))
46
+ return gates
47
+
48
+
49
+ def random_decoder(rng: np.random.Generator, accessible: tuple[int, ...], depth: int) -> list[Gate]:
50
+ """Witness ensemble: depth counts layers containing at most one two-qubit gate."""
51
+ gates: list[Gate] = []
52
+ if not accessible:
53
+ return gates
54
+ for _ in range(depth):
55
+ for q in accessible:
56
+ if rng.random() < 0.35:
57
+ gates.append(Gate(("H", "S")[int(rng.integers(2))], q))
58
+ if len(accessible) >= 2:
59
+ c, target = rng.choice(accessible, 2, replace=False)
60
+ gates.append(Gate("CNOT", int(c), int(target)))
61
+ return gates
62
+
63
+
64
+ def inverse_decoder(scrambler: list[Gate], accessible: tuple[int, ...]) -> list[Gate] | None:
65
+ """Known-U construction, only if every qubit touched by U is accessible."""
66
+ # The caller applies this circuit with inverse=True; this matters for S -> S†.
67
+ return scrambler if set(SCRAMBLED).issubset(accessible) else None
68
+
69
+
70
+ def two_qubit_depth(circuit: list[Gate]) -> int:
71
+ """Greedy valid layering of ordered CNOTs; one-qubit gates cost zero here."""
72
+ layers: list[set[int]] = []
73
+ for gate in circuit:
74
+ if gate.name != "CNOT":
75
+ continue
76
+ assert gate.b is not None
77
+ used = {gate.a, gate.b}
78
+ for layer in layers:
79
+ if not (layer & used):
80
+ layer.update(used)
81
+ break
82
+ else:
83
+ layers.append(set(used))
84
+ return len(layers)
85
+
86
+
87
+ def bounded_clifford_search(state: np.ndarray, accessible: tuple[int, ...], output: int,
88
+ max_depth: int) -> tuple[list[Gate], float]:
89
+ """Exhaustive witness for <=3 accessible qubits and depth <=2.
90
+
91
+ This deliberately tiny enumerator is supplied for validation experiments, not
92
+ used in the 4E prototype (whose access register is already larger). It does
93
+ not certify an optimum beyond the enumerated gate set and bound.
94
+ """
95
+ if len(accessible) > 3 or max_depth > 2:
96
+ raise ValueError("bounded search is intentionally limited to <=3 qubits and depth <=2")
97
+ local_choices = list(product(("I", "H", "S"), repeat=len(accessible)))
98
+ entanglers: list[tuple[int, int] | None] = [None] + [(a, b) for a in accessible for b in accessible if a != b]
99
+ layers: list[list[Gate]] = []
100
+ for local in local_choices:
101
+ singles = [Gate(name, q) for q, name in zip(accessible, local) if name != "I"]
102
+ for pair in entanglers:
103
+ layers.append(singles + ([] if pair is None else [Gate("CNOT", *pair)]))
104
+ best_circuit: list[Gate] = []
105
+ best_score = bell_fidelity(state, R, output, N_QUBITS)
106
+ frontier = [([], state)]
107
+ for _ in range(max_depth):
108
+ new_frontier = []
109
+ for prefix, partial in frontier:
110
+ for layer in layers:
111
+ candidate = prefix + layer
112
+ evolved = apply_circuit(partial, layer, N_QUBITS)
113
+ score = bell_fidelity(evolved, R, output, N_QUBITS)
114
+ if score > best_score:
115
+ best_circuit, best_score = candidate, score
116
+ new_frontier.append((candidate, evolved))
117
+ frontier = new_frontier
118
+ return best_circuit, best_score
119
+
120
+
121
+ def access_set(t: int, mode: str) -> tuple[int, ...]:
122
+ emitted = SCRAMBLED[:t]
123
+ if mode == "cumulative":
124
+ return (*E, *emitted)
125
+ if mode == "last_only":
126
+ return (*E, emitted[-1]) if emitted else E
127
+ if mode == "no_early":
128
+ return emitted
129
+ raise ValueError(mode)
130
+
131
+
132
+ def evaluate_trial(scrambler: list[Gate], rng: np.random.Generator, t: int, depth: int, mode: str,
133
+ decoder_samples: int) -> list[float]:
134
+ scrambled = apply_circuit(initial_state(), scrambler, N_QUBITS)
135
+ accessible = access_set(t, mode)
136
+ values: list[float] = []
137
+ # A random witness circuit is never claimed to be optimal; retain the best sampled witness.
138
+ for _ in range(decoder_samples):
139
+ candidate = random_decoder(rng, accessible, depth)
140
+ state = apply_circuit(scrambled.copy(), candidate, N_QUBITS)
141
+ values.append(bell_fidelity(state, R, A, N_QUBITS))
142
+ inv = inverse_decoder(scrambler, accessible)
143
+ if inv is not None and depth >= two_qubit_depth(inv):
144
+ state = apply_circuit(scrambled.copy(), inv, N_QUBITS, inverse=True)
145
+ values.append(bell_fidelity(state, R, A, N_QUBITS))
146
+ return values
147
+
148
+
149
+ def run(config: Config) -> list[dict[str, object]]:
150
+ rng = np.random.default_rng(config.seed)
151
+ rows: list[dict[str, object]] = []
152
+ regimes = {"none": 0, "weak": 1, "deep": 6}
153
+ for regime, layers in regimes.items():
154
+ for mode in ("cumulative", "no_early", "last_only"):
155
+ for t in range(1, len(SCRAMBLED) + 1):
156
+ for depth in config.depths:
157
+ scores = []
158
+ for _ in range(config.trials):
159
+ scores.append(max(evaluate_trial(random_scrambler(rng, layers), rng, t, depth, mode,
160
+ config.decoder_samples)))
161
+ a = np.asarray(scores)
162
+ rows.append({"regime": regime, "access": mode, "t": t, "k": depth,
163
+ "trials": config.trials, "mean_fidelity": a.mean(),
164
+ "median_fidelity": np.median(a), "std_fidelity": a.std(),
165
+ "proportion_ge_090": np.mean(a >= .90),
166
+ "proportion_ge_099": np.mean(a >= .99)})
167
+ return rows
168
+
169
+
170
+ def write_csv(rows: list[dict[str, object]], path: Path) -> None:
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ with path.open("w", newline="") as f:
173
+ writer = csv.DictWriter(f, fieldnames=list(rows[0]))
174
+ writer.writeheader(); writer.writerows(rows)
175
+
176
+
177
+ def run_decoupling_and_petz(config: Config) -> tuple[list[dict[str, object]], list[dict[str, object]]]:
178
+ """Phase A plus explicit Petz recovery; no SDP and no depth claim."""
179
+ from .channels import channel_at_time, channel_validation, decoupling_metrics, petz_entanglement_fidelity
180
+ from .stabilizer import diagnostics as stabilizer_diagnostics
181
+
182
+ rng = np.random.default_rng(config.seed + 1)
183
+ decoupling_rows: list[dict[str, object]] = []
184
+ recovery_rows: list[dict[str, object]] = []
185
+ regimes = {"none": 0, "weak": 1, "deep": 6}
186
+ witness_depths = (0, 2, 4, 6, 8)
187
+ for regime, layers in regimes.items():
188
+ for trial in range(config.trials):
189
+ scrambler = random_scrambler(rng, layers)
190
+ state = apply_circuit(initial_state(), scrambler, N_QUBITS)
191
+ for t in range(1, len(SCRAMBLED) + 1):
192
+ cumulative_metrics = None
193
+ for access_name, has_e in (("E_plus_D", True), ("D_only", False)):
194
+ metrics = decoupling_metrics(state, t, include_early_radiation=has_e)
195
+ if has_e:
196
+ cumulative_metrics = metrics
197
+ decoupling_rows.append({"regime": regime, "trial": trial, "t": t, "access_model": access_name,
198
+ **metrics})
199
+ channel = channel_at_time(scrambler, t)
200
+ validation = channel_validation(channel)
201
+ petz_fidelity, petz_info = petz_entanglement_fidelity(channel)
202
+ stabilizer = stabilizer_diagnostics(scrambler, N_QUBITS, R, A, B, E, t)
203
+ assert cumulative_metrics is not None
204
+ h2 = cumulative_metrics["conditional_collision_entropy_bits"]
205
+ information = cumulative_metrics["mutual_information_bits"]
206
+ audit = {"mutual_information_bits": information, "H2_R_given_C_bits": h2, "renyi2_candidate": 2 ** (h2 - 1),
207
+ "von_neumann_candidate": 2 ** (-information),
208
+ "stabilizer_rank_formula": cumulative_metrics["rank_rho_RC"] / (2 * cumulative_metrics["rank_rho_C"]),
209
+ "petz_minus_stabilizer_rank_formula": petz_fidelity - cumulative_metrics["rank_rho_RC"] / (2 * cumulative_metrics["rank_rho_C"]),
210
+ "petz_minus_renyi2_candidate": petz_fidelity - 2 ** (h2 - 1),
211
+ "petz_minus_von_neumann_candidate": petz_fidelity - 2 ** (-information),
212
+ "rank_rho_RC": cumulative_metrics["rank_rho_RC"], "rank_rho_C": cumulative_metrics["rank_rho_C"],
213
+ "spectrum_rho_RC": cumulative_metrics["spectrum_rho_RC"], "spectrum_rho_C": cumulative_metrics["spectrum_rho_C"]}
214
+ recovery_rows.append({"regime": regime, "trial": trial, "t": t, "algorithm": "petz",
215
+ "two_qubit_depth": "", "entanglement_fidelity": petz_fidelity,
216
+ **validation, **petz_info, **audit, **stabilizer})
217
+ accessible = access_set(t, "cumulative")
218
+ for depth in witness_depths:
219
+ decoded = apply_circuit(state.copy(), random_decoder(rng, accessible, depth), N_QUBITS)
220
+ recovery_rows.append({"regime": regime, "trial": trial, "t": t,
221
+ "algorithm": "random_witness", "two_qubit_depth": depth,
222
+ "entanglement_fidelity": bell_fidelity(decoded, R, A, N_QUBITS),
223
+ **validation, **petz_info, **audit, **stabilizer})
224
+ inv = inverse_decoder(scrambler, accessible)
225
+ if inv is not None:
226
+ decoded = apply_circuit(state.copy(), inv, N_QUBITS, inverse=True)
227
+ recovery_rows.append({"regime": regime, "trial": trial, "t": t, "algorithm": "U_inverse_control",
228
+ "two_qubit_depth": two_qubit_depth(inv),
229
+ "entanglement_fidelity": bell_fidelity(decoded, R, A, N_QUBITS),
230
+ **validation, **petz_info, **audit, **stabilizer})
231
+ return decoupling_rows, recovery_rows
232
+
233
+
234
+ def summarize(rows: list[dict[str, object]], group: tuple[str, ...], value: str) -> list[dict[str, object]]:
235
+ result: list[dict[str, object]] = []
236
+ keys = sorted({tuple(row[k] for k in group) for row in rows})
237
+ for key in keys:
238
+ values = np.asarray([float(row[value]) for row in rows if tuple(row[k] for k in group) == key])
239
+ result.append(dict(zip(group, key)) | {"count": len(values), "mean": values.mean(), "median": np.median(values),
240
+ "std": values.std(), "q10": np.quantile(values, .10),
241
+ "q50": np.quantile(values, .50), "q90": np.quantile(values, .90)})
242
+ return result