Exemplo n.º 1
0
def test_protocols():
    for p in [1, 1j, -1]:
        cirq.testing.assert_implements_consistent_protocols(cirq.GlobalPhaseOperation(p))

    np.testing.assert_allclose(
        cirq.unitary(cirq.GlobalPhaseOperation(1j)), np.array([[1j]]), atol=1e-8
    )
Exemplo n.º 2
0
def test_circuit_diagram_tagged_global_phase():
    # Tests global phase operation
    q = cirq.NamedQubit('a')
    global_phase = cirq.GlobalPhaseOperation(
        coefficient=-1.0).with_tags('tag0')

    # Just global phase in a circuit
    assert (cirq.circuit_diagram_info(global_phase,
                                      default='default') == 'default')
    cirq.testing.assert_has_diagram(cirq.Circuit(global_phase),
                                    "\n\nglobal phase:   π['tag0']",
                                    use_unicode_characters=True)
    cirq.testing.assert_has_diagram(cirq.Circuit(global_phase),
                                    "\n\nglobal phase:   π",
                                    use_unicode_characters=True,
                                    include_tags=False)

    expected = cirq.CircuitDiagramInfo(wire_symbols=(),
                                       exponent=1.0,
                                       connected=True,
                                       exponent_qubit_index=None,
                                       auto_exponent_parens=True)

    # Operation with no qubits and returns diagram info with no wire symbols
    class NoWireSymbols(cirq.GlobalPhaseOperation):
        def _circuit_diagram_info_(
                self, args: 'cirq.CircuitDiagramInfoArgs'
        ) -> 'cirq.CircuitDiagramInfo':
            return expected

    no_wire_symbol_op = NoWireSymbols(coefficient=-1.0).with_tags('tag0')
    assert (cirq.circuit_diagram_info(no_wire_symbol_op,
                                      default='default') == expected)
    cirq.testing.assert_has_diagram(cirq.Circuit(no_wire_symbol_op),
                                    "\n\nglobal phase:   π['tag0']",
                                    use_unicode_characters=True)

    # Two global phases in one moment
    tag1 = cirq.GlobalPhaseOperation(coefficient=1j).with_tags('tag1')
    tag2 = cirq.GlobalPhaseOperation(coefficient=1j).with_tags('tag2')
    c = cirq.Circuit([cirq.X(q), tag1, tag2])
    cirq.testing.assert_has_diagram(c,
                                    """\
a: ─────────────X───────────────────

global phase:   π['tag1', 'tag2']""",
                                    use_unicode_characters=True,
                                    precision=2)

    # Two moments with global phase, one with another tagged gate
    c = cirq.Circuit([cirq.X(q).with_tags('x_tag'), tag1])
    c.append(cirq.Moment([cirq.X(q), tag2]))
    cirq.testing.assert_has_diagram(c,
                                    """\
a: ─────────────X['x_tag']─────X──────────────

global phase:   0.5π['tag1']   0.5π['tag2']
""",
                                    use_unicode_characters=True,
                                    include_tags=True)
Exemplo n.º 3
0
def test_init():
    op = cirq.GlobalPhaseOperation(1j)
    assert op.coefficient == 1j
    assert op.qubits == ()
    assert op.with_qubits() is op

    with pytest.raises(ValueError, match='not unitary'):
        _ = cirq.GlobalPhaseOperation(2)
    with pytest.raises(ValueError, match='0 qubits'):
        _ = cirq.GlobalPhaseOperation(1j).with_qubits(cirq.LineQubit(0))
Exemplo n.º 4
0
def get_match_circuit() -> cirq.Circuit:
    qubits = [cirq.LineQubit(i) for i in range(9)]

    g = cirq.CZPowGate(exponent=0.1)
    zz = cirq.ZZPowGate(exponent=0.3)
    px = cirq.PhasedXPowGate(phase_exponent=0.6, exponent=0.2)
    circ = cirq.Circuit(
        [
            cirq.H(qubits[0]),
            cirq.X(qubits[1]),
            cirq.Y(qubits[2]),
            cirq.Z(qubits[3]),
            cirq.S(qubits[4]),
            cirq.CNOT(qubits[1], qubits[4]),
            cirq.T(qubits[3]),
            cirq.CNOT(qubits[6], qubits[8]),
            cirq.I(qubits[5]),
            cirq.XPowGate(exponent=0.1)(qubits[5]),
            cirq.YPowGate(exponent=0.1)(qubits[6]),
            cirq.ZPowGate(exponent=0.1)(qubits[7]),
            g(qubits[2], qubits[3]),
            zz(qubits[3], qubits[4]),
            px(qubits[6]),
            cirq.CZ(qubits[2], qubits[3]),
            cirq.ISWAP(qubits[4], qubits[5]),
            cirq.FSimGate(1.4, 0.7)(qubits[6], qubits[7]),
            cirq.google.SYC(qubits[3], qubits[0]),
            cirq.PhasedISwapPowGate(phase_exponent=0.7, exponent=0.8)(
                qubits[3], qubits[4]),
            cirq.GlobalPhaseOperation(1j),
            cirq.measure_each(*qubits[3:-2]),
        ],
        strategy=InsertStrategy.EARLIEST,
    )
    return circ
Exemplo n.º 5
0
def test_valid_check_raises():
    q0 = cirq.LineQubit(0)
    with pytest.raises(AssertionError,
                       match='Unitaries are completely different'):
        assert_valid_decomp(
            np.eye(4),
            [cirq.X(q0)],
            single_qubit_gate_types=(cirq.XPowGate, ),
        )
    with pytest.raises(AssertionError,
                       match='Unitaries do not match closely enough'):
        assert_valid_decomp(
            np.eye(4),
            [cirq.rx(0.01)(q0)],
            single_qubit_gate_types=(cirq.Rx, ),
        )
    with pytest.raises(
            AssertionError,
            match='Global phase operation was output when it should not'):
        assert_valid_decomp(np.eye(4),
                            [cirq.GlobalPhaseOperation(np.exp(1j * 0.01))])
    with pytest.raises(AssertionError,
                       match='Disallowed operation was output'):
        assert_valid_decomp(
            np.eye(4),
            [cirq.X(q0)],
            single_qubit_gate_types=(cirq.IdentityGate, ),
        )
Exemplo n.º 6
0
def test_is_supported_operation():
    class MultiQubitOp(cirq.Operation):
        """Multi-qubit operation with unitary.

        Used to verify that `is_supported_operation` does not attempt to
        allocate the unitary for multi-qubit operations.
        """
        @property
        def qubits(self):
            return cirq.LineQubit.range(100)

        def with_qubits(self, *new_qubits):
            raise NotImplementedError()

        def _has_unitary_(self):
            return True

        def _unitary_(self):
            assert False

    q1, q2 = cirq.LineQubit.range(2)
    assert cirq.CliffordSimulator.is_supported_operation(cirq.X(q1))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.H(q1))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.CNOT(q1, q2))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.measure(q1))
    assert cirq.CliffordSimulator.is_supported_operation(
        cirq.GlobalPhaseOperation(1j))

    assert not cirq.CliffordSimulator.is_supported_operation(cirq.T(q1))
    assert not cirq.CliffordSimulator.is_supported_operation(MultiQubitOp())
Exemplo n.º 7
0
def test_scalar_operations():
    assert_url_to_circuit_returns('{"cols":[["…"]]}', cirq.Circuit())

    assert_url_to_circuit_returns('{"cols":[["NeGate"]]}',
                                  cirq.Circuit(cirq.GlobalPhaseOperation(-1)))

    assert_url_to_circuit_returns('{"cols":[["i"]]}',
                                  cirq.Circuit(cirq.GlobalPhaseOperation(1j)))

    assert_url_to_circuit_returns('{"cols":[["-i"]]}',
                                  cirq.Circuit(cirq.GlobalPhaseOperation(-1j)))

    assert_url_to_circuit_returns(
        '{"cols":[["√i"]]}', cirq.Circuit(cirq.GlobalPhaseOperation(1j**0.5)))

    assert_url_to_circuit_returns(
        '{"cols":[["√-i"]]}', cirq.Circuit(cirq.GlobalPhaseOperation(1j**-0.5)))
Exemplo n.º 8
0
def test_decompose():
    a, b = cirq.LineQubit.range(2)
    assert cirq.decompose_once(2 * cirq.X(a) * cirq.Z(b), default=None) is None
    assert cirq.decompose_once(1j * cirq.X(a) * cirq.Z(b)) == [
        cirq.GlobalPhaseOperation(1j),
        cirq.X(a), cirq.Z(b)
    ]
    assert cirq.decompose_once(cirq.Y(b) * cirq.Z(a)) == [cirq.Z(a), cirq.Y(b)]
Exemplo n.º 9
0
def test_simulate_global_phase_operation():
    q1, q2 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit([cirq.I(q1), cirq.I(q2), cirq.GlobalPhaseOperation(-1j)])
    simulator = cirq.CliffordSimulator()

    result = simulator.simulate(circuit).final_state.state_vector()

    assert np.allclose(result, [-1j, 0, 0, 0])
Exemplo n.º 10
0
def test_act_on_ch_form(phase):
    state = cirq.StabilizerStateChForm(0)
    args = cirq.ActOnStabilizerCHFormArgs(
        state,
        [],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(cirq.GlobalPhaseOperation(phase), args, allow_decompose=False)
    assert state.state_vector() == [[phase]]
Exemplo n.º 11
0
def test_is_supported_operation():
    q1, q2 = cirq.LineQubit.range(2)
    assert cirq.CliffordSimulator.is_supported_operation(cirq.X(q1))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.H(q1))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.CNOT(q1, q2))
    assert cirq.CliffordSimulator.is_supported_operation(cirq.measure(q1))
    assert cirq.CliffordSimulator.is_supported_operation(
        cirq.GlobalPhaseOperation(1j))

    assert not cirq.CliffordSimulator.is_supported_operation(cirq.T(q1))
Exemplo n.º 12
0
 def do_phase_flip(self, controls: 'qp.QubitIntersection'):
     if controls.bit:
         if len(controls.qubits):
             g = cirq.Z
             for _ in range(len(controls.qubits) - 1):
                 g = cirq.ControlledGate(g)
             ctrls = [cirq.NamedQubit(str(q)) for q in controls.qubits]
             self.circuit.append(g(*ctrls),
                                 cirq.InsertStrategy.NEW_THEN_INLINE)
         else:
             self.circuit.append(cirq.GlobalPhaseOperation(-1), cirq.InsertStrategy.NEW_THEN_INLINE)
Exemplo n.º 13
0
def test_ideal_sqrt_iswap_simulates_correctly_invalid_circuit_fails() -> None:
    engine_simulator = PhasedFSimEngineSimulator.create_with_ideal_sqrt_iswap()

    with pytest.raises(IncompatibleMomentError):
        a, b = cirq.LineQubit.range(2)
        circuit = cirq.Circuit([cirq.CZ.on(a, b)])
        engine_simulator.simulate(circuit)

    with pytest.raises(IncompatibleMomentError):
        circuit = cirq.Circuit(cirq.GlobalPhaseOperation(coefficient=1.0))
        engine_simulator.simulate(circuit)
Exemplo n.º 14
0
def test_tagged_measurement():
    assert not cirq.is_measurement(cirq.GlobalPhaseOperation(coefficient=-1.0).with_tags('tag0'))

    a = cirq.LineQubit(0)
    op = cirq.measure(a, key='m').with_tags('tag')
    assert cirq.is_measurement(op)

    remap_op = cirq.with_measurement_key_mapping(op, {'m': 'k'})
    assert remap_op.tags == ('tag',)
    assert cirq.is_measurement(remap_op)
    assert cirq.measurement_keys(remap_op) == {'k'}
    assert cirq.with_measurement_key_mapping(op, {'x': 'k'}) == op
Exemplo n.º 15
0
 def get_ops(use_circuit_op, use_global_phase):
     q = cirq.LineQubit.range(3)
     yield [CustomX(q[0]).with_tags('custom tags'), CustomX(q[1]) ** 2, CustomX(q[2]) ** 3]
     yield [CustomX(q[0]) ** 0.5, cirq.testing.TwoQubitGate()(*q[:2])]
     if use_circuit_op:
         circuit_op = cirq.CircuitOperation(
             cirq.FrozenCircuit(get_ops(False, False)), repetitions=10
         ).with_tags('circuit op tags')
         recursive_circuit_op = cirq.CircuitOperation(
             cirq.FrozenCircuit([circuit_op, CustomX(q[2]) ** 0.5]),
             repetitions=10,
             qubit_map={q[0]: q[1], q[1]: q[2], q[2]: q[0]},
         )
         yield [circuit_op, recursive_circuit_op]
     if use_global_phase:
         yield cirq.GlobalPhaseOperation(1j)
Exemplo n.º 16
0
def cphase_to_sqrt_iswap(a, b, turns):
    """Implement a C-Phase gate using two sqrt ISWAP gates and single-qubit
    operations. The circuit is equivalent to cirq.CZPowGate(exponent=turns).

    Output unitary:
    [1   0   0   0],
    [0   1   0   0],
    [0   0   1   0],
    [0   0   0   e^{i turns pi}].

    Args:
        a: the first qubit
        b: the second qubit
        turns: Exponent specifying the evolution time in number of rotations.
    """
    theta = (turns % 2) * np.pi
    if 0 <= theta <= np.pi:
        sign = 1.0
        theta_prime = theta
    elif np.pi < theta < 2 * np.pi:
        sign = -1.0
        theta_prime = 2 * np.pi - theta

    if np.isclose(theta, np.pi):
        # If we are close to pi, just set values manually to avoid possible
        # numerical errors with arcsin of greater than 1.0 (Ahem, Windows).
        phi = np.pi / 2
        xi = np.pi / 2
    else:
        phi = np.arcsin(np.sqrt(2) * np.sin(theta_prime / 4))
        xi = np.arctan(np.tan(phi) / np.sqrt(2))

    yield cirq.rz(sign * 0.5 * theta_prime).on(a)
    yield cirq.rz(sign * 0.5 * theta_prime).on(b)
    yield cirq.rx(xi).on(a)
    yield cirq.X(b)**(-sign * 0.5)
    yield SQRT_ISWAP_INV(a, b)
    yield cirq.rx(-2 * phi).on(a)
    yield SQRT_ISWAP(a, b)

    yield cirq.rx(xi).on(a)
    yield cirq.X(b)**(sign * 0.5)
    # Corrects global phase
    yield cirq.GlobalPhaseOperation(np.exp(sign * theta_prime * 0.25j))
Exemplo n.º 17
0
def test_make_floquet_request_for_moment_fails_for_non_gate_operation(
) -> None:
    moment = cirq.Moment(cirq.GlobalPhaseOperation(coefficient=1.0))
    with pytest.raises(workflow.IncompatibleMomentError):
        workflow.prepare_floquet_characterization_for_moment(
            moment, WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION)
Exemplo n.º 18
0

@pytest.mark.parametrize(
    'gate_family, gates_to_check',
    [
        (
            cirq.GateFamily(CustomXPowGate),
            [
                (CustomX, True),
                (CustomX ** 0.5, True),
                (CustomX ** sympy.Symbol('theta'), True),
                (CustomXPowGate(exponent=0.25, global_shift=0.15), True),
                (cirq.SingleQubitGate(), False),
                (cirq.X ** 0.5, False),
                (None, False),
                (cirq.GlobalPhaseOperation(1j), False),
            ],
        ),
        (
            cirq.GateFamily(CustomX),
            [
                (CustomX, True),
                (CustomXPowGate(exponent=1, global_shift=0.15), True),
                (CustomX ** 2, False),
                (CustomX ** 3, True),
                (CustomX ** sympy.Symbol('theta'), False),
                (None, False),
                (cirq.GlobalPhaseOperation(1j), False),
            ],
        ),
        (
Exemplo n.º 19
0
def test_act_on_ch_form(phase):
    state = cirq.StabilizerStateChForm(0)
    args = cirq.ActOnStabilizerCHFormArgs(state, [])
    cirq.act_on(cirq.GlobalPhaseOperation(phase), args, allow_decompose=False)
    assert state.state_vector() == [[phase]]
Exemplo n.º 20
0
def test_prepare_characterization_for_moment_fails_for_non_gate_operation(
        options):
    moment = cirq.Moment(cirq.GlobalPhaseOperation(coefficient=1.0))
    with pytest.raises(workflow.IncompatibleMomentError):
        workflow.prepare_characterization_for_moment(moment, options)
Exemplo n.º 21
0
def test_diagram():
    a, b = cirq.LineQubit.range(2)
    x, y = cirq.LineQubit.range(10, 12)

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.CNOT(a, x),
                cirq.CNOT(b, y),
                cirq.GlobalPhaseOperation(-1),
            ])
        ]),
        """
                ┌──┐
0: ──────────────@─────
                 │
1: ──────────────┼@────
                 ││
10: ─────────────X┼────
                  │
11: ──────────────X────

global phase:    π
                └──┘
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.CNOT(a, x),
                cirq.CNOT(b, y),
                cirq.GlobalPhaseOperation(-1),
                cirq.GlobalPhaseOperation(-1),
            ]),
        ]),
        """
                ┌──┐
0: ──────────────@─────
                 │
1: ──────────────┼@────
                 ││
10: ─────────────X┼────
                  │
11: ──────────────X────

global phase:
                └──┘
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.CNOT(a, x),
                cirq.CNOT(b, y),
                cirq.GlobalPhaseOperation(-1),
                cirq.GlobalPhaseOperation(-1),
            ]),
            cirq.Moment([
                cirq.GlobalPhaseOperation(1j),
            ]),
            cirq.Moment([
                cirq.X(a),
            ]),
        ]),
        """
                ┌──┐
0: ──────────────@────────────X───
                 │
1: ──────────────┼@───────────────
                 ││
10: ─────────────X┼───────────────
                  │
11: ──────────────X───────────────

global phase:          0.5π
                └──┘
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.X(a),
            ]),
            cirq.Moment([
                cirq.GlobalPhaseOperation(-1j),
            ]),
        ]),
        """
0: ─────────────X───────────

global phase:       -0.5π
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.X(a),
                cirq.GlobalPhaseOperation(np.exp(1j)),
            ]),
        ]),
        """
0: ─────────────X────────

global phase:   0.318π
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.X(a),
                cirq.GlobalPhaseOperation(np.exp(1j)),
            ]),
        ]),
        """
0: ─────────────X──────────

global phase:   0.31831π
        """,
        precision=5,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.X(a),
                cirq.GlobalPhaseOperation(1j),
            ]),
            cirq.Moment([
                cirq.GlobalPhaseOperation(-1j),
            ]),
        ]),
        """
0: -------------X----------------

global phase:   0.5pi   -0.5pi
        """,
        use_unicode_characters=False,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit([
            cirq.Moment([
                cirq.GlobalPhaseOperation(-1j),
            ]),
        ]),
        """
global phase:   -0.5π
        """,
    )
Exemplo n.º 22
0
def test_repr():
    op = cirq.GlobalPhaseOperation(1j)
    cirq.testing.assert_equivalent_repr(op)
Exemplo n.º 23
0
def test_str():
    assert str(cirq.GlobalPhaseOperation(1j)) == '1j'
Exemplo n.º 24
0
def test_validate_operation_no_gate():
    device = ionq.IonQAPIDevice(qubits=[])
    with pytest.raises(ValueError, match='no gates'):
        device.validate_operation(cirq.GlobalPhaseOperation(1j))
Exemplo n.º 25
0
def test_act_on_tableau(phase):
    original_tableau = cirq.CliffordTableau(0)
    args = cirq.ActOnCliffordTableauArgs(original_tableau.copy(), [],
                                         np.random.RandomState(), {})
    cirq.act_on(cirq.GlobalPhaseOperation(phase), args, allow_decompose=False)
    assert args.tableau == original_tableau
Exemplo n.º 26
0
def test_global_phase_op_json_dict():
    assert cirq.GlobalPhaseOperation(-1j)._json_dict_() == {
        'cirq_type': 'GlobalPhaseOperation',
        'coefficient': -1j,
    }
Exemplo n.º 27
0
def test_string_format():
    x, y, z = cirq.LineQubit.range(3)

    fc0 = cirq.FrozenCircuit()
    op0 = cirq.CircuitOperation(fc0)
    assert (
        str(op0)
        == f"""\
{op0.circuit.diagram_name()}:
[                         ]"""
    )

    fc0_global_phase_inner = cirq.FrozenCircuit(
        cirq.GlobalPhaseOperation(1j), cirq.GlobalPhaseOperation(1j)
    )
    op0_global_phase_inner = cirq.CircuitOperation(fc0_global_phase_inner)
    fc0_global_phase_outer = cirq.FrozenCircuit(
        op0_global_phase_inner, cirq.GlobalPhaseOperation(1j)
    )
    op0_global_phase_outer = cirq.CircuitOperation(fc0_global_phase_outer)
    assert (
        str(op0_global_phase_outer)
        == f"""\
{op0_global_phase_outer.circuit.diagram_name()}:
[                         ]
[                         ]
[ global phase:   -0.5π   ]"""
    )

    fc1 = cirq.FrozenCircuit(cirq.X(x), cirq.H(y), cirq.CX(y, z), cirq.measure(x, y, z, key='m'))
    op1 = cirq.CircuitOperation(fc1)
    assert (
        str(op1)
        == f"""\
{op1.circuit.diagram_name()}:
[ 0: ───X───────M('m')─── ]
[               │         ]
[ 1: ───H───@───M──────── ]
[           │   │         ]
[ 2: ───────X───M──────── ]"""
    )
    assert (
        repr(op1)
        == f"""\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.H(cirq.LineQubit(1)),
        ),
        cirq.Moment(
            cirq.CNOT(cirq.LineQubit(1), cirq.LineQubit(2)),
        ),
        cirq.Moment(
            cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1), cirq.LineQubit(2), key='m'),
        ),
    ]),
)"""
    )

    fc2 = cirq.FrozenCircuit(cirq.X(x), cirq.H(y), cirq.CX(y, x))
    op2 = cirq.CircuitOperation(
        circuit=fc2,
        qubit_map=({y: z}),
        repetitions=3,
        parent_path=('outer', 'inner'),
        repetition_ids=['a', 'b', 'c'],
    )
    assert (
        str(op2)
        == f"""\
{op2.circuit.diagram_name()}:
[ 0: ───X───X───          ]
[           │             ]
[ 1: ───H───@───          ](qubit_map={{1: 2}}, parent_path=('outer', 'inner'),\
 repetition_ids=['a', 'b', 'c'])"""
    )
    assert (
        repr(op2)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.H(cirq.LineQubit(1)),
        ),
        cirq.Moment(
            cirq.CNOT(cirq.LineQubit(1), cirq.LineQubit(0)),
        ),
    ]),
    repetitions=3,
    qubit_map={cirq.LineQubit(1): cirq.LineQubit(2)},
    parent_path=('outer', 'inner'),
    repetition_ids=['a', 'b', 'c'],
)"""
    )

    fc3 = cirq.FrozenCircuit(
        cirq.X(x) ** sympy.Symbol('b'),
        cirq.measure(x, key='m'),
    )
    op3 = cirq.CircuitOperation(
        circuit=fc3,
        qubit_map={x: y},
        measurement_key_map={'m': 'p'},
        param_resolver={sympy.Symbol('b'): 2},
    )
    indented_fc3_repr = repr(fc3).replace('\n', '\n    ')
    assert (
        str(op3)
        == f"""\
{op3.circuit.diagram_name()}:
[ 0: ───X^b───M('m')───   ](qubit_map={{0: 1}}, \
key_map={{m: p}}, params={{b: 2}})"""
    )
    assert (
        repr(op3)
        == f"""\
cirq.CircuitOperation(
    circuit={indented_fc3_repr},
    qubit_map={{cirq.LineQubit(0): cirq.LineQubit(1)}},
    measurement_key_map={{'m': 'p'}},
    param_resolver=cirq.ParamResolver({{sympy.Symbol('b'): 2}}),
)"""
    )

    fc4 = cirq.FrozenCircuit(cirq.X(y))
    op4 = cirq.CircuitOperation(fc4)
    fc5 = cirq.FrozenCircuit(cirq.X(x), op4)
    op5 = cirq.CircuitOperation(fc5)
    assert (
        repr(op5)
        == f"""\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.CircuitOperation(
                circuit=cirq.FrozenCircuit([
                    cirq.Moment(
                        cirq.X(cirq.LineQubit(1)),
                    ),
                ]),
            ),
        ),
    ]),
)"""
    )
Exemplo n.º 28
0
def test_serialize_non_gate_op_invalid():
    q0 = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.X(q0), cirq.GlobalPhaseOperation(1j))
    serializer = ionq.Serializer()
    with pytest.raises(ValueError, match='GlobalPhaseOperation'):
        _ = serializer.serialize(circuit)
Exemplo n.º 29
0
def test_zeta_chi_gamma_calibration_for_moments_invalid_argument_fails(
) -> None:
    a, b, c = cirq.LineQubit.range(3)

    with pytest.raises(ValueError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit(), [1])
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, [])

    with pytest.raises(ValueError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit(SQRT_ISWAP_GATE.on(a, b)), [None])
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, [])

    with pytest.raises(ValueError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit(SQRT_ISWAP_GATE.on(a, b)), [0])
        characterizations = [
            PhasedFSimCalibrationResult(
                parameters={},
                gate=SQRT_ISWAP_GATE,
                options=WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION,
            )
        ]
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, characterizations)

    with pytest.raises(workflow.IncompatibleMomentError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit(cirq.GlobalPhaseOperation(coefficient=1.0)), [None])
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, [])

    with pytest.raises(workflow.IncompatibleMomentError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit(cirq.CZ.on(a, b)), [None])
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, [])

    with pytest.raises(workflow.IncompatibleMomentError):
        circuit_with_calibration = workflow.CircuitWithCalibration(
            cirq.Circuit([SQRT_ISWAP_GATE.on(a, b),
                          cirq.Z.on(c)]), [0])
        characterizations = [
            PhasedFSimCalibrationResult(
                parameters={
                    (a, b):
                    PhasedFSimCharacterization(theta=0.1,
                                               zeta=0.2,
                                               chi=0.3,
                                               gamma=0.4,
                                               phi=0.5)
                },
                gate=SQRT_ISWAP_GATE,
                options=WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION,
            )
        ]
        workflow.make_zeta_chi_gamma_compensation_for_moments(
            circuit_with_calibration, characterizations)
Exemplo n.º 30
0
 cirq.FREDKIN,
 'FSimGate':
 cirq.FSimGate(theta=0.123, phi=.456),
 'Foxtail':
 cirq.google.Foxtail,
 'GateOperation': [
     cirq.CCNOT(*cirq.LineQubit.range(3)),
     cirq.CCZ(*cirq.LineQubit.range(3)),
     cirq.CNOT(*cirq.LineQubit.range(2)),
     cirq.CSWAP(*cirq.LineQubit.range(3)),
     cirq.CZ(*cirq.LineQubit.range(2))
 ],
 'GeneralizedAmplitudeDampingChannel':
 cirq.GeneralizedAmplitudeDampingChannel(0.1, 0.2),
 'GlobalPhaseOperation':
 cirq.GlobalPhaseOperation(-1j),
 'GridQubit':
 cirq.GridQubit(10, 11),
 'H':
 cirq.H,
 'HPowGate': [cirq.HPowGate(exponent=-8), cirq.H**0.123],
 'I':
 cirq.I,
 'ISWAP':
 cirq.ISWAP,
 'ISwapPowGate': [cirq.ISwapPowGate(exponent=-8), cirq.ISWAP**0.123],
 'IdentityGate': [
     cirq.I,
     cirq.IdentityGate(num_qubits=5),
     cirq.IdentityGate(num_qubits=5, qid_shape=(3, ) * 5)
 ],