From 932f0659db748c93cdde96a049ee32895104fe8f Mon Sep 17 00:00:00 2001 From: Zeeshan Ahmed <56979517+Zshan0@users.noreply.github.com> Date: Tue, 24 Aug 2021 06:18:29 +0530 Subject: [PATCH] Added r(theta, phi) gate (#4455) As requested in #3415. Made changes in `_parser.py` and added `r` gate under. I have replicated the format of `u3` and set params to `QasmUGate` according to `r(theta, phi) = u3(theta, phi - pi/2, -phi + pi/2)`. Also wrote a test for the same. --- cirq-core/cirq/contrib/qasm_import/_parser.py | 10 ++++++ .../cirq/contrib/qasm_import/_parser_test.py | 33 ++++++++++++++----- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/cirq-core/cirq/contrib/qasm_import/_parser.py b/cirq-core/cirq/contrib/qasm_import/_parser.py index 122a1edc60e..aa5c19484b2 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser.py @@ -207,6 +207,16 @@ def __init__(self): num_args=1, cirq_gate=(lambda params: QasmUGate(*[p / np.pi for p in params])), ), + 'r': QasmGateStatement( + qasm_gate='r', + num_params=2, + num_args=1, + cirq_gate=( + lambda params: QasmUGate( + params[0] / np.pi, (params[1] / np.pi) - 0.5, (-params[1] / np.pi) + 0.5 + ) + ), + ), 'x': QasmGateStatement(qasm_gate='x', num_params=0, num_args=1, cirq_gate=ops.X), 'y': QasmGateStatement(qasm_gate='y', num_params=0, num_args=1, cirq_gate=ops.Y), 'z': QasmGateStatement(qasm_gate='z', num_params=0, num_args=1, cirq_gate=ops.Z), diff --git a/cirq-core/cirq/contrib/qasm_import/_parser_test.py b/cirq-core/cirq/contrib/qasm_import/_parser_test.py index 722cc460d2a..81dc06f3b69 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser_test.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser_test.py @@ -740,12 +740,36 @@ def test_u3_gate(): assert parsed_qasm.qregs == {'q': 2} +def test_r_gate(): + qasm = """ + OPENQASM 2.0; + include "qelib1.inc"; + qreg q[1]; + r(pi, pi / 2.0) q[0]; +""" + parser = QasmParser() + + q0 = cirq.NamedQubit('q_0') + + expected_circuit = Circuit() + expected_circuit.append(QasmUGate(1.0, 0.0, 0.0)(q0)) + + parsed_qasm = parser.parse(qasm) + + assert parsed_qasm.supportedFormat + assert parsed_qasm.qelib1Include + + ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit) + assert parsed_qasm.qregs == {'q': 1} + + @pytest.mark.parametrize( 'qasm_gate', [ 'id', 'u2', 'u3', + 'r', ] + [g[0] for g in rotation_gates] + [g[0] for g in single_qubit_gates], @@ -766,14 +790,7 @@ def test_standard_single_qubit_gates_wrong_number_of_args(qasm_gate): @pytest.mark.parametrize( ['qasm_gate', 'num_params'], - [ - ['id', 0], - ['u2', 2], - ['u3', 3], - ['rx', 1], - ['ry', 1], - ['rz', 1], - ] + [['id', 0], ['u2', 2], ['u3', 3], ['rx', 1], ['ry', 1], ['rz', 1], ['r', 2]] + [[g[0], 0] for g in single_qubit_gates], ) def test_standard_gates_wrong_params_error(qasm_gate: str, num_params: int):