def result_types_zero_shots_bell_pair_testing(device: Device,
                                              include_state_vector: bool,
                                              run_kwargs: Dict[str, Any]):
    circuit = (Circuit().h(0).cnot(
        0, 1).expectation(observable=Observable.H() @ Observable.X(),
                          target=[0, 1]).amplitude(["01", "10", "00", "11"]))
    if include_state_vector:
        circuit.state_vector()
    result = device.run(circuit, **run_kwargs).result()
    assert len(result.result_types) == 3 if include_state_vector else 2
    assert np.allclose(
        result.get_value_by_result_type(
            ResultType.Expectation(observable=Observable.H() @ Observable.X(),
                                   target=[0, 1])),
        1 / np.sqrt(2),
    )
    if include_state_vector:
        assert np.allclose(
            result.get_value_by_result_type(ResultType.StateVector()),
            np.array([1, 0, 0, 1]) / np.sqrt(2),
        )
    assert result.get_value_by_result_type(
        ResultType.Amplitude(["01", "10", "00", "11"])) == {
            "01": 0j,
            "10": 0j,
            "00": (1 / np.sqrt(2)),
            "11": (1 / np.sqrt(2)),
        }
コード例 #2
0
def result_types_nonzero_shots_bell_pair_testing(device: Device, run_kwargs: Dict[str, Any]):
    circuit = (
        Circuit()
        .h(0)
        .cnot(0, 1)
        .expectation(observable=Observable.H() @ Observable.X(), target=[0, 1])
        .sample(observable=Observable.H() @ Observable.X(), target=[0, 1])
    )
    result = device.run(circuit, **run_kwargs).result()
    assert len(result.result_types) == 2
    assert (
        0.6
        < result.get_value_by_result_type(
            ResultType.Expectation(observable=Observable.H() @ Observable.X(), target=[0, 1])
        )
        < 0.8
    )
    assert (
        len(
            result.get_value_by_result_type(
                ResultType.Sample(observable=Observable.H() @ Observable.X(), target=[0, 1])
            )
        )
        == run_kwargs["shots"]
    )
コード例 #3
0
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]))
コード例 #4
0
def result_types_zero_shots_bell_pair_testing(
    device: Device,
    include_state_vector: bool,
    run_kwargs: Dict[str, Any],
    include_amplitude: bool = True,
):
    circuit = (Circuit().h(0).cnot(0, 1).expectation(
        observable=Observable.H() @ Observable.X(), target=[0, 1]))
    if include_amplitude:
        circuit.amplitude(["01", "10", "00", "11"])
    if include_state_vector:
        circuit.state_vector()
    tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM))
    for task in tasks:
        result = device.run(task, **run_kwargs).result()
        assert len(result.result_types) == 3 if include_state_vector else 2
        assert np.allclose(
            result.get_value_by_result_type(
                ResultType.Expectation(
                    observable=Observable.H() @ Observable.X(), target=[0,
                                                                        1])),
            1 / np.sqrt(2),
        )
        if include_state_vector:
            assert np.allclose(
                result.get_value_by_result_type(ResultType.StateVector()),
                np.array([1, 0, 0, 1]) / np.sqrt(2),
            )
        if include_amplitude:
            amplitude = result.get_value_by_result_type(
                ResultType.Amplitude(["01", "10", "00", "11"]))
            assert np.isclose(amplitude["01"], 0)
            assert np.isclose(amplitude["10"], 0)
            assert np.isclose(amplitude["00"], 1 / np.sqrt(2))
            assert np.isclose(amplitude["11"], 1 / np.sqrt(2))
コード例 #5
0
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
コード例 #6
0
def test_basis_rotation_instructions_multiple_result_types_same_targets():
    circ = (Circuit().h(0).cnot(0, 1).expectation(
        observable=Observable.H() @ Observable.X(),
        target=[0, 1]).sample(observable=Observable.H() @ Observable.X(),
                              target=[0, 1]).variance(
                                  observable=Observable.H() @ Observable.X(),
                                  target=[0, 1]))
    expected = [Instruction(Gate.Ry(-np.pi / 4), 0), Instruction(Gate.H(), 1)]
    assert circ.basis_rotation_instructions == expected
コード例 #7
0
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
コード例 #8
0
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
    )
コード例 #9
0
def result_types_noncommuting_flipped_targets_testing(device: Device, run_kwargs: Dict[str, Any]):
    circuit = (
        Circuit()
        .h(0)
        .cnot(0, 1)
        .expectation(observable=Observable.H() @ Observable.X(), target=[0, 1])
        .expectation(observable=Observable.H() @ Observable.X(), target=[1, 0])
    )
    result = device.run(circuit, shots=0, **run_kwargs).result()
    assert np.allclose(result.values[0], np.sqrt(2) / 2)
    assert np.allclose(result.values[1], np.sqrt(2) / 2)
コード例 #10
0
def test_tensor_product_to_ir():
    t = Observable.TensorProduct(
        [Observable.Z(), Observable.I(),
         Observable.X()])
    assert t.to_ir() == ["z", "i", "x"]
    assert t.qubit_count == 3
    assert t.ascii_symbols == tuple(["Z@I@X"] * 3)
コード例 #11
0
def test_tensor_product_rmatmul_observable():
    t1 = Observable.TensorProduct([Observable.Z(), Observable.I(), Observable.X()])
    o1 = Observable.I()
    t = o1 @ t1
    assert t.to_ir() == ["i", "z", "i", "x"]
    assert t.qubit_count == 4
    assert t.ascii_symbols == tuple(["I@Z@I@X"] * 4)
コード例 #12
0
def test_basis_rotation_instructions_tensor_product_shared_factors():
    circ = (Circuit().h(0).cnot(0, 1).expectation(
        observable=Observable.X() @ Observable.Y() @ Observable.Y(),
        target=[0, 1,
                2]).expectation(observable=Observable.X() @ Observable.Y(),
                                target=[0, 1]))
    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
コード例 #13
0
def test_obs_rt_repr():
    a1 = ObservableResultType(ascii_symbols=["Obs"],
                              observable=Observable.X(),
                              target=0)
    assert (
        str(a1) ==
        "ObservableResultType(observable=X('qubit_count': 1), target=QubitSet([Qubit(0)]))"
    )
コード例 #14
0
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)
コード例 #15
0
def test_ir_non_empty_instructions_result_types_basis_rotation_instructions():
    circ = Circuit().h(0).cnot(0, 1).sample(observable=Observable.X(),
                                            target=[0])
    expected = jaqcd.Program(
        instructions=[jaqcd.H(target=0),
                      jaqcd.CNot(control=0, target=1)],
        results=[jaqcd.Sample(observable=["x"], targets=[0])],
        basis_rotation_instructions=[jaqcd.H(target=0)],
    )
    assert circ.to_ir() == expected
コード例 #16
0
def result_types_noncommuting_all(device: Device, run_kwargs: Dict[str, Any]):
    array = np.array([[1, 2j], [-2j, 0]])
    circuit = (Circuit().h(0).cnot(
        0, 1).expectation(observable=Observable.Hermitian(array)).expectation(
            observable=Observable.X()))
    tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM))
    for task in tasks:
        result = device.run(task, shots=0, **run_kwargs).result()
        assert np.allclose(result.values[0], [0.5, 0.5])
        assert np.allclose(result.values[1], [0, 0])
コード例 #17
0
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)
コード例 #18
0
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
コード例 #19
0
def openqasm_result_types_bell_pair_testing(device: Device,
                                            run_kwargs: Dict[str, Any]):
    openqasm_string = ("OPENQASM 3;"
                       "qubit[2] q;"
                       "h q[0];"
                       "cnot q[0], q[1];"
                       "#pragma braket result expectation h(q[0]) @ x(q[1])"
                       "#pragma braket result sample h(q[0]) @ x(q[1])")
    hardcoded_openqasm = OpenQasmProgram(source=openqasm_string)
    circuit = (Circuit().h(0).cnot(0, 1).expectation(
        Observable.H() @ Observable.X(),
        (0, 1)).sample(Observable.H() @ Observable.X(), (0, 1)))
    generated_openqasm = circuit.to_ir(ir_type=IRType.OPENQASM)

    for program in hardcoded_openqasm, generated_openqasm:
        result = device.run(program, **run_kwargs).result()
        assert len(result.result_types) == 2
        assert (0.6 < result.get_value_by_result_type(
            ResultType.Expectation(observable=Observable.H() @ Observable.X(),
                                   target=[0, 1])) < 0.8)
        assert (len(
            result.get_value_by_result_type(
                ResultType.Sample(observable=Observable.H() @ Observable.X(),
                                  target=[0, 1]))) == run_kwargs["shots"])
コード例 #20
0
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",
    )
コード例 #21
0
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
コード例 #22
0
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",
    )
コード例 #23
0
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 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)
コード例 #25
0
def test_variance_parent_class():
    assert isinstance(ResultType.Variance(observable=Observable.X(), target=0),
                      ObservableResultType)
コード例 #26
0
def test_basis_rotation_instructions_target():
    circ = Circuit().h(0).cnot(0, 1).expectation(observable=Observable.X(),
                                                 target=0)
    expected = [Instruction(Gate.H(), 0)]
    assert circ.basis_rotation_instructions == expected
コード例 #27
0
        },
    }))
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
コード例 #28
0
def test_qubit_count_getter(h):
    assert h.qubit_count is h._moments.qubit_count


@pytest.mark.xfail(raises=AttributeError)
def test_qubit_count_setter(h):
    h.qubit_count = 1


@pytest.mark.parametrize(
    "circuit,expected_qubit_count",
    [
        (Circuit().h(0).h(1).h(2), 3),
        (
            Circuit().h(0).expectation(
                observable=Observable.H() @ Observable.X(),
                target=[0, 1]).sample(
                    observable=Observable.H() @ Observable.X(), target=[0, 1]),
            2,
        ),
        (
            Circuit().h(0).probability([1, 2]).state_vector(),
            1,
        ),
        (
            Circuit().h(0).variance(observable=Observable.H(),
                                    target=1).state_vector().amplitude(["01"]),
            2,
        ),
    ],
)
コード例 #29
0
def test_expectation_init_value_error_ascii_symbols():
    ObservableResultType(ascii_symbols=["Obs"],
                         observable=Observable.X() @ Observable.Y(),
                         target=[1, 2])
コード例 #30
0
def test_obs_rt_init_value_error_qubit_count():
    ObservableResultType(ascii_symbols=["Obs"],
                         observable=Observable.X(),
                         target=[0, 1])