Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 15 additions & 1 deletion graphix/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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``.
Expand Down
21 changes: 21 additions & 0 deletions tests/test_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down