diff --git a/code/qec/color_code/memory_circuit.py b/code/qec/color_code/memory_circuit.py index 06bbbbd..dd3007d 100644 --- a/code/qec/color_code/memory_circuit.py +++ b/code/qec/color_code/memory_circuit.py @@ -552,18 +552,18 @@ def add_reset(self, qubits, basis='Z'): # Apply preparation errors if self.noise_model is not None: - # Use 22-parameter noise model: explicit X_ERROR and Z_ERROR - # For Z-basis prep (|0>): X error flips to |1> - # For X-basis prep (|+>): Z error flips to |-> - if basis == 'Z' and self.noise_model.p_prep_X > 0: + # Basis-labeled semantics (same as the surface-code builder): + # - Z-basis prep (|0>): X flips to |1> -> use p_prep_Z (Z-basis prep failure) + # - X-basis prep (|+>): Z flips to |-> -> use p_prep_X (X-basis prep failure) + if basis == 'Z' and self.noise_model.p_prep_Z > 0: c += self.margin - c += 'X_ERROR(%.10f) ' % self.noise_model.p_prep_X + c += 'X_ERROR(%.10f) ' % self.noise_model.p_prep_Z for q in qubits: c += '%d ' % q c += '\n' - elif basis == 'X' and self.noise_model.p_prep_Z > 0: + elif basis == 'X' and self.noise_model.p_prep_X > 0: c += self.margin - c += 'Z_ERROR(%.10f) ' % self.noise_model.p_prep_Z + c += 'Z_ERROR(%.10f) ' % self.noise_model.p_prep_X for q in qubits: c += '%d ' % q c += '\n' @@ -585,10 +585,13 @@ def add_single_error(self, qubits, error_type): """Add a single-qubit error (X or Z) to specified qubits.""" # Determine error probability if self.noise_model is not None: + # Basis-labeled semantics: + # - Applying X corresponds to Z-basis prep failure -> p_prep_Z + # - Applying Z corresponds to X-basis prep failure -> p_prep_X if error_type == 'X': - error_prob = self.noise_model.p_prep_X - elif error_type == 'Z': error_prob = self.noise_model.p_prep_Z + elif error_type == 'Z': + error_prob = self.noise_model.p_prep_X else: error_prob = 0. else: @@ -776,9 +779,10 @@ def add_measure_reset(self, qubits, error_free_reset=False): # Measurement error (before measurement) if self.noise_model is not None: - if self.noise_model.p_meas_X > 0: + # Z-basis measurement failure is modeled as a pre-measurement X flip. + if self.noise_model.p_meas_Z > 0: c += self.margin - c += 'X_ERROR(%.10f) ' % self.noise_model.p_meas_X + c += 'X_ERROR(%.10f) ' % self.noise_model.p_meas_Z for q in qubits: c += '%d ' % q c += '\n' @@ -798,9 +802,10 @@ def add_measure_reset(self, qubits, error_free_reset=False): # Reset error (after reset, if not error-free) if not error_free_reset: if self.noise_model is not None: - if self.noise_model.p_prep_X > 0: + # Z-basis reset failure is modeled as a post-reset X flip. + if self.noise_model.p_prep_Z > 0: c += self.margin - c += 'X_ERROR(%.10f) ' % self.noise_model.p_prep_X + c += 'X_ERROR(%.10f) ' % self.noise_model.p_prep_Z for q in qubits: c += '%d ' % q c += '\n' @@ -831,9 +836,9 @@ def add_measure(self, qubits, basis='Z', include_reset=False): When NoiseModel is set, uses explicit X_ERROR/Z_ERROR with measurement probabilities. Otherwise uses spam_error for backwards compatibility. - Convention: - - Z-basis measurement: X error before measurement flips the outcome - - X-basis measurement: Z error before measurement flips the outcome + Convention (basis-labeled, same as the surface-code builder): + - Z-basis measurement: X error before measurement flips the outcome (p_meas_Z) + - X-basis measurement: Z error before measurement flips the outcome (p_meas_X) """ basis = basis.upper() @@ -841,15 +846,15 @@ def add_measure(self, qubits, basis='Z', include_reset=False): # Apply measurement errors (before measurement) if self.noise_model is not None: # Use 22-parameter noise model: explicit X_ERROR or Z_ERROR - if basis == 'Z' and self.noise_model.p_meas_X > 0: + if basis == 'Z' and self.noise_model.p_meas_Z > 0: c += self.margin - c += 'X_ERROR(%.10f) ' % self.noise_model.p_meas_X + c += 'X_ERROR(%.10f) ' % self.noise_model.p_meas_Z for q in qubits: c += '%d ' % q c += '\n' - elif basis == 'X' and self.noise_model.p_meas_Z > 0: + elif basis == 'X' and self.noise_model.p_meas_X > 0: c += self.margin - c += 'Z_ERROR(%.10f) ' % self.noise_model.p_meas_Z + c += 'Z_ERROR(%.10f) ' % self.noise_model.p_meas_X for q in qubits: c += '%d ' % q c += '\n' @@ -1326,8 +1331,10 @@ def _add_stabilizer_round( if not state_prep: if logical_measurement and orig_noise_model is not None: # Inject ONLY a "fake data-measurement SPAM" error on data qubits. + # - X-basis data measurement failure -> apply Z with prob p_meas_X + # - Z-basis data measurement failure -> apply X with prob p_meas_Z if self.basis.upper() == 'X': - p_fake = float(orig_noise_model.p_meas_Z) + p_fake = float(orig_noise_model.p_meas_X) if p_fake > 0: c = self.margin + 'Z_ERROR(%.10f) ' % p_fake for q in self.code.data_qubits: @@ -1335,7 +1342,7 @@ def _add_stabilizer_round( c += '\n' self.circuit += c else: # 'Z' - p_fake = float(orig_noise_model.p_meas_X) + p_fake = float(orig_noise_model.p_meas_Z) if p_fake > 0: c = self.margin + 'X_ERROR(%.10f) ' % p_fake for q in self.code.data_qubits: diff --git a/code/qec/noise_model.py b/code/qec/noise_model.py index 8669cfc..9904daf 100644 --- a/code/qec/noise_model.py +++ b/code/qec/noise_model.py @@ -171,10 +171,12 @@ class NoiseModel: 25-Parameter Noise Model for circuit-level noise simulation. Attributes: - p_prep_X: X error probability after state preparation - p_prep_Z: Z error probability after state preparation - p_meas_X: X error probability before measurement - p_meas_Z: Z error probability before measurement + p_prep_X: X-basis (|+>) state-preparation failure probability (applied as Z after reset) + p_prep_Z: Z-basis (|0>) state-preparation failure probability (applied as X after reset) + p_meas_X: X-basis measurement failure probability (applied as Z before measurement) + p_meas_Z: Z-basis measurement failure probability (applied as X before measurement) + The four keys above are named by the failing basis, not by the applied + Pauli, in both the surface-code and the color-code circuits. p_idle_cnot_X/Y/Z: Idle Pauli errors during bulk/CNOT layers (single-qubit Pauli channel) p_idle_spam_X/Y/Z: Idle Pauli errors on data qubits during ancilla prep/reset window. NOTE: In noise-model mode we intentionally do NOT apply data-qubit diff --git a/code/qec/precompute_dem.py b/code/qec/precompute_dem.py index ba34d1e..7860f21 100644 --- a/code/qec/precompute_dem.py +++ b/code/qec/precompute_dem.py @@ -1651,20 +1651,23 @@ def build_single_p_marginal_color_code( if len(err_type) == 2: p_err[int(eidx)] = nm_cnot.get(err_type, 0.0) elif len(err_type) == 1: + # Basis-labeled keys, as in the surface-code path and in the + # color MemoryCircuit: basis 0 is X (Z fault, p_*_X), basis 1 is + # Z (X fault, p_*_Z). if is_ancilla_prep: prep_basis = int(prep_basis_map[(round_idx, q)]) - p_err[int(eidx)] = p_prep_Z_nm if prep_basis == 0 else p_prep_X_nm + p_err[int(eidx)] = p_prep_X_nm if prep_basis == 0 else p_prep_Z_nm elif is_ancilla_meas: meas_basis = int(meas_basis_map[(round_idx, q)]) - p_err[int(eidx)] = p_meas_Z_nm if meas_basis == 0 else p_meas_X_nm + p_err[int(eidx)] = p_meas_X_nm if meas_basis == 0 else p_meas_Z_nm elif is_data_prep: prep_basis = int(prep_basis_map[(round_idx, q)]) if is_final_round: # The final perfect round models noisy data readout with a # fake Pauli error at tt=0 (see MemoryCircuit). - p_err[int(eidx)] = (p_meas_Z_nm if prep_basis == 0 else p_meas_X_nm) + p_err[int(eidx)] = (p_meas_X_nm if prep_basis == 0 else p_meas_Z_nm) else: - p_err[int(eidx)] = (p_prep_Z_nm if prep_basis == 0 else p_prep_X_nm) + p_err[int(eidx)] = (p_prep_X_nm if prep_basis == 0 else p_prep_Z_nm) elif is_data_spam_idle: p_err[int(eidx)] = nm_idle_spam.get(err_type, 0.0) else: diff --git a/code/tests/test_color_augmented_dem_precompute.py b/code/tests/test_color_augmented_dem_precompute.py index e80ab4e..54e8687 100644 --- a/code/tests/test_color_augmented_dem_precompute.py +++ b/code/tests/test_color_augmented_dem_precompute.py @@ -92,11 +92,11 @@ def test_color_precompute_p_vector_uses_25p_values(basis): "data_prep_probability", ), [ - ("X", "Z", 0.0044, "Z", 0.0022), - ("Z", "X", 0.0033, "X", 0.0011), + ("X", "Z", 0.0033, "Z", 0.0011), + ("Z", "X", 0.0044, "X", 0.0022), ], ) -def test_color_single_qubit_noise_probabilities_follow_pauli_labels( +def test_color_single_qubit_noise_probabilities_follow_basis_labels( basis, final_error_type, final_probability, @@ -157,10 +157,10 @@ def test_color_single_qubit_noise_probabilities_follow_pauli_labels( np.testing.assert_allclose( probabilities[7:11], [ - noise_model.p_prep_Z, - noise_model.p_meas_Z, noise_model.p_prep_X, noise_model.p_meas_X, + noise_model.p_prep_Z, + noise_model.p_meas_Z, ], rtol=0.0, atol=1e-9, @@ -277,8 +277,8 @@ def test_color_noiseless_context_restores_noise_state_normally(): "final_probability", ), [ - ("X", "Z_ERROR", "Z", 0.023, 0.047), - ("Z", "X_ERROR", "X", 0.019, 0.031), + ("X", "Z_ERROR", "Z", 0.019, 0.031), + ("Z", "X_ERROR", "X", 0.023, 0.047), ], ) def test_color_stim_and_dem_data_noise_locations_match( @@ -359,10 +359,10 @@ def test_color_stim_and_dem_data_noise_locations_match( sorted([data_prep_probability, final_probability]) ) assert sorted(stim_xcheck_error_ops) == pytest.approx( - sorted([noise_model.p_prep_Z, noise_model.p_meas_Z] * (n_rounds - 1)) + sorted([noise_model.p_prep_X, noise_model.p_meas_X] * (n_rounds - 1)) ) assert sorted(stim_zcheck_error_ops) == pytest.approx( - sorted([noise_model.p_prep_X, noise_model.p_meas_X] * (n_rounds - 1)) + sorted([noise_model.p_prep_Z, noise_model.p_meas_Z] * (n_rounds - 1)) ) layout = _extract_color_round_layout( diff --git a/code/tests/test_color_code_prep_meas_key_convention.py b/code/tests/test_color_code_prep_meas_key_convention.py new file mode 100644 index 0000000..2e7fc97 --- /dev/null +++ b/code/tests/test_color_code_prep_meas_key_convention.py @@ -0,0 +1,199 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Convention of the four prep/meas noise-model keys in the color-code path. + +``p_prep_X``, ``p_prep_Z``, ``p_meas_X`` and ``p_meas_Z`` are named by the +basis of the reset or measurement that fails, not by the Pauli that is +applied: an X-basis failure is a ``Z_ERROR``, a Z-basis failure is an +``X_ERROR``. The surface-code builder, the color-code builder and the +color-code DEM precompute must all read the keys in this sense. +""" + +import sys +import unittest +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from qec.color_code.memory_circuit import MemoryCircuit as ColorMemoryCircuit +from qec.noise_model import NoiseModel +from qec.precompute_dem import build_single_p_marginal_color_code +from qec.surface_code.memory_circuit import MemoryCircuit as SurfaceMemoryCircuit + +PROBABILITY = 0.01 +BASES = ("X", "Z") + +# key -> (Stim instruction, ancilla family that is reset/measured in that +# basis, memory basis in which the data qubits are reset/measured in it). +EXPECTED = { + "p_prep_X": ("Z_ERROR", "xcheck", "X"), + "p_prep_Z": ("X_ERROR", "zcheck", "Z"), + "p_meas_X": ("Z_ERROR", "xcheck", "X"), + "p_meas_Z": ("X_ERROR", "zcheck", "Z"), +} + + +def _build_color(basis, noise_model): + circuit = ColorMemoryCircuit( + distance=3, + idle_error=0.0, + sqgate_error=0.0, + tqgate_error=0.0, + spam_error=0.0, + n_rounds=3, + basis=basis, + noise_model=noise_model, + add_detectors=False, + schedule="nearest-neighbor", + ) + return circuit, circuit.stim_circuit_raw + + +def _build_surface(basis, noise_model): + circuit = SurfaceMemoryCircuit( + distance=3, + idle_error=0.0, + sqgate_error=0.0, + tqgate_error=0.0, + spam_error=0.0, + n_rounds=3, + basis=basis, + noise_model=noise_model, + ) + return circuit, circuit.stim_circuit + + +def _flip_error_sites(build, basis, noise_model): + """Return {(instruction, probability): qubit families hit} for a circuit.""" + circuit, stim_circuit = build(basis, noise_model) + families = { + "data": {int(q) for q in circuit.code.data_qubits}, + "xcheck": {int(q) for q in circuit.code.xcheck_qubits}, + "zcheck": {int(q) for q in circuit.code.zcheck_qubits}, + } + sites = {} + for instruction in stim_circuit.flattened(): + if instruction.name not in ("X_ERROR", "Z_ERROR"): + continue + targets = {target.value for target in instruction.targets_copy()} + key = (instruction.name, round(instruction.gate_args_copy()[0], 9)) + hit = sites.setdefault(key, set()) + hit.update(name for name, qubits in families.items() if targets & qubits) + return {key: frozenset(hit) for key, hit in sites.items()} + + +def _expected_sites(key, basis): + instruction, ancilla_family, data_basis = EXPECTED[key] + families = {ancilla_family} + if basis == data_basis: + families.add("data") + return {(instruction, PROBABILITY): frozenset(families)} + + +class TestColorCodePrepMeasKeyConvention(unittest.TestCase): + + def test_single_key_maps_to_failing_basis_in_color_circuit(self): + for key in EXPECTED: + for basis in BASES: + with self.subTest(key=key, basis=basis): + sites = _flip_error_sites(_build_color, basis, NoiseModel(**{key: PROBABILITY})) + self.assertEqual(sites, _expected_sites(key, basis)) + + def test_z_basis_memory_uses_z_keys_for_x_errors(self): + """Z-basis prep/meas failures (X_ERROR) come from the *_Z keys only.""" + for key, other in (("p_prep_Z", "p_prep_X"), ("p_meas_Z", "p_meas_X")): + with self.subTest(key=key): + sites = _flip_error_sites(_build_color, "Z", NoiseModel(**{key: PROBABILITY})) + self.assertIn(("X_ERROR", PROBABILITY), sites) + sites = _flip_error_sites(_build_color, "Z", NoiseModel(**{other: PROBABILITY})) + self.assertNotIn("X_ERROR", {instruction for instruction, _ in sites}) + + def test_color_and_surface_builders_agree(self): + for key in EXPECTED: + for basis in BASES: + with self.subTest(key=key, basis=basis): + noise_model = NoiseModel(**{key: PROBABILITY}) + self.assertEqual( + _flip_error_sites(_build_color, basis, noise_model), + _flip_error_sites(_build_surface, basis, noise_model), + ) + + def test_color_and_surface_builders_agree_with_distinct_values(self): + noise_model = NoiseModel(p_prep_X=0.011, p_prep_Z=0.022, p_meas_X=0.033, p_meas_Z=0.044) + for basis in BASES: + with self.subTest(basis=basis): + color_sites = _flip_error_sites(_build_color, basis, noise_model) + self.assertEqual( + set(color_sites), + { + ("Z_ERROR", 0.011), + ("X_ERROR", 0.022), + ("Z_ERROR", 0.033), + ("X_ERROR", 0.044), + }, + ) + self.assertEqual(color_sites, _flip_error_sites(_build_surface, basis, noise_model)) + + def test_color_dem_marginals_use_basis_labeled_keys(self): + """The precomputed color p-vector assigns the same key as the Stim circuit.""" + noise_model = NoiseModel(p_prep_X=0.011, p_prep_Z=0.022, p_meas_X=0.033, p_meas_Z=0.044) + t_total = 4 + last = t_total - 1 + # (error index, round, time step, qubit, Pauli, second qubit); qubit 0 is + # data, qubit 1 an X-check ancilla, qubit 2 a Z-check ancilla. + for basis, pauli, p_data_prep, p_data_meas in ( + ("X", "Z", noise_model.p_prep_X, noise_model.p_meas_X), + ("Z", "X", noise_model.p_prep_Z, noise_model.p_meas_Z), + ): + metadata = [ + (0, -1, -1, -1, "I", -1), + (1, 1, 0, 1, "Z", -1), # X-check ancilla prep + (2, 1, last, 1, "Z", -1), # X-check ancilla measurement + (3, 1, 0, 2, "X", -1), # Z-check ancilla prep + (4, 1, last, 2, "X", -1), # Z-check ancilla measurement + (5, 0, 0, 0, pauli, -1), # data prep (first round) + (6, 2, 0, 0, pauli, -1), # data readout flip (final round) + ] + with self.subTest(basis=basis): + probabilities = build_single_p_marginal_color_code( + error_metadata_global=metadata, + t_total=t_total, + n_rounds=3, + data_qubits=np.array([0], dtype=np.int32), + xcheck_qubits=np.array([1], dtype=np.int32), + zcheck_qubits=np.array([2], dtype=np.int32), + basis=basis, + p_scalar=0.0, + noise_model=noise_model, + ) + np.testing.assert_allclose( + probabilities[1:], + [ + noise_model.p_prep_X, + noise_model.p_meas_X, + noise_model.p_prep_Z, + noise_model.p_meas_Z, + p_data_prep, + p_data_meas, + ], + rtol=0.0, + atol=1e-9, + ) + + +if __name__ == "__main__": + unittest.main()