def test_circuit(boolean_str): boolean_expr = sympy_parser.parse_expr(boolean_str) var_names = cirq.parameter_names(boolean_expr) qubits = [cirq.NamedQubit(name) for name in var_names] # We use Sympy to evaluate the expression: n = len(var_names) expected = [] for binary_inputs in itertools.product([0, 1], repeat=n): subed_expr = boolean_expr for var_name, binary_input in zip(var_names, binary_inputs): subed_expr = subed_expr.subs(var_name, binary_input) expected.append(bool(subed_expr)) # We build a circuit and look at its output state vector: circuit = cirq.Circuit() circuit.append(cirq.H.on_each(*qubits)) hamiltonian_gate = cirq.BooleanHamiltonian({q.name: q for q in qubits}, [boolean_str], 0.1 * math.pi) assert hamiltonian_gate.num_qubits() == n circuit.append(hamiltonian_gate) phi = cirq.Simulator().simulate(circuit, qubit_order=qubits, initial_state=0).state_vector() actual = np.arctan2(phi.real, phi.imag) - math.pi / 2.0 > 0.0 # Compare the two: np.testing.assert_array_equal(actual, expected)
def test_with_custom_names(): q0, q1, q2, q3 = cirq.LineQubit.range(4) original_op = cirq.BooleanHamiltonian( { 'a': q0, 'b': q1 }, ['a'], 0.1, ) assert cirq.decompose(original_op) == [cirq.Rz(rads=-0.05).on(q0)] renamed_op = original_op.with_qubits(q2, q3) assert cirq.decompose(renamed_op) == [cirq.Rz(rads=-0.05).on(q2)] with pytest.raises(ValueError, match='Length of replacement qubits must be the same'): original_op.with_qubits(q2)
def test_with_custom_names(): q0, q1, q2, q3 = cirq.LineQubit.range(4) with cirq.testing.assert_deprecated( 'Use cirq.BooleanHamiltonianGate', deadline='v0.15', count=3 ): original_op = cirq.BooleanHamiltonian( {'a': q0, 'b': q1}, ['a'], 0.1, ) assert cirq.decompose(original_op) == [cirq.Rz(rads=-0.05).on(q0)] renamed_op = original_op.with_qubits(q2, q3) assert cirq.decompose(renamed_op) == [cirq.Rz(rads=-0.05).on(q2)] with pytest.raises(ValueError, match='Length of replacement qubits must be the same'): original_op.with_qubits(q2) with pytest.raises(ValueError, match='All qubits must be 2-dimensional'): original_op.with_qubits(q0, cirq.LineQid(1, 3))