Skip to content

Commit 5113e57

Browse files
authored
fix: apply pow modifier to cnot and swap gates (#414)
1 parent e7b02ed commit 5113e57

6 files changed

Lines changed: 238 additions & 4 deletions

File tree

‎src/braket/default_simulator/gate_operations.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,8 @@ def _base_matrix(self) -> np.ndarray:
208208
return CX._matrix
209209

210210
@property
211-
def gate_type(self) -> str:
212-
return "cx"
211+
def gate_type(self) -> str | None:
212+
return "cx" if self._power % 2 == 1 else None
213213

214214

215215
@_from_braket_instruction.register(braket_instruction.CNot)
@@ -694,8 +694,8 @@ def _base_matrix(self) -> np.ndarray:
694694
return Swap._matrix
695695

696696
@property
697-
def gate_type(self) -> str:
698-
return "swap"
697+
def gate_type(self) -> str | None:
698+
return "swap" if self._power % 2 == 1 else None
699699

700700

701701
@_from_braket_instruction.register(braket_instruction.Swap)

‎test/unit_tests/braket/default_simulator/test_density_matrix_simulation.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
from braket.default_simulator import gate_operations, noise_operations, observables
2020
from braket.default_simulator.density_matrix_simulation import DensityMatrixSimulation
21+
from braket.default_simulator.state_vector_simulation import StateVectorSimulation
2122

2223
sx = np.array([[0, 1], [1, 0]], dtype=complex)
2324
si = np.array([[1, 0], [0, 1]], dtype=complex)
@@ -520,3 +521,52 @@ def test_toffoli_gate():
520521
prob_7 = counter[7] / total_shots
521522
assert abs(prob_2 - 0.5) < 0.1
522523
assert abs(prob_7 - 0.5) < 0.1
524+
525+
526+
_POWERS = [0, 1, 2, 3, -1, -2, 0.5, -0.5, 1.5]
527+
528+
_POWERED_GATES = [
529+
(gate_operations.Hadamard, 1, ()),
530+
(gate_operations.PauliX, 1, ()),
531+
(gate_operations.PauliZ, 1, ()),
532+
(gate_operations.S, 1, ()),
533+
(gate_operations.T, 1, ()),
534+
(gate_operations.RotX, 1, (0.37,)),
535+
(gate_operations.RotZ, 1, (0.37,)),
536+
(gate_operations.PhaseShift, 1, (0.37,)),
537+
(gate_operations.CX, 2, ()),
538+
(gate_operations.CY, 2, ()),
539+
(gate_operations.CZ, 2, ()),
540+
(gate_operations.Swap, 2, ()),
541+
(gate_operations.ISwap, 2, ()),
542+
(gate_operations.ECR, 2, ()),
543+
(gate_operations.CPhaseShift, 2, (0.37,)),
544+
(gate_operations.PSwap, 2, (0.37,)),
545+
(gate_operations.XX, 2, (0.37,)),
546+
(gate_operations.ZZ, 2, (0.37,)),
547+
]
548+
549+
550+
def _preparation_operations(qubit_count):
551+
return [gate_operations.RotY([q], 0.3 + 0.4 * q) for q in range(qubit_count)] + [
552+
gate_operations.RotZ([q], 0.2 + 0.3 * q) for q in range(qubit_count)
553+
]
554+
555+
556+
def _assert_matches_state_vector(operations, qubit_count):
557+
simulation = DensityMatrixSimulation(qubit_count, 0)
558+
simulation.evolve(operations)
559+
reference = StateVectorSimulation(qubit_count, 0, 1)
560+
reference.evolve(operations)
561+
state_vector = reference.state_vector
562+
assert np.allclose(simulation.density_matrix, np.outer(state_vector, state_vector.conj()))
563+
564+
565+
@pytest.mark.parametrize("qubit_count, targets", [(3, (2, 0)), (5, (4, 1))])
566+
@pytest.mark.parametrize("power", _POWERS)
567+
@pytest.mark.parametrize("gate_class, num_targets, args", _POWERED_GATES)
568+
def test_powered_gate(gate_class, num_targets, args, power, qubit_count, targets):
569+
operations = _preparation_operations(qubit_count) + [
570+
gate_class(targets[:num_targets], *args, power=power)
571+
]
572+
_assert_matches_state_vector(operations, qubit_count)

‎test/unit_tests/braket/default_simulator/test_density_matrix_simulator.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import numpy as np
2222
import pytest
23+
from scipy.linalg import fractional_matrix_power
2324
from braket.device_schema.simulators import (
2425
GateModelSimulatorDeviceCapabilities,
2526
GateModelSimulatorDeviceParameters,
@@ -1088,3 +1089,42 @@ def test_remove_verbatim_box_with_nested_braces():
10881089
assert "box{" not in result
10891090
assert "if (b == 1) {" in result
10901091
assert "x $0;" in result
1092+
1093+
1094+
_TWO_QUBIT_BASE_MATRICES = {
1095+
"cnot": np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex),
1096+
"swap": np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex),
1097+
"cz": np.diag([1, 1, 1, -1]).astype(complex),
1098+
"iswap": np.array([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]], dtype=complex),
1099+
}
1100+
1101+
1102+
def _openqasm_matrix(matrix):
1103+
return (
1104+
"["
1105+
+ ", ".join("[" + ", ".join(f"{z.real}{z.imag:+}im" for z in row) + "]" for row in matrix)
1106+
+ "]"
1107+
)
1108+
1109+
1110+
@pytest.mark.parametrize("power", [0, 2, 3, -1, -2, 0.5, -0.5, 1.5])
1111+
@pytest.mark.parametrize("gate", list(_TWO_QUBIT_BASE_MATRICES))
1112+
def test_pow_two_qubit_gate_matches_unitary(gate, power):
1113+
preparation = "qubit[2] q;\nry(0.7) q[0];\nry(0.3) q[1];\n"
1114+
powered = f"OPENQASM 3.0;\n{preparation}pow({power}) @ {gate} q[0], q[1];\n"
1115+
matrix = fractional_matrix_power(_TWO_QUBIT_BASE_MATRICES[gate], power)
1116+
unitary = (
1117+
f"OPENQASM 3.0;\n{preparation}"
1118+
f"#pragma braket unitary({_openqasm_matrix(matrix)}) q[0], q[1]\n"
1119+
)
1120+
result_type = "#pragma braket result density_matrix\n"
1121+
results = [
1122+
np.asarray(
1123+
DensityMatrixSimulator()
1124+
.run(OpenQASMProgram(source=source + result_type), shots=0)
1125+
.resultTypes[0]
1126+
.value
1127+
)
1128+
for source in (powered, unitary)
1129+
]
1130+
assert np.allclose(*results)

‎test/unit_tests/braket/default_simulator/test_gate_operations.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,29 @@ def test_gate_operation(ir_instruction, targets, operation_type):
8888
check_unitary(operation_instance.matrix)
8989

9090

91+
@pytest.mark.parametrize(
92+
"operation_type, gate_type", [(gate_operations.CX, "cx"), (gate_operations.Swap, "swap")]
93+
)
94+
@pytest.mark.parametrize(
95+
"power, uses_gate_type",
96+
[
97+
(1, True),
98+
(3, True),
99+
(-1, True),
100+
(1.0, True),
101+
(0, False),
102+
(2, False),
103+
(-2, False),
104+
(0.5, False),
105+
],
106+
)
107+
def test_matrix_free_gate_type_respects_power(operation_type, gate_type, power, uses_gate_type):
108+
operation = operation_type([0, 1], power=power)
109+
assert operation.gate_type == (gate_type if uses_gate_type else None)
110+
if uses_gate_type:
111+
np.testing.assert_allclose(operation.matrix, operation._base_matrix)
112+
113+
91114
# ---------------------------------------------------------------------------
92115
# Measure class tests
93116
# ---------------------------------------------------------------------------

‎test/unit_tests/braket/default_simulator/test_state_vector_simulation.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import pytest
1818

1919
from braket.default_simulator import gate_operations, observables
20+
from braket.default_simulator.linalg_utils import controlled_matrix
2021
from braket.default_simulator.state_vector_simulation import StateVectorSimulation
2122

2223
evolve_testdata = [
@@ -544,3 +545,85 @@ def test_ghz_tree_retrieve_samples(batch_size):
544545
assert 0.4 < counter[0] / (counter[0] + counter[960]) < 0.6
545546
assert 0.4 < counter[960] / (counter[0] + counter[960]) < 0.6
546547
assert counter[0] + counter[960] == 10000
548+
549+
550+
_POWERS = [0, 1, 2, 3, -1, -2, 0.5, -0.5, 1.5]
551+
552+
_POWERED_GATES = [
553+
(gate_operations.Hadamard, 1, ()),
554+
(gate_operations.PauliX, 1, ()),
555+
(gate_operations.PauliZ, 1, ()),
556+
(gate_operations.S, 1, ()),
557+
(gate_operations.T, 1, ()),
558+
(gate_operations.RotX, 1, (0.37,)),
559+
(gate_operations.RotZ, 1, (0.37,)),
560+
(gate_operations.PhaseShift, 1, (0.37,)),
561+
(gate_operations.CX, 2, ()),
562+
(gate_operations.CY, 2, ()),
563+
(gate_operations.CZ, 2, ()),
564+
(gate_operations.Swap, 2, ()),
565+
(gate_operations.ISwap, 2, ()),
566+
(gate_operations.ECR, 2, ()),
567+
(gate_operations.CPhaseShift, 2, (0.37,)),
568+
(gate_operations.PSwap, 2, (0.37,)),
569+
(gate_operations.XX, 2, (0.37,)),
570+
(gate_operations.ZZ, 2, (0.37,)),
571+
]
572+
573+
574+
def _preparation_operations(qubit_count):
575+
return [gate_operations.RotY([q], 0.3 + 0.4 * q) for q in range(qubit_count)] + [
576+
gate_operations.RotZ([q], 0.2 + 0.3 * q) for q in range(qubit_count)
577+
]
578+
579+
580+
def _apply_reference(state_vector, operation, qubit_count):
581+
matrix = controlled_matrix(operation.matrix, operation.control_state)
582+
targets = operation.targets
583+
num_targets = len(targets)
584+
product = np.tensordot(
585+
matrix.reshape([2] * 2 * num_targets),
586+
state_vector.reshape([2] * qubit_count),
587+
axes=(range(num_targets, 2 * num_targets), targets),
588+
)
589+
return np.moveaxis(product, range(num_targets), targets).reshape(-1)
590+
591+
592+
def _reference_state_vector(operations, qubit_count):
593+
state_vector = np.zeros(2**qubit_count, dtype=complex)
594+
state_vector[0] = 1
595+
for operation in operations:
596+
state_vector = _apply_reference(state_vector, operation, qubit_count)
597+
return state_vector
598+
599+
600+
@pytest.mark.parametrize("qubit_count, targets", [(3, (2, 0)), (11, (9, 3))])
601+
@pytest.mark.parametrize("power", _POWERS)
602+
@pytest.mark.parametrize("gate_class, num_targets, args", _POWERED_GATES)
603+
def test_powered_gate(gate_class, num_targets, args, power, qubit_count, targets):
604+
operations = _preparation_operations(qubit_count) + [
605+
gate_class(targets[:num_targets], *args, power=power)
606+
]
607+
simulation = StateVectorSimulation(qubit_count, 0, 1)
608+
simulation.evolve(operations)
609+
assert np.allclose(simulation.state_vector, _reference_state_vector(operations, qubit_count))
610+
611+
612+
@pytest.mark.parametrize(
613+
"qubit_count, targets, control_state",
614+
[
615+
(4, (1, 3, 0), (1,)),
616+
(4, (1, 3, 0), (0,)),
617+
(4, (1, 3, 0, 2), (1, 1)),
618+
(4, (3, 1, 2, 0), (0, 0)),
619+
],
620+
)
621+
@pytest.mark.parametrize("power", [0, 2, 0.5, -1])
622+
@pytest.mark.parametrize("gate_class", [gate_operations.CX, gate_operations.Swap])
623+
def test_controlled_powered_gate(gate_class, power, qubit_count, targets, control_state):
624+
operations = _preparation_operations(qubit_count) + [
625+
gate_class(targets, ctrl_modifiers=control_state, power=power)
626+
]
627+
simulation = StateVectorSimulation(qubit_count, 0, 1)
628+
simulation.evolve(operations)
629+
assert np.allclose(simulation.state_vector, _reference_state_vector(operations, qubit_count))

‎test/unit_tests/braket/default_simulator/test_state_vector_simulator.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import numpy as np
2222
import pytest
23+
from scipy.linalg import fractional_matrix_power
2324
from braket.device_schema.simulators import (
2425
GateModelSimulatorDeviceCapabilities,
2526
GateModelSimulatorDeviceParameters,
@@ -1709,6 +1710,43 @@ def test_program_set_validation():
17091710
assert result is not None
17101711

17111712

1713+
_TWO_QUBIT_BASE_MATRICES = {
1714+
"cnot": np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex),
1715+
"swap": np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex),
1716+
"cz": np.diag([1, 1, 1, -1]).astype(complex),
1717+
"iswap": np.array([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]], dtype=complex),
1718+
}
1719+
1720+
1721+
def _openqasm_matrix(matrix):
1722+
return (
1723+
"["
1724+
+ ", ".join("[" + ", ".join(f"{z.real}{z.imag:+}im" for z in row) + "]" for row in matrix)
1725+
+ "]"
1726+
)
1727+
1728+
1729+
@pytest.mark.parametrize("power", [0, 2, 3, -1, -2, 0.5, -0.5, 1.5])
1730+
@pytest.mark.parametrize("gate", list(_TWO_QUBIT_BASE_MATRICES))
1731+
def test_pow_two_qubit_gate_matches_unitary(gate, power):
1732+
preparation = "qubit[2] q;\nry(0.7) q[0];\nry(0.3) q[1];\n"
1733+
powered = f"OPENQASM 3.0;\n{preparation}pow({power}) @ {gate} q[0], q[1];\n"
1734+
matrix = fractional_matrix_power(_TWO_QUBIT_BASE_MATRICES[gate], power)
1735+
unitary = (
1736+
f"OPENQASM 3.0;\n{preparation}"
1737+
f"#pragma braket unitary({_openqasm_matrix(matrix)}) q[0], q[1]\n"
1738+
)
1739+
result_type = "#pragma braket result state_vector\n"
1740+
results = [
1741+
np.asarray(
1742+
StateVectorSimulator()
1743+
.run(OpenQASMProgram(source=source + result_type), shots=0)
1744+
.resultTypes[0]
1745+
.value
1746+
)
1747+
for source in (powered, unitary)
1748+
]
1749+
assert np.allclose(*results)
17121750
def test_output_classical_value_derived_from_unreported_register():
17131751
"""Only the ``int`` output is reported. The bit register it is computed from
17141752
is measured, but is not an output."""

0 commit comments

Comments
 (0)