def test_add_result_type_same_observable_wrong_target_order_tensor_product(): Circuit().add_result_type( ResultType.Expectation( observable=Observable.Y() @ Observable.X(), target=[0, 1])).add_result_type( ResultType.Variance(observable=Observable.Y() @ Observable.X(), target=[1, 0]))
def test_add_result_type_observable_no_conflict_all(): expected = [ ResultType.Variance(observable=Observable.Y()), ResultType.Expectation(observable=Observable.Y()), ] circ = Circuit(expected) assert circ.result_types == expected
def test_add_result_type_observable_conflict_different_selected_targets_then_all_target( ): circ = Circuit().add_result_type( ResultType.Expectation(observable=Observable.Z(), target=[0])) circ.add_result_type( ResultType.Expectation(observable=Observable.Y(), target=[1])) circ.add_result_type(ResultType.Expectation(observable=Observable.Y()))
def test_multiple_result_types_with_custom_hermitian_ascii_symbol(): herm_matrix = (Observable.Y() @ Observable.Z()).to_matrix() circ = (Circuit().cnot(0, 2).cnot(1, 3).h(0).variance( observable=Observable.Y(), target=0).expectation(observable=Observable.Y(), target=3).expectation( observable=Observable.Hermitian( matrix=herm_matrix, display_name="MyHerm", ), target=[1, 2], )) expected = ( "T : | 0 |1| Result Types |", " ", "q0 : -C---H-Variance(Y)---------", " | ", "q1 : -|-C---Expectation(MyHerm)-", " | | | ", "q2 : -X-|---Expectation(MyHerm)-", " | ", "q3 : ---X---Expectation(Y)------", "", "T : | 0 |1| Result Types |", ) expected = "\n".join(expected) assert AsciiCircuitDiagram.build_diagram(circ) == expected
def test_multiple_result_types_with_state_vector_amplitude(): circ = ( Circuit() .cnot(0, 2) .cnot(1, 3) .h(0) .variance(observable=Observable.Y(), target=0) .expectation(observable=Observable.Y(), target=3) .expectation(observable=Observable.Hermitian(np.array([[1.0, 0.0], [0.0, 1.0]])), target=1) .amplitude(["0001"]) .state_vector() ) expected = ( "T : | 0 |1| Result Types |", " ", "q0 : -C---H-Variance(Y)------------", " | ", "q1 : -|-C---Expectation(Hermitian)-", " | | ", "q2 : -X-|--------------------------", " | ", "q3 : ---X---Expectation(Y)---------", "", "T : | 0 |1| Result Types |", "", "Additional result types: Amplitude(0001), StateVector", ) expected = "\n".join(expected) assert AsciiCircuitDiagram.build_diagram(circ) == expected
def test_multiple_result_types(): circ = ( Circuit() .cnot(0, 2) .cnot(1, 3) .h(0) .variance(observable=Observable.Y(), target=0) .expectation(observable=Observable.Y(), target=2) .sample(observable=Observable.Y()) ) expected = ( "T : | 0 |1| Result Types |", " ", "q0 : -C---H-Variance(Y)----Sample(Y)-", " | | ", "q1 : -|-C------------------Sample(Y)-", " | | | ", "q2 : -X-|---Expectation(Y)-Sample(Y)-", " | | ", "q3 : ---X------------------Sample(Y)-", "", "T : | 0 |1| Result Types |", ) expected = "\n".join(expected) assert AsciiCircuitDiagram.build_diagram(circ) == expected
def test_flattened_tensor_product(): observable_one = Observable.Z() @ Observable.Y() observable_two = Observable.X() @ Observable.H() actual = Observable.TensorProduct([observable_one, observable_two]) expected = Observable.TensorProduct( [Observable.Z(), Observable.Y(), Observable.X(), Observable.H()] ) assert expected == actual
def test_add_result_type_same_observable_wrong_target_order_tensor_product(): circ = (Circuit().add_result_type( ResultType.Expectation( observable=Observable.Y() @ Observable.X(), target=[0, 1])).add_result_type( ResultType.Variance(observable=Observable.Y() @ Observable.X(), target=[1, 0]))) assert not circ.observables_simultaneously_measurable assert not circ.basis_rotation_instructions
def test_add_result_type_observable_conflict_different_selected_targets_then_all_target( ): circ = Circuit().add_result_type( ResultType.Expectation(observable=Observable.Z(), target=[0])) circ.add_result_type( ResultType.Expectation(observable=Observable.Y(), target=[1])) circ.add_result_type(ResultType.Expectation(observable=Observable.Y())) assert not circ.observables_simultaneously_measurable assert not circ.basis_rotation_instructions
def test_obs_rt_equality(): a1 = ObservableResultType(ascii_symbols=["Obs"], observable=Observable.X(), target=0) a2 = ObservableResultType(ascii_symbols=["Obs"], observable=Observable.X(), target=0) a3 = ObservableResultType(ascii_symbols=["Obs"], observable=Observable.X(), target=1) a4 = "hi" assert a1 == a2 assert a1 != a3 assert a1 != a4 assert ResultType.Variance(observable=Observable.Y(), target=0) != ResultType.Expectation( observable=Observable.Y(), target=0 )
def test_basis_rotation_instructions_tensor_product(): circ = (Circuit().h(0).cnot(0, 1).expectation( observable=Observable.X() @ Observable.Y() @ Observable.Y(), target=[0, 1, 2])) expected = [ Instruction(Gate.H(), 0), Instruction(Gate.Z(), 1), Instruction(Gate.S(), 1), Instruction(Gate.H(), 1), Instruction(Gate.Z(), 2), Instruction(Gate.S(), 2), Instruction(Gate.H(), 2), ] assert circ.basis_rotation_instructions == expected
def test_get_value_by_result_type(result_obj_4): result = GateModelQuantumTaskResult.from_object(result_obj_4) assert np.allclose( result.get_value_by_result_type(ResultType.Probability(target=0)), result.values[0] ) assert np.allclose(result.get_value_by_result_type(ResultType.StateVector()), result.values[1]) assert ( result.get_value_by_result_type(ResultType.Expectation(observable=Observable.Y(), target=0)) == result.values[2] ) assert ( result.get_value_by_result_type(ResultType.Variance(observable=Observable.Y(), target=0)) == result.values[3] ) assert result.get_value_by_result_type(ResultType.Amplitude(state=["00"])) == result.values[4]
def result_types_tensor_y_hermitian_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] theta = 0.432 phi = 0.123 varphi = -0.543 array = np.array( [ [-6, 2 + 1j, -3, -5 + 2j], [2 - 1j, 0, 2 - 1j, -5 + 4j], [-3, 2 + 1j, 0, -4 + 3j], [-5 - 2j, -5 - 4j, -4 - 3j, -6], ] ) obs = Observable.Y() @ Observable.Hermitian(array) obs_targets = [0, 1, 2] circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) result = device.run(circuit, **run_kwargs).result() expected_mean = 1.4499810303182408 expected_var = 74.03174647518193 y_array = np.array([[0, -1j], [1j, 0]]) expected_eigs = np.linalg.eigvalsh(np.kron(y_array, array)) assert_variance_expectation_sample_result( result, shots, expected_var, expected_mean, expected_eigs )
def test_add_result_type_observable_no_conflict_state_vector_obs_return_value( ): expected = [ ResultType.StateVector(), ResultType.Expectation(observable=Observable.Y()), ] circ = Circuit(expected) assert circ.result_types == expected
def test_tensor_product_matmul_tensor(): t1 = Observable.TensorProduct([Observable.Z(), Observable.I(), Observable.X()]) t2 = Observable.TensorProduct( [Observable.Hermitian(matrix=Observable.I().to_matrix()), Observable.Y()] ) t3 = t1 @ t2 assert t3.to_ir() == ["z", "i", "x", [[[1.0, 0], [0, 0]], [[0, 0], [1.0, 0]]], "y"] assert t3.qubit_count == 5 assert t3.ascii_symbols == tuple(["Z@I@X@Hermitian@Y"] * 5)
def result_types_noncommuting_testing(device: Device, run_kwargs: Dict[str, Any]): shots = 0 theta = 0.432 phi = 0.123 varphi = -0.543 array = np.array( [ [-6, 2 + 1j, -3, -5 + 2j], [2 - 1j, 0, 2 - 1j, -5 + 4j], [-3, 2 + 1j, 0, -4 + 3j], [-5 - 2j, -5 - 4j, -4 - 3j, -6], ] ) obs1 = Observable.X() @ Observable.Y() obs1_targets = [0, 2] obs2 = Observable.Z() @ Observable.Z() obs2_targets = [0, 2] obs3 = Observable.Y() @ Observable.Hermitian(array) obs3_targets = [0, 1, 2] circuit = ( get_result_types_three_qubit_circuit(theta, phi, varphi, obs1, obs1_targets, shots) .expectation(obs2, obs2_targets) .expectation(obs3, obs3_targets) ) result = device.run(circuit, **run_kwargs).result() expected_mean1 = np.sin(theta) * np.sin(phi) * np.sin(varphi) expected_var1 = ( 8 * np.sin(theta) ** 2 * np.cos(2 * varphi) * np.sin(phi) ** 2 - np.cos(2 * (theta - phi)) - np.cos(2 * (theta + phi)) + 2 * np.cos(2 * theta) + 2 * np.cos(2 * phi) + 14 ) / 16 expected_mean2 = 0.849694136476246 expected_mean3 = 1.4499810303182408 assert np.allclose(result.values[0], expected_var1) assert np.allclose(result.values[1], expected_mean1) assert np.allclose(result.values[2], expected_mean2) assert np.allclose(result.values[3], expected_mean3)
def test_basis_rotation_instructions_all(): circ = Circuit().h(0).cnot(0, 1).sample(observable=Observable.Y()) expected = [ Instruction(Gate.Z(), 0), Instruction(Gate.S(), 0), Instruction(Gate.H(), 0), Instruction(Gate.Z(), 1), Instruction(Gate.S(), 1), Instruction(Gate.H(), 1), ] assert circ.basis_rotation_instructions == expected
def result_types_observable_not_in_instructions(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) bell = (Circuit().h(0).cnot(0, 1).expectation(observable=Observable.X(), target=[2]).variance( observable=Observable.Y(), target=[3])) result = device.run(bell, **run_kwargs).result() assert np.allclose(result.values[0], 0, **tol) assert np.allclose(result.values[1], 1, **tol)
def test_basis_rotation_instructions_identity(): circ = (Circuit().h(0).cnot(0, 1).cnot(1, 2).cnot(2, 3).cnot( 3, 4).expectation(observable=Observable.X(), target=[ 0 ]).expectation(observable=Observable.I(), target=[2]).expectation( observable=Observable.I() @ Observable.Y(), target=[1, 3]).expectation(observable=Observable.I(), target=[ 0 ]).expectation(observable=Observable.X() @ Observable.I(), target=[1, 3]).expectation(observable=Observable.Y(), target=[2])) expected = [ Instruction(Gate.H(), 0), Instruction(Gate.H(), 1), Instruction(Gate.Z(), 2), Instruction(Gate.S(), 2), Instruction(Gate.H(), 2), Instruction(Gate.Z(), 3), Instruction(Gate.S(), 3), Instruction(Gate.H(), 3), ] assert circ.basis_rotation_instructions == expected
def test_result_types_target_some(): circ = (Circuit().h(0).h(1).h(100).expectation( observable=Observable.Y() @ Observable.Z(), target=[0, 100])) expected = ( "T : |0| Result Types |", " ", "q0 : -H-Expectation(Y@Z)-", " | ", "q1 : -H-|----------------", " | ", "q100 : -H-Expectation(Y@Z)-", "", "T : |0| Result Types |", ) _assert_correct_diagram(circ, expected)
def test_result_types_target_some(): circ = (Circuit().h(0).h(1).h(100).expectation( observable=Observable.Y() @ Observable.Z(), target=[0, 100])) expected = ( "T : |0| Result Types |", " ", "q0 : -H-Expectation(Y@Z)-", " | ", "q1 : -H-|----------------", " | ", "q100 : -H-Expectation(Y@Z)-", "", "T : |0| Result Types |", ) expected = "\n".join(expected) assert AsciiCircuitDiagram.build_diagram(circ) == expected
def test_batch_execute_parallel(mock_run_batch): """Test batch_execute(parallel=True) correctly calls batch execution methods in Braket SDK""" mock_run_batch.return_value = TASK_BATCH dev = _aws_device(wires=4, foo="bar", parallel=True) assert dev.parallel is True with QuantumTape() as circuit: qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.probs(wires=[0]) qml.expval(qml.PauliX(1)) qml.var(qml.PauliY(2)) qml.sample(qml.PauliZ(3)) circuits = [circuit, circuit] batch_results = dev.batch_execute(circuits) for results in batch_results: assert np.allclose( results[0], RESULT.get_value_by_result_type( result_types.Probability(target=[0]))) assert np.allclose( results[1], RESULT.get_value_by_result_type( result_types.Expectation(observable=Observable.X(), target=1)), ) assert np.allclose( results[2], RESULT.get_value_by_result_type( result_types.Variance(observable=Observable.Y(), target=2)), ) assert np.allclose( results[3], RESULT.get_value_by_result_type( result_types.Sample(observable=Observable.Z(), target=3)), ) mock_run_batch.assert_called_with( [CIRCUIT, CIRCUIT], s3_destination_folder=("foo", "bar"), shots=SHOTS, max_parallel=None, max_connections=AwsQuantumTaskBatch.MAX_CONNECTIONS_DEFAULT, poll_timeout_seconds=AwsQuantumTask.DEFAULT_RESULTS_POLL_TIMEOUT, poll_interval_seconds=AwsQuantumTask.DEFAULT_RESULTS_POLL_INTERVAL, foo="bar", )
def test_pl_to_braket_circuit_hamiltonian(): """Tests that a PennyLane circuit is correctly converted into a Braket circuit""" dev = _aws_device(wires=2, foo="bar") with QuantumTape() as tape: qml.RX(0.2, wires=0) qml.RX(0.3, wires=1) qml.CNOT(wires=[0, 1]) qml.expval( qml.Hamiltonian((2, 3), (qml.PauliX(wires=0), qml.PauliY(wires=1)))) braket_circuit_true = (Circuit().rx(0, 0.2).rx(1, 0.3).cnot( 0, 1).expectation(Observable.X(), [0]).expectation(Observable.Y(), [1])) braket_circuit = dev._pl_to_braket_circuit(tape) assert braket_circuit_true == braket_circuit
def test_execute(mock_run): mock_run.return_value = TASK dev = _aws_device(wires=4, foo="bar") with QuantumTape() as circuit: qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.probs(wires=[0]) qml.expval(qml.PauliX(1)) qml.var(qml.PauliY(2)) qml.sample(qml.PauliZ(3)) results = dev.execute(circuit) assert np.allclose( results[0], RESULT.get_value_by_result_type(result_types.Probability(target=[0]))) assert np.allclose( results[1], RESULT.get_value_by_result_type( result_types.Expectation(observable=Observable.X(), target=1)), ) assert np.allclose( results[2], RESULT.get_value_by_result_type( result_types.Variance(observable=Observable.Y(), target=2)), ) assert np.allclose( results[3], RESULT.get_value_by_result_type( result_types.Sample(observable=Observable.Z(), target=3)), ) assert dev.task == TASK mock_run.assert_called_with( CIRCUIT, s3_destination_folder=("foo", "bar"), shots=SHOTS, poll_timeout_seconds=AwsQuantumTask.DEFAULT_RESULTS_POLL_TIMEOUT, poll_interval_seconds=AwsQuantumTask.DEFAULT_RESULTS_POLL_INTERVAL, foo="bar", )
def result_types_tensor_x_y_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] theta = 0.432 phi = 0.123 varphi = -0.543 obs = Observable.X() @ Observable.Y() obs_targets = [0, 2] circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) result = device.run(circuit, **run_kwargs).result() expected_mean = np.sin(theta) * np.sin(phi) * np.sin(varphi) expected_var = (8 * np.sin(theta)**2 * np.cos(2 * varphi) * np.sin(phi)**2 - np.cos(2 * (theta - phi)) - np.cos(2 * (theta + phi)) + 2 * np.cos(2 * theta) + 2 * np.cos(2 * phi) + 14) / 16 expected_eigs = get_pauli_eigenvalues(1) assert_variance_expectation_sample_result(result, shots, expected_var, expected_mean, expected_eigs)
def result_types_tensor_z_h_y_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] theta = 0.432 phi = 0.123 varphi = -0.543 obs = Observable.Z() @ Observable.H() @ Observable.Y() obs_targets = [0, 1, 2] circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() expected_mean = -(np.cos(varphi) * np.sin(phi) + np.sin(varphi) * np.cos(theta)) / np.sqrt(2) expected_var = (3 + np.cos(2 * phi) * np.cos(varphi)**2 - np.cos(2 * theta) * np.sin(varphi)**2 - 2 * np.cos(theta) * np.sin(phi) * np.sin(2 * varphi)) / 4 expected_eigs = get_pauli_eigenvalues(1) assert_variance_expectation_sample_result(result, shots, expected_var, expected_mean, expected_eigs)
})) TASK = Mock() TASK.result.return_value = RESULT type(TASK).id = PropertyMock(return_value="task_arn") TASK.state.return_value = "COMPLETED" TASK_BATCH = Mock() TASK_BATCH.results.return_value = [RESULT, RESULT] type(TASK_BATCH).tasks = PropertyMock(return_value=[TASK, TASK]) SIM_TASK = Mock() SIM_TASK.result.return_value.additional_metadata.simulatorMetadata.executionDuration = 1234 type(SIM_TASK).id = PropertyMock(return_value="task_arn") SIM_TASK.state.return_value = "COMPLETED" CIRCUIT = (Circuit().h(0).cnot( 0, 1).i(2).i(3).probability(target=[0]).expectation( observable=Observable.X(), target=1).variance(observable=Observable.Y(), target=2).sample(observable=Observable.Z(), target=3)) DEVICE_ARN = "baz" def test_reset(): """Tests that the members of the device are cleared on reset.""" dev = _aws_device(wires=2) dev._circuit = CIRCUIT dev._task = TASK dev.reset() assert dev.circuit is None assert dev.task is None
def test_add_result_type_observable_conflict_selected_target_then_all_target(): circ = Circuit().add_result_type( ResultType.Expectation(observable=Observable.Y(), target=[0, 1])) circ.add_result_type(ResultType.Probability())
def test_add_result_type_observable_conflict_all(): circ = Circuit().add_result_type(ResultType.Probability()) circ.add_result_type(ResultType.Expectation(observable=Observable.Y()))
def test_expectation_init_value_error_ascii_symbols(): ObservableResultType(ascii_symbols=["Obs"], observable=Observable.X() @ Observable.Y(), target=[1, 2])