예제 #1
0
def assert_optimizes(before: cirq.Circuit,
                     expected: cirq.Circuit,
                     optimizer: Optional[Callable[[cirq.Circuit],
                                                  None]] = None):
    if optimizer is None:
        optimizer = cirq.MergeSingleQubitGates().optimize_circuit
    optimizer(before)

    # Ignore differences that would be caught by follow-up optimizations.
    followup_optimizations = [cirq.DropNegligible(), cirq.DropEmptyMoments()]
    for post in followup_optimizations:
        post(before)  # type: ignore #  error: "object" not callable
        post(expected)  # type: ignore #  error: "object" not callable

    assert before == expected, 'BEFORE {} : EXPECTED {}'.format(
        before, expected)
def assert_optimizes(before, after, optimizer=None):
    if optimizer is None:
        optimizer = cirq.MergeSingleQubitGates()
    optimizer.optimize_circuit(before)

    # Ignore differences that would be caught by follow-up optimizations.
    followup_optimizations = [cirq.DropNegligible(), cirq.DropEmptyMoments()]
    for post in followup_optimizations:
        post.optimize_circuit(before)
        post.optimize_circuit(after)

    if before != after:
        # coverage: ignore
        print("before:", before)
        print("after:", after)
    assert before == after
예제 #3
0
def test_combines_sequence():
    with cirq.testing.assert_deprecated("Use cirq.merge_k_qubit_unitaries",
                                        deadline='v1.0'):
        m = cirq.MergeSingleQubitGates()
    q = cirq.NamedQubit('q')
    c = cirq.Circuit(cirq.X(q)**0.5, cirq.Z(q)**0.5, cirq.X(q)**-0.5)

    opt_summary = m.optimization_at(c, 0, c.operation_at(q, 0))
    assert opt_summary.clear_span == 3
    assert list(opt_summary.clear_qubits) == [q]
    assert len(opt_summary.new_operations) == 1
    assert isinstance(opt_summary.new_operations[0].gate, cirq.MatrixGate)
    cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(
        opt_summary.new_operations[0]),
                                                    cirq.unitary(cirq.Y**0.5),
                                                    atol=1e-7)
def test_combines_sequence():
    m = cirq.MergeSingleQubitGates()
    q = cirq.QubitId()
    c = cirq.Circuit([
        cirq.Moment([cirq.X(q)**0.5]),
        cirq.Moment([cirq.Z(q)**0.5]),
        cirq.Moment([cirq.X(q)**-0.5]),
    ])

    opt_summary = m.optimization_at(c, 0, c.operation_at(q, 0))
    assert opt_summary.clear_span == 3
    assert list(opt_summary.clear_qubits) == [q]
    assert len(opt_summary.new_operations) == 1
    assert isinstance(opt_summary.new_operations[0].gate,
                      cirq.SingleQubitMatrixGate)
    cirq.testing.assert_allclose_up_to_global_phase(
        opt_summary.new_operations[0].matrix(), (cirq.Y**0.5).matrix(),
        atol=1e-7)
예제 #5
0
def test_rewrite():
    q0 = cirq.LineQubit(0)
    q1 = cirq.LineQubit(1)
    circuit = cirq.Circuit.from_ops(
        cirq.X(q0),
        cirq.X(q1),
        cirq.Y(q0),
        cirq.CZ(q0, q1),
        cirq.Y(q1),
    )
    cirq.MergeSingleQubitGates(
        rewriter=lambda ops: cirq.H(ops[0].qubits[0])
    ).optimize_circuit(circuit)
    cirq.DropEmptyMoments().optimize_circuit(circuit)

    cirq.testing.assert_same_circuits(circuit, cirq.Circuit.from_ops(
        cirq.H(q0),
        cirq.H(q1),
        cirq.CZ(q0, q1),
        cirq.H(q1),
    ))
def test_extension():
    class DummyGate(cirq.Gate):
        pass

    ext = cirq.Extensions()
    ext.add_cast(
        cirq.KnownMatrix, DummyGate,
        lambda _: cirq.SingleQubitMatrixGate(np.array([[0, 1], [1, 0]])))
    optimizer = cirq.MergeSingleQubitGates(extensions=ext)

    q = cirq.QubitId()
    c = cirq.Circuit([
        cirq.Moment([DummyGate().on(q)]),
    ])
    assert_optimizes(
        before=c,
        after=cirq.Circuit([
            cirq.Moment(
                [cirq.SingleQubitMatrixGate(np.array([[0, 1], [1, 0]]))(q)])
        ]),
        optimizer=optimizer)
예제 #7
0
def assert_optimizes(before: cirq.Circuit,
                     expected: cirq.Circuit,
                     optimizer: cirq.OptimizationPass = None):
    if optimizer is None:
        optimizer = cirq.MergeSingleQubitGates()
    optimizer.optimize_circuit(before)

    # Ignore differences that would be caught by follow-up optimizations.
    followup_optimizations = [cirq.DropNegligible(), cirq.DropEmptyMoments()]
    for post in followup_optimizations:
        post.optimize_circuit(before)
        post.optimize_circuit(expected)

    try:
        assert before == expected
    except AssertionError:  # coverage: ignore
        # coverage: ignore
        print("BEFORE")
        print(before)
        print("EXPECTED")
        print(expected)
        raise
def test_stopped_at_2qubit():
    m = cirq.MergeSingleQubitGates()
    q = cirq.QubitId()
    q2 = cirq.QubitId()
    c = cirq.Circuit([
        cirq.Moment([cirq.Z(q)]),
        cirq.Moment([cirq.H(q)]),
        cirq.Moment([cirq.X(q)]),
        cirq.Moment([cirq.H(q)]),
        cirq.Moment([cirq.CZ(q, q2)]),
        cirq.Moment([cirq.H(q)]),
    ])

    opt_summary = m.optimization_at(c, 0, c.operation_at(q, 0))
    assert opt_summary.clear_span == 4
    assert list(opt_summary.clear_qubits) == [q]
    if len(opt_summary.new_operations) != 0:
        assert len(opt_summary.new_operations) == 1
        assert isinstance(opt_summary.new_operations[0].gate,
                          cirq.SingleQubitMatrixGate)
        cirq.testing.assert_allclose_up_to_global_phase(
            opt_summary.new_operations[0].matrix(), np.eye(2), atol=1e-7)
예제 #9
0
def assert_optimizes(
    before: cirq.Circuit,
    expected: cirq.Circuit,
    optimizer: Optional[Callable[[cirq.Circuit], None]] = None,
    deprecated_msg: str = "Use cirq.merge_k_qubit_unitaries",
):
    with cirq.testing.assert_deprecated(deprecated_msg, deadline='v1.0'):
        if optimizer is None:
            optimizer = cirq.MergeSingleQubitGates().optimize_circuit
        optimizer(before)

    # Ignore differences that would be caught by follow-up optimizations.
    followup_transformers = [
        cirq.drop_negligible_operations, cirq.drop_empty_moments
    ]
    for transform in followup_transformers:
        before = transform(
            before)  # type: ignore #  error: "object" not callable
        expected = transform(
            expected)  # type: ignore #  error: "object" not callable

    assert before == expected, f'BEFORE:\n{before}\nEXPECTED:\n{expected}'
def assert_optimizes(before: cirq.Circuit,
                     expected: cirq.Circuit,
                     optimizer: Optional[Callable[[cirq.Circuit],
                                                  None]] = None):
    if optimizer is None:
        optimizer = cirq.MergeSingleQubitGates().optimize_circuit
    optimizer(before)

    # Ignore differences that would be caught by follow-up optimizations.
    followup_optimizations = [cirq.DropNegligible(), cirq.DropEmptyMoments()]
    for post in followup_optimizations:
        post(before)  # type: ignore #  error: "object" not callable
        post(expected)  # type: ignore #  error: "object" not callable

    try:
        assert before == expected
    except AssertionError:  # coverage: ignore
        # coverage: ignore
        print("BEFORE")
        print(before)
        print("EXPECTED")
        print(expected)
        raise
예제 #11
0
def test_not_both():
    with pytest.raises(ValueError):
        _ = cirq.MergeSingleQubitGates(synthesizer=lambda *args: None, rewriter=lambda *args: None)
예제 #12
0
def test_not_both():
    with cirq.testing.assert_deprecated("Use cirq.merge_k_qubit_unitaries",
                                        deadline='v1.0'):
        with pytest.raises(ValueError):
            _ = cirq.MergeSingleQubitGates(synthesizer=lambda *args: None,
                                           rewriter=lambda *args: None)