From ebeeddbb71f8273f0b07c8559c3e637148df2c19 Mon Sep 17 00:00:00 2001 From: KainanP Date: Sun, 29 Nov 2026 07:19:14 -0300 Subject: [PATCH] Copy command domains in Pattern.copy Pattern.copy made shallow copies of the commands, so the s_domain, t_domain and domain sets were shared with the original pattern. shift_signals(method="mc") updates these sets in place, so shifting the signals of a copy also rewrote the original, which then no longer implemented the same map. Copy the set-valued fields of each command. Fixes #653. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ graphix/pattern.py | 16 +++++++++++++++- tests/test_pattern.py | 21 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4203455dc..30190f989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - #645: Fix negative sign in circuit extraction strings +- #653: `Pattern.copy` now copies the domains of the commands, so that transformations that update domains in place, such as `shift_signals(method="mc")`, no longer change the original pattern when applied to its copy. + ### Changed - #587: diff --git a/graphix/pattern.py b/graphix/pattern.py index 9eec173c0..188d84e63 100644 --- a/graphix/pattern.py +++ b/graphix/pattern.py @@ -1624,7 +1624,7 @@ def replace_parameters( def copy(self) -> Pattern: """Return a copy of the pattern.""" result = self.__new__(self.__class__) - result.__seq = [copy.copy(cmd) for cmd in self.__seq] + result.__seq = [_copy_command(cmd) for cmd in self.__seq] result.__input_nodes = self.__input_nodes.copy() result.__output_nodes = self.__output_nodes.copy() result.__n_node = self.__n_node @@ -2072,6 +2072,20 @@ def shift_outcomes(outcomes: Mapping[int, Outcome], signal_dict: Mapping[int, Ab } +def _copy_command(cmd: CommandType) -> CommandType: + """Return a shallow copy of ``cmd`` whose domain sets are copied too. + + Some transformations (e.g. ``shift_signals(method="mc")``) update the + domains of commands in place, so a copied pattern must not share these + sets with the original. + """ + result = copy.copy(cmd) + for name, value in list(vars(result).items()): + if isinstance(value, set): + setattr(result, name, set(value)) + return result + + def _reverse_mapping(m: Mapping[K, V]) -> dict[V, list[K]]: """ Build a reverse mapping of ``m``. diff --git a/tests/test_pattern.py b/tests/test_pattern.py index bfbce7f15..8c9868df1 100644 --- a/tests/test_pattern.py +++ b/tests/test_pattern.py @@ -223,6 +223,27 @@ def test_shift_signals(self, fx_bg: PCG64, jumps: int) -> None: state_mbqc = pattern.simulate(rng=rng) assert state_mbqc.isclose(state) + def test_shift_signals_mc_on_copy_keeps_original(self) -> None: + # Regression test for #653: the copy must not share domain sets with the original. + circuit = Circuit(1) + for _ in range(3): + circuit.h(0) + pattern = circuit.transpile().pattern + pattern_ref = list(copy.deepcopy(pattern)) + duplicate = pattern.copy() + duplicate.shift_signals(method="mc") + assert list(duplicate) != pattern_ref + assert list(pattern) == pattern_ref + psi = rand_state_vector(1, rng=np.random.default_rng(0)) + expected = circuit.simulate(input_state=Statevector(data=psi)).state + measured = sorted(pattern.measurement_commands()) + values: tuple[Outcome, ...] = (0, 1) + for outcomes in itertools.product(values, repeat=len(measured)): + selector = FixedBranchSelector(dict(zip(measured, outcomes, strict=True))) + for p in (pattern, duplicate): + state = p.simulate(input_state=Statevector(data=psi), branch_selector=selector) + assert state.isclose(expected) + @pytest.mark.parametrize("jumps", range(1, 11)) @pytest.mark.parametrize("backend", ["statevector", "densitymatrix"]) @pytest.mark.filterwarnings("ignore:Simulating using densitymatrix backend with no noise.")