Beispiel #1
0
def test_device_deprecated():
    q = cirq.LineQubit(0)
    a = cirq.FrozenCircuit(cirq.X(q))
    with cirq.testing.assert_deprecated(
            cirq.circuits.circuit._DEVICE_DEP_MESSAGE, deadline='v0.15'):
        _ = a.device
Beispiel #2
0
 def wrap(*ops):
     return cirq.CircuitOperation(cirq.FrozenCircuit(*ops))
Beispiel #3
0
def test_mapped_circuit_preserves_moments():
    q0, q1 = cirq.LineQubit.range(2)
    fc = cirq.FrozenCircuit(cirq.Moment(cirq.X(q0)), cirq.Moment(cirq.X(q1)))
    op = cirq.CircuitOperation(fc)
    assert op.mapped_circuit() == fc
    assert op.repeat(3).mapped_circuit(deep=True) == fc * 3
def test_decompose_nested():
    a, b, c, d = cirq.LineQubit.range(4)
    exp1 = sympy.Symbol('exp1')
    exp_half = sympy.Symbol('exp_half')
    exp_one = sympy.Symbol('exp_one')
    exp_two = sympy.Symbol('exp_two')
    circuit1 = cirq.FrozenCircuit(cirq.X(a)**exp1, cirq.measure(a, key='m1'))
    op1 = cirq.CircuitOperation(circuit1)
    circuit2 = cirq.FrozenCircuit(
        op1.with_qubits(a).with_measurement_key_mapping({'m1': 'ma'}),
        op1.with_qubits(b).with_measurement_key_mapping({'m1': 'mb'}),
        op1.with_qubits(c).with_measurement_key_mapping({'m1': 'mc'}),
        op1.with_qubits(d).with_measurement_key_mapping({'m1': 'md'}),
    )
    op2 = cirq.CircuitOperation(circuit2)
    circuit3 = cirq.FrozenCircuit(
        op2.with_params({exp1: exp_half}),
        op2.with_params({exp1: exp_one}),
        op2.with_params({exp1: exp_two}),
    )
    op3 = cirq.CircuitOperation(circuit3)

    final_op = op3.with_params({exp_half: 0.5, exp_one: 1.0, exp_two: 2.0})

    expected_circuit1 = cirq.Circuit(
        op2.with_params({
            exp1: 0.5,
            exp_half: 0.5,
            exp_one: 1.0,
            exp_two: 2.0
        }),
        op2.with_params({
            exp1: 1.0,
            exp_half: 0.5,
            exp_one: 1.0,
            exp_two: 2.0
        }),
        op2.with_params({
            exp1: 2.0,
            exp_half: 0.5,
            exp_one: 1.0,
            exp_two: 2.0
        }),
    )

    result_ops1 = cirq.decompose_once(final_op)
    assert cirq.Circuit(result_ops1) == expected_circuit1

    expected_circuit = cirq.Circuit(
        cirq.X(a)**0.5,
        cirq.measure(a, key='ma'),
        cirq.X(b)**0.5,
        cirq.measure(b, key='mb'),
        cirq.X(c)**0.5,
        cirq.measure(c, key='mc'),
        cirq.X(d)**0.5,
        cirq.measure(d, key='md'),
        cirq.X(a)**1.0,
        cirq.measure(a, key='ma'),
        cirq.X(b)**1.0,
        cirq.measure(b, key='mb'),
        cirq.X(c)**1.0,
        cirq.measure(c, key='mc'),
        cirq.X(d)**1.0,
        cirq.measure(d, key='md'),
        cirq.X(a)**2.0,
        cirq.measure(a, key='ma'),
        cirq.X(b)**2.0,
        cirq.measure(b, key='mb'),
        cirq.X(c)**2.0,
        cirq.measure(c, key='mc'),
        cirq.X(d)**2.0,
        cirq.measure(d, key='md'),
    )
    assert cirq.Circuit(cirq.decompose(final_op)) == expected_circuit
    # Verify that mapped_circuit gives the same operations.
    assert final_op.mapped_circuit(deep=True) == expected_circuit
def default_circuit():
    return cirq.FrozenCircuit(
        cirq.X(cirq.GridQubit(1, 1))**sympy.Symbol('k'),
        cirq.measure(cirq.GridQubit(1, 1), key='m'),
    )
Beispiel #6
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.serialization_key()}:
[                         ]""")

    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.serialization_key()}:
[ 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,
                                repetition_ids=['a', 'b', 'c'])
    assert (str(op2) == f"""\
{op2.circuit.serialization_key()}:
[ 0: ───X───X───          ]
[           │             ]
[ 1: ───H───@───          ](qubit_map={{1: 2}}, 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)},
    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.serialization_key()}:
[ 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)),
                    ),
                ]),
            ),
        ),
    ]),
)""")
Beispiel #7
0
from google.protobuf import any_pb2
from google.protobuf.text_format import Merge

import cirq
import cirq_google
import cirq_google as cg
from cirq_google.api import v1, v2
from cirq_google.engine.engine import EngineContext
from cirq_google.engine.client.quantum_v1alpha1 import types as qtypes

_CIRCUIT = cirq.Circuit(
    cirq.X(cirq.GridQubit(5, 2))**0.5,
    cirq.measure(cirq.GridQubit(5, 2), key='result'))

_CIRCUIT2 = cirq.FrozenCircuit(
    cirq.Y(cirq.GridQubit(5, 2))**0.5,
    cirq.measure(cirq.GridQubit(5, 2), key='result'))


def _to_any(proto):
    any_proto = qtypes.any_pb2.Any()
    any_proto.Pack(proto)
    return any_proto


def _to_timestamp(json_string):
    timestamp_proto = qtypes.timestamp_pb2.Timestamp()
    timestamp_proto.FromJsonString(json_string)
    return timestamp_proto

def test_subcircuit_entanglement_causes_join():
    args = create_container(qs2)
    assert len(set(args.values())) == 3
    args.apply_operation(cirq.CircuitOperation(cirq.FrozenCircuit(cirq.CNOT(q0, q1))))
    assert len(set(args.values())) == 2
    assert args[q0] is args[q1]
Beispiel #9
0
def test_merge_k_qubit_unitaries_deep():
    q = cirq.LineQubit.range(2)
    h_cz_y = [cirq.H(q[0]), cirq.CZ(*q), cirq.Y(q[1])]
    c_orig = cirq.Circuit(
        h_cz_y,
        cirq.Moment(cirq.X(q[0]).with_tags("ignore"), cirq.Y(q[1])),
        cirq.CircuitOperation(
            cirq.FrozenCircuit(h_cz_y)).repeat(6).with_tags("ignore"),
        [cirq.CNOT(*q), cirq.CNOT(*q)],
        cirq.CircuitOperation(cirq.FrozenCircuit(h_cz_y)).repeat(4),
        [cirq.CNOT(*q), cirq.CZ(*q), cirq.CNOT(*q)],
        cirq.CircuitOperation(
            cirq.FrozenCircuit(h_cz_y)).repeat(5).with_tags("preserve_tag"),
    )

    def _wrap_in_cop(ops: cirq.OP_TREE, tag: str):
        return cirq.CircuitOperation(cirq.FrozenCircuit(ops)).with_tags(tag)

    c_expected = cirq.Circuit(
        _wrap_in_cop([h_cz_y, cirq.Y(q[1])], '1'),
        cirq.Moment(cirq.X(q[0]).with_tags("ignore")),
        cirq.CircuitOperation(
            cirq.FrozenCircuit(h_cz_y)).repeat(6).with_tags("ignore"),
        _wrap_in_cop([cirq.CNOT(*q), cirq.CNOT(*q)], '2'),
        cirq.CircuitOperation(cirq.FrozenCircuit(_wrap_in_cop(h_cz_y,
                                                              '3'))).repeat(4),
        _wrap_in_cop([cirq.CNOT(*q), cirq.CZ(*q),
                      cirq.CNOT(*q)], '4'),
        cirq.CircuitOperation(cirq.FrozenCircuit(_wrap_in_cop(
            h_cz_y, '5'))).repeat(5).with_tags("preserve_tag"),
        strategy=cirq.InsertStrategy.NEW,
    )

    component_id = 0

    def rewriter_merge_to_circuit_op(
            op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
        nonlocal component_id
        component_id = component_id + 1
        return op.with_tags(f'{component_id}')

    context = cirq.TransformerContext(tags_to_ignore=("ignore", ), deep=True)
    c_new = cirq.merge_k_qubit_unitaries(c_orig,
                                         k=2,
                                         context=context,
                                         rewriter=rewriter_merge_to_circuit_op)
    cirq.testing.assert_same_circuits(c_new, c_expected)

    def _wrap_in_matrix_gate(ops: cirq.OP_TREE):
        op = _wrap_in_cop(ops, 'temp')
        return cirq.MatrixGate(cirq.unitary(op)).on(*op.qubits)

    c_expected_matrix = cirq.Circuit(
        _wrap_in_matrix_gate([h_cz_y, cirq.Y(q[1])]),
        cirq.Moment(cirq.X(q[0]).with_tags("ignore")),
        cirq.CircuitOperation(
            cirq.FrozenCircuit(h_cz_y)).repeat(6).with_tags("ignore"),
        _wrap_in_matrix_gate([cirq.CNOT(*q), cirq.CNOT(*q)]),
        cirq.CircuitOperation(cirq.FrozenCircuit(
            _wrap_in_matrix_gate(h_cz_y))).repeat(4),
        _wrap_in_matrix_gate([cirq.CNOT(*q),
                              cirq.CZ(*q),
                              cirq.CNOT(*q)]),
        cirq.CircuitOperation(cirq.FrozenCircuit(
            _wrap_in_matrix_gate(h_cz_y))).repeat(5).with_tags("preserve_tag"),
        strategy=cirq.InsertStrategy.NEW,
    )
    c_new_matrix = cirq.merge_k_qubit_unitaries(c_orig, k=2, context=context)
    cirq.testing.assert_same_circuits(c_new_matrix, c_expected_matrix)
Beispiel #10
0
def test_serialize_non_gate_op_invalid():
    q0 = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.X(q0), cirq.CircuitOperation(cirq.FrozenCircuit()))
    serializer = ionq.Serializer()
    with pytest.raises(ValueError, match='CircuitOperation'):
        _ = serializer.serialize(circuit)
def test_subcircuit_identity_does_not_join():
    args = create_container(qs2)
    assert len(set(args.values())) == 3
    args.apply_operation(cirq.CircuitOperation(cirq.FrozenCircuit(cirq.IdentityGate(2)(q0, q1))))
    assert len(set(args.values())) == 3
    assert args[q0] is not args[q1]
def test_immutable():
    q = cirq.LineQubit(0)
    c = cirq.FrozenCircuit(cirq.X(q), cirq.H(q))

    with pytest.raises(AttributeError, match="can't set attribute"):
        c.moments = (cirq.Moment(cirq.H(q)), cirq.Moment(cirq.X(q)))
def test_expands_composite_recursively_preserving_structur():
    q = cirq.LineQubit.range(2)
    c_nested = cirq.FrozenCircuit(cirq.SWAP(*q[:2]),
                                  cirq.SWAP(*q[:2]).with_tags("ignore"),
                                  cirq.SWAP(*q[:2]))
    c_nested_expanded = cirq.FrozenCircuit(
        [cirq.CNOT(*q), cirq.CNOT(*q[::-1]),
         cirq.CNOT(*q)],
        cirq.SWAP(*q[:2]).with_tags("ignore"),
        [cirq.CNOT(*q), cirq.CNOT(*q[::-1]),
         cirq.CNOT(*q)],
    )
    c_orig = cirq.Circuit(
        c_nested,
        cirq.CircuitOperation(
            cirq.FrozenCircuit(
                c_nested,
                cirq.CircuitOperation(c_nested).repeat(5).with_tags("ignore"),
                cirq.CircuitOperation(c_nested).repeat(6).with_tags(
                    "preserve_tag"),
                cirq.CircuitOperation(c_nested).repeat(7),
                c_nested,
            )).repeat(4).with_tags("ignore"),
        c_nested,
        cirq.CircuitOperation(
            cirq.FrozenCircuit(
                c_nested,
                cirq.CircuitOperation(c_nested).repeat(5).with_tags("ignore"),
                cirq.CircuitOperation(c_nested).repeat(6).with_tags(
                    "preserve_tag"),
                cirq.CircuitOperation(c_nested).repeat(7),
                c_nested,
            )).repeat(5).with_tags("preserve_tag"),
        c_nested,
    )
    c_expected = cirq.Circuit(
        c_nested_expanded,
        cirq.CircuitOperation(
            cirq.FrozenCircuit(
                c_nested,
                cirq.CircuitOperation(c_nested).repeat(5).with_tags("ignore"),
                cirq.CircuitOperation(c_nested).repeat(6).with_tags(
                    "preserve_tag"),
                cirq.CircuitOperation(c_nested).repeat(7),
                c_nested,
            )).repeat(4).with_tags("ignore"),
        c_nested_expanded,
        cirq.CircuitOperation(
            cirq.FrozenCircuit(
                c_nested_expanded,
                cirq.CircuitOperation(c_nested).repeat(5).with_tags("ignore"),
                cirq.CircuitOperation(c_nested_expanded).repeat(6).with_tags(
                    "preserve_tag"),
                cirq.CircuitOperation(c_nested_expanded).repeat(7),
                c_nested_expanded,
            )).repeat(5).with_tags("preserve_tag"),
        c_nested_expanded,
    )

    context = cirq.TransformerContext(tags_to_ignore=["ignore"], deep=True)
    c_expanded = cirq.expand_composite(
        c_orig, no_decomp=lambda op: op.gate == cirq.CNOT, context=context)
    cirq.testing.assert_same_circuits(c_expanded, c_expected)
Beispiel #14
0
    assert sum(1 for _ in circuit.findall_operations(lambda e: len(e.qubits) > 2)) <= 6
    circuit.append(cirq.I.on_each(*target_op.qubits))
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(circuit), cirq.unitary(target_op), atol=1e-7
    )


theta = sympy.Symbol('theta')
all_exps = np.linspace(0, 1, 10)
q = cirq.LineQubit.range(2)


@pytest.mark.parametrize(
    'op, theta_range',
    [
        (cirq.CircuitOperation(cirq.FrozenCircuit(cirq.SWAP(*q), cirq.ZZ(*q) ** theta)), all_exps),
        (cirq.CircuitOperation(cirq.FrozenCircuit(cirq.ZZ(*q) ** theta, cirq.SWAP(*q))), all_exps),
        (cirq.PhasedISwapPowGate(exponent=1, phase_exponent=theta).on(*q), all_exps),
        (cirq.PhasedISwapPowGate(exponent=theta, phase_exponent=0.25).on(*q), all_exps),
        (cirq.CNOT(*q) ** theta, all_exps),
        (cirq.CZ(*q) ** theta, all_exps),
        (cirq.ZZ(*q) ** theta, all_exps),
        (cirq.SWAP(*q) ** theta, [1]),
        (cirq.ISWAP(*q) ** theta, [1]),
    ],
)
def test_known_two_qubit_op_decomposition(op, theta_range):
    for theta_val in theta_range:
        op_resolved = cirq.resolve_parameters(op, {'theta': theta_val}, recursive=False)
        known_2q_circuit = cirq.Circuit(cg.known_2q_op_to_sycamore_operations(op_resolved))
        matrix_2q_circuit = cirq.Circuit(
Beispiel #15
0
        gateset=cirq_google.SycamoreTargetGateset(
            tabulation=sycamore_tabulation))
    u1 = cirq.unitary(circuit)
    u2 = cirq.unitary(converted_circuit)
    overlap = abs(np.trace(u1.conj().T @ u2))
    assert np.isclose(overlap, 4.0, 0.1)


q = cirq.GridQubit.rect(1, 3)
matrix_gate = cirq.MatrixGate(cirq.testing.random_unitary(2))


@pytest.mark.parametrize(
    'op',
    [
        cirq.CircuitOperation(cirq.FrozenCircuit(matrix_gate(q[0]))),
        matrix_gate(q[0]),
        matrix_gate(q[0]).with_tags('test_tags'),
        matrix_gate(q[0]).controlled_by(q[1]),
        matrix_gate(q[0]).controlled_by(q[1]).with_tags('test_tags'),
        matrix_gate(q[0]).with_tags('test_tags').controlled_by(q[1]),
    ],
)
def test_supported_operation(op):
    circuit = cirq.Circuit(op)
    converted_circuit = cirq.optimize_for_target_gateset(
        circuit, gateset=cirq_google.SycamoreTargetGateset())
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(
        circuit, converted_circuit, atol=1e-8)
    multi_qubit_ops = [
        e for e in converted_circuit.all_operations() if len(e.qubits) > 1
Beispiel #16
0
 def _wrap_in_cop(ops: cirq.OP_TREE, tag: str):
     return cirq.CircuitOperation(cirq.FrozenCircuit(ops)).with_tags(tag)
Beispiel #17
0
def test_parameterized_repeat_side_effects():
    q = cirq.LineQubit(0)
    op = cirq.CircuitOperation(
        cirq.FrozenCircuit(
            cirq.X(q).with_classical_controls('c'), cirq.measure(q, key='m')),
        repetitions=sympy.Symbol('a'),
    )

    # Control keys can be calculated because they only "lift" if there's a matching
    # measurement, in which case they're not returned here.
    assert cirq.control_keys(op) == {cirq.MeasurementKey('c')}

    # "local" params do not bind to the repetition param.
    assert cirq.parameter_names(op.with_params({'a': 1})) == {'a'}

    # Check errors that require unrolling the circuit.
    with pytest.raises(
            ValueError,
            match='Cannot unroll circuit due to nondeterministic repetitions'):
        cirq.measurement_key_objs(op)
    with pytest.raises(
            ValueError,
            match='Cannot unroll circuit due to nondeterministic repetitions'):
        cirq.measurement_key_names(op)
    with pytest.raises(
            ValueError,
            match='Cannot unroll circuit due to nondeterministic repetitions'):
        op.mapped_circuit()
    with pytest.raises(
            ValueError,
            match='Cannot unroll circuit due to nondeterministic repetitions'):
        cirq.decompose(op)

    # Not compatible with repetition ids
    with pytest.raises(ValueError,
                       match='repetition ids with parameterized repetitions'):
        op.with_repetition_ids(['x', 'y'])
    with pytest.raises(ValueError,
                       match='repetition ids with parameterized repetitions'):
        op.repeat(repetition_ids=['x', 'y'])

    # TODO(daxfohl): This should work, but likely requires a new protocol that returns *just* the
    # name of the measurement keys. (measurement_key_names returns the full serialized string).
    with pytest.raises(
            ValueError,
            match='Cannot unroll circuit due to nondeterministic repetitions'):
        cirq.with_measurement_key_mapping(op, {'m': 'm2'})

    # Everything should work once resolved
    op = cirq.resolve_parameters(op, {'a': 2})
    assert set(map(str, cirq.measurement_key_objs(op))) == {'0:m', '1:m'}
    assert op.mapped_circuit() == cirq.Circuit(
        cirq.X(q).with_classical_controls('c'),
        cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('0:m')),
        cirq.X(q).with_classical_controls('c'),
        cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('1:m')),
    )
    assert cirq.decompose(op) == cirq.decompose(
        cirq.Circuit(
            cirq.X(q).with_classical_controls('c'),
            cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('0:m')),
            cirq.X(q).with_classical_controls('c'),
            cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('1:m')),
        ))
def test_map_operations_deep_subcircuits():
    q = cirq.LineQubit.range(5)
    c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4]))
    c_orig_with_circuit_ops = cirq.Circuit(
        cirq.CircuitOperation(
            cirq.FrozenCircuit(
                [
                    cirq.CircuitOperation(cirq.FrozenCircuit(op)).repeat(2).with_tags("internal")
                    for op in c_orig.all_operations()
                ]
            )
        )
        .repeat(6)
        .with_tags("external")
    )

    def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE:
        yield [
            cirq.Z.on_each(*op.qubits),
            cirq.CX(*op.qubits),
            cirq.Z.on_each(*op.qubits),
        ] if op.gate == cirq.CX else op

    cirq.testing.assert_has_diagram(
        c_orig_with_circuit_ops,
        '''
      [       [ 0: ───@─── ]                                                               ]
      [ 0: ───[       │    ]────────────────────────────────────────────────────────────── ]
      [       [ 1: ───X─── ](loops=2)['internal']                                          ]
      [       │                                                                            ]
      [ 1: ───#2────────────────────────────────────────────────────────────────────────── ]
      [                                                                                    ]
      [       [ 2: ───X─── ]                                                               ]
0: ───[ 2: ───[       │    ]────────────────────────────────────────────────────────────── ]────────────────────────
      [       [ 3: ───@─── ](loops=2)['internal']                                          ]
      [       │                                                                            ]
      [       │                                     [ 3: ───@─── ]                         ]
      [ 3: ───#2────────────────────────────────────[       │    ]──────────────────────── ]
      [                                             [ 4: ───X─── ](loops=2)['internal']    ]
      [                                             │                                      ]
      [ 4: ─────────────────────────────────────────#2──────────────────────────────────── ](loops=6)['external']
      │
1: ───#2────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
2: ───#3────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
3: ───#4────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
4: ───#5────────────────────────────────────────────────────────────────────────────────────────────────────────────
''',
    )

    c_mapped = cirq.map_operations(c_orig_with_circuit_ops, map_func, deep=True)
    for unroller in [
        cirq.unroll_circuit_op,
        cirq.unroll_circuit_op_greedy_earliest,
        cirq.unroll_circuit_op_greedy_frontier,
    ]:
        cirq.testing.assert_has_diagram(
            unroller(c_mapped, deep=True),
            '''
      [       [ 0: ───Z───@───Z─── ]                                                                       ]
      [ 0: ───[           │        ]────────────────────────────────────────────────────────────────────── ]
      [       [ 1: ───Z───X───Z─── ](loops=2)['internal']                                                  ]
      [       │                                                                                            ]
      [ 1: ───#2────────────────────────────────────────────────────────────────────────────────────────── ]
      [                                                                                                    ]
      [       [ 2: ───Z───X───Z─── ]                                                                       ]
0: ───[ 2: ───[           │        ]────────────────────────────────────────────────────────────────────── ]────────────────────────
      [       [ 3: ───Z───@───Z─── ](loops=2)['internal']                                                  ]
      [       │                                                                                            ]
      [       │                                             [ 3: ───Z───@───Z─── ]                         ]
      [ 3: ───#2────────────────────────────────────────────[           │        ]──────────────────────── ]
      [                                                     [ 4: ───Z───X───Z─── ](loops=2)['internal']    ]
      [                                                     │                                              ]
      [ 4: ─────────────────────────────────────────────────#2──────────────────────────────────────────── ](loops=6)['external']
      │
1: ───#2────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
2: ───#3────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
3: ───#4────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
      │
4: ───#5────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
''',
        )
def test_validate_operation_no_gate():
    device = ionq.IonQAPIDevice(qubits=[])
    with pytest.raises(ValueError, match='no gates'):
        device.validate_operation(cirq.CircuitOperation(cirq.FrozenCircuit()))
def test_unroll_circuit_op_and_variants():
    q = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.X(q[0]), cirq.CNOT(q[0], q[1]), cirq.X(q[0]))
    cirq.testing.assert_has_diagram(
        c,
        '''
0: ───X───@───X───
          │
1: ───────X───────
''',
    )
    mapped_circuit = cirq.map_operations(
        c, lambda op, i: [cirq.Z(q[1])] * 2 if op.gate == cirq.CNOT else op
    )
    mapped_circuit_deep = cirq.Circuit(
        [cirq.Moment(cirq.CircuitOperation(cirq.FrozenCircuit(m))) for m in mapped_circuit[:-1]],
        mapped_circuit[-1],
    )
    cirq.testing.assert_has_diagram(
        mapped_circuit_deep,
        '''
0: ───[ 0: ───X─── ]────────────────────────────────────────────────────────────X───

1: ────────────────────[ 1: ───[ 1: ───Z───Z─── ]['<mapped_circuit_op>']─── ]───────
''',
    )
    for unroller in [
        cirq.unroll_circuit_op_greedy_earliest,
        cirq.unroll_circuit_op_greedy_frontier,
        cirq.unroll_circuit_op,
    ]:
        cirq.testing.assert_same_circuits(
            unroller(mapped_circuit), unroller(mapped_circuit_deep, deep=True, tags_to_check=None)
        )
        cirq.testing.assert_has_diagram(
            unroller(mapped_circuit_deep, deep=True),
            '''
0: ───[ 0: ───X─── ]────────────────────────X───

1: ────────────────────[ 1: ───Z───Z─── ]───────
            ''',
        )

    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op(mapped_circuit),
        '''
0: ───X───────────X───

1: ───────Z───Z───────
''',
    )
    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op_greedy_earliest(mapped_circuit),
        '''
0: ───X───────X───

1: ───Z───Z───────
''',
    )
    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op_greedy_frontier(mapped_circuit),
        '''
0: ───X───────X───

1: ───────Z───Z───
''',
    )
def test_string_format():
    x, y, z = cirq.LineQubit.range(3)

    fc0 = cirq.FrozenCircuit()
    op0 = cirq.CircuitOperation(fc0)
    assert str(op0) == f"[  ]"

    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"""\
[                       ]
[                       ]
[ 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"""\
[ 0: ───X───────M('m')─── ]
[               │         ]
[ 1: ───H───@───M──────── ]
[           │   │         ]
[ 2: ───────X───M──────── ]""")
    assert (repr(op1) == """\
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=cirq.MeasurementKey(name='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"""\
[ 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"""\
[ 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) == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.CircuitOperation(
                circuit=cirq.FrozenCircuit([
                    cirq.Moment(
                        cirq.X(cirq.LineQubit(1)),
                    ),
                ]),
            ),
        ),
    ]),
)""")
Beispiel #22
0
def test_serialize_deserialize_circuit_with_subcircuit():
    q0 = cirq.GridQubit(1, 1)
    q1 = cirq.GridQubit(1, 2)
    tag1 = cg.CalibrationTag('abc123')
    fcircuit = cirq.FrozenCircuit(cirq.X(q0))
    circuit = cirq.Circuit(
        cirq.X(q1).with_tags(tag1),
        cirq.CircuitOperation(fcircuit).repeat(repetition_ids=['a', 'b']),
        cirq.CircuitOperation(fcircuit).with_qubit_mapping({q0: q1}),
        cirq.X(q0),
    )

    op1 = v2.program_pb2.Operation()
    op1.gate.id = 'x_pow'
    op1.args['half_turns'].arg_value.float_value = 1.0
    op1.qubits.add().id = '1_2'
    op1.token_constant_index = 0

    c_op1 = v2.program_pb2.CircuitOperation()
    c_op1.circuit_constant_index = 1
    rep_spec = c_op1.repetition_specification
    rep_spec.repetition_count = 2
    rep_spec.repetition_ids.ids.extend(['a', 'b'])

    c_op2 = v2.program_pb2.CircuitOperation()
    c_op2.circuit_constant_index = 1
    c_op2.repetition_specification.repetition_count = 1
    qmap = c_op2.qubit_map.entries.add()
    qmap.key.id = '1_1'
    qmap.value.id = '1_2'

    proto = v2.program_pb2.Program(
        language=v2.program_pb2.Language(arg_function_language='', gate_set='my_gate_set'),
        circuit=v2.program_pb2.Circuit(
            scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT,
            moments=[
                v2.program_pb2.Moment(
                    operations=[op1],
                    circuit_operations=[c_op1],
                ),
                v2.program_pb2.Moment(
                    operations=[X_SERIALIZER.to_proto(cirq.X(q0))],
                    circuit_operations=[c_op2],
                ),
            ],
        ),
        constants=[
            v2.program_pb2.Constant(string_value='abc123'),
            v2.program_pb2.Constant(
                circuit_value=v2.program_pb2.Circuit(
                    scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT,
                    moments=[
                        v2.program_pb2.Moment(
                            operations=[X_SERIALIZER.to_proto(cirq.X(q0))],
                        )
                    ],
                )
            ),
        ],
    )
    assert proto == MY_GATE_SET.serialize(circuit)
    assert MY_GATE_SET.deserialize(proto) == circuit
Beispiel #23
0
def test_serialize_deserialize_circuit_with_subcircuit():
    serializer = cg.CircuitSerializer('my_gate_set')
    tag1 = cg.CalibrationTag('abc123')
    fcircuit = cirq.FrozenCircuit(
        cirq.XPowGate(exponent=2 * sympy.Symbol('t'))(Q0))
    circuit = cirq.Circuit(
        cirq.X(Q1).with_tags(tag1),
        cirq.CircuitOperation(fcircuit).repeat(repetition_ids=['a', 'b']),
        cirq.CircuitOperation(fcircuit).with_qubit_mapping({Q0: Q1}),
        cirq.X(Q0),
    )

    op_x = v2.program_pb2.Operation()
    op_x.xpowgate.exponent.float_value = 1.0
    op_x.qubit_constant_index.append(2)
    op_tag = v2.program_pb2.Operation()
    op_tag.xpowgate.exponent.float_value = 1.0
    op_tag.qubit_constant_index.append(0)
    op_tag.token_constant_index = 1
    op_symbol = v2.program_pb2.Operation()
    op_symbol.xpowgate.exponent.func.type = 'mul'
    op_symbol.xpowgate.exponent.func.args.add().arg_value.float_value = 2.0
    op_symbol.xpowgate.exponent.func.args.add().symbol = 't'
    op_symbol.qubit_constant_index.append(2)

    c_op1 = v2.program_pb2.CircuitOperation()
    c_op1.circuit_constant_index = 3
    rep_spec = c_op1.repetition_specification
    rep_spec.repetition_count = 2
    rep_spec.repetition_ids.ids.extend(['a', 'b'])

    c_op2 = v2.program_pb2.CircuitOperation()
    c_op2.circuit_constant_index = 3
    c_op2.repetition_specification.repetition_count = 1
    qmap = c_op2.qubit_map.entries.add()
    qmap.key.id = '2_4'
    qmap.value.id = '2_5'

    proto = v2.program_pb2.Program(
        language=v2.program_pb2.Language(arg_function_language='exp',
                                         gate_set='my_gate_set'),
        circuit=v2.program_pb2.Circuit(
            scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT,
            moments=[
                v2.program_pb2.Moment(
                    operations=[op_tag],
                    circuit_operations=[c_op1],
                ),
                v2.program_pb2.Moment(
                    operations=[op_x],
                    circuit_operations=[c_op2],
                ),
            ],
        ),
        constants=[
            v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='2_5')),
            v2.program_pb2.Constant(string_value='abc123'),
            v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='2_4')),
            v2.program_pb2.Constant(circuit_value=v2.program_pb2.Circuit(
                scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT,
                moments=[v2.program_pb2.Moment(operations=[op_symbol], )],
            )),
        ],
    )
    assert proto == serializer.serialize(circuit)
    assert serializer.deserialize(proto) == circuit
Beispiel #24
0
 def _wrap_cop(c: cirq.FrozenCircuit, *tags) -> cirq.FrozenCircuit:
     return cirq.FrozenCircuit(cirq.CircuitOperation(c).with_tags(*tags, t_all))
Beispiel #25
0
def test_gateset_validate_circuit_op_negative_reps():
    gate = CustomXPowGate(exponent=0.5)
    op = cirq.CircuitOperation(cirq.FrozenCircuit(gate.on(cirq.LineQubit(0))),
                               repetitions=-1)
    assert op not in cirq.Gateset(gate)
    assert op**-1 in cirq.Gateset(gate)
Beispiel #26
0
def default_circuit():
    return cirq.FrozenCircuit(
        cirq.X(cirq.GridQubit(1, 1))**sympy.Symbol('k'),
        cirq.X(cirq.GridQubit(1, 2)).with_tags(DEFAULT_TOKEN),
        cirq.measure(cirq.GridQubit(1, 1), key='m'),
    )
Beispiel #27
0
 def wrap_frozen(*ops):
     return cirq.FrozenCircuit(wrap(*ops))
Beispiel #28
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from unittest import mock

import pytest

import cirq
import cirq_google as cg
import cirq_google.engine.client.quantum


@pytest.mark.parametrize('circuit', [cirq.Circuit(), cirq.FrozenCircuit()])
def test_run_circuit(circuit):
    engine = mock.Mock()
    sampler = cg.QuantumEngineSampler(engine=engine,
                                      processor_id='tmp',
                                      gate_set=cg.XMON)
    params = [cirq.ParamResolver({'a': 1})]
    sampler.run_sweep(circuit, params, 5)
    engine.run_sweep.assert_called_with(
        gate_set=cg.XMON,
        params=params,
        processor_ids=['tmp'],
        program=circuit,
        repetitions=5,
    )
Beispiel #29
0
def test_parameterized_repeat():
    q = cirq.LineQubit(0)
    op = cirq.CircuitOperation(cirq.FrozenCircuit(
        cirq.X(q)))**sympy.Symbol('a')
    assert cirq.parameter_names(op) == {'a'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 0})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 2})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': -1})
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError,
                       match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5})
    with pytest.raises(
            ValueError,
            match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op**-1
    assert cirq.parameter_names(op) == {'a'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 0})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': 2})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={'a': -1})
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError,
                       match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5})
    with pytest.raises(
            ValueError,
            match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op**sympy.Symbol('b')
    assert cirq.parameter_names(op) == {'a', 'b'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 1,
                                           'b': 1
                                       })
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 2,
                                           'b': 1
                                       })
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 1,
                                           'b': 2
                                       })
    assert np.allclose(result.state_vector(), [1, 0])
    with pytest.raises(TypeError,
                       match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op),
                                  param_resolver={
                                      'a': 1.5,
                                      'b': 1
                                  })
    with pytest.raises(
            ValueError,
            match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op**2.0
    assert cirq.parameter_names(op) == {'a', 'b'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 1,
                                           'b': 1
                                       })
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 1.5,
                                           'b': 1
                                       })
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op),
                                       param_resolver={
                                           'a': 1,
                                           'b': 1.5
                                       })
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError,
                       match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op),
                                  param_resolver={
                                      'a': 1.5,
                                      'b': 1.5
                                  })
    with pytest.raises(
            ValueError,
            match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
Beispiel #30
0
def test_init_device_deprecated():
    q = cirq.LineQubit(0)
    with cirq.testing.assert_deprecated(
            cirq.circuits.circuit._DEVICE_DEP_MESSAGE, deadline='v0.15'):
        _ = cirq.FrozenCircuit(cirq.X(q), device=cirq.UNCONSTRAINED_DEVICE)