def test_optimizes_single_iswap(): a, b = cirq.LineQubit.range(2) c = cirq.Circuit.from_ops(cirq.ISWAP(a, b)) assert_optimization_not_broken(c) cg.MergeInteractions().optimize_circuit(c) assert len([1 for op in c.all_operations() if len(op.qubits) == 2]) == 2 assert all(cg.XmonGate.is_xmon_op(op) for op in c.all_operations())
def assert_optimization_not_broken(circuit): """Check that the unitary matrix for the input circuit is the same (up to global phase and rounding error) as the unitary matrix of the optimized circuit.""" u_before = circuit.to_unitary_matrix() cg.MergeInteractions().optimize_circuit(circuit) u_after = circuit.to_unitary_matrix() cirq.testing.assert_allclose_up_to_global_phase( u_before, u_after, atol=1e-8)
def test_decompose_partial_czs(circuit): optimizer = cg.MergeInteractions(allow_partial_czs=False) optimizer.optimize_circuit(circuit) cz_gates = [op.gate for op in circuit.all_operations() if cg.XmonGate.is_xmon_op(op) and isinstance(op.gate, cg.Exp11Gate)] num_full_cz = sum(1 for cz in cz_gates if cz.half_turns == 1) num_part_cz = sum(1 for cz in cz_gates if cz.half_turns != 1) assert num_full_cz == 2 assert num_part_cz == 0
def test_not_decompose_partial_czs(): circuit = cirq.Circuit.from_ops( cg.Exp11Gate(half_turns=0.1)(*cirq.LineQubit.range(2)), ) optimizer = cg.MergeInteractions(allow_partial_czs=True) optimizer.optimize_circuit(circuit) cz_gates = [op.gate for op in circuit.all_operations() if cg.XmonGate.is_xmon_op(op) and isinstance(op.gate, cg.Exp11Gate)] num_full_cz = sum(1 for cz in cz_gates if cz.half_turns == 1) num_part_cz = sum(1 for cz in cz_gates if cz.half_turns != 1) assert num_full_cz == 0 assert num_part_cz == 1
def assert_optimizes(before: cirq.Circuit, expected: cirq.Circuit): actual = cirq.Circuit(before) opt = cg.MergeInteractions() opt.optimize_circuit(actual) # Ignore differences that would be caught by follow-up optimizations. followup_optimizations = [ cg.MergeRotations(), cg.EjectFullW(), cg.EjectZ(), cirq.DropNegligible(), cirq.DropEmptyMoments() ] for post in followup_optimizations: post.optimize_circuit(actual) post.optimize_circuit(expected) if actual != expected: # coverage: ignore print('ACTUAL') print(actual) print('EXPECTED') print(expected) assert actual == expected