Beispiel #1
0
    def test_repeated_interface_construction(self):
        """Test that the interface is correctly applied multiple times"""
        with TorchInterface.apply(QuantumTape()) as tape:
            qml.RX(0.5, wires=0)
            qml.expval(qml.PauliX(0))

        assert tape.interface == "torch"
        assert isinstance(tape, TorchInterface)
        assert tape.__bare__ == QuantumTape

        TorchInterface.apply(tape, dtype=torch.float32)
        assert tape.interface == "torch"
        assert isinstance(tape, TorchInterface)
        assert tape.__bare__ == QuantumTape
        assert tape.dtype is torch.float32
Beispiel #2
0
    def test_execution(self):
        """Test execution"""
        a = tf.Variable(0.1)
        dev = qml.device("default.qubit.tf", wires=1)

        with tf.GradientTape() as tape:
            with QuantumTape() as qtape:
                qml.RY(a, wires=0)
                qml.RX(0.2, wires=0)
                qml.expval(qml.PauliZ(0))

            res = qtape.execute(dev)

        assert isinstance(res, tf.Tensor)
        assert res.shape == (1, )
Beispiel #3
0
    def test_single_mode_sample(self):
        """Test that there is only one array of values returned
        for a single wire qml.sample"""
        dev = qml.device("default.qubit", wires=2, shots=10)
        x = 0.543
        y = -0.654

        with QuantumTape() as tape:
            qml.RX(x, wires=[0])
            qml.RY(y, wires=[1])
            qml.CNOT(wires=[0, 1])
            qml.sample(qml.PauliZ(0) @ qml.PauliX(1))

        res = tape.execute(dev)
        assert res.shape == (1, 10)
Beispiel #4
0
        def cost_fn(a, p, device):
            tape = QuantumTape()

            with tape:
                qml.RX(a, wires=0)
                U3(*p, wires=0)
                qml.expval(qml.PauliX(0))

            tape = AutogradInterface.apply(tape.expand())

            assert tape.trainable_params == {1, 2, 3, 4}
            assert [i.name for i in tape.operations] == ["RX", "Rot", "PhaseShift"]
            assert np.all(np.array(tape.get_parameters()) == [p[2], p[0], -p[2], p[1] + p[2]])

            return tape.execute(device=device)
Beispiel #5
0
    def test_tensor_observables_rmatmul(self):
        """Test that tensor observables are correctly processed from the annotated
        queue. Here, we test multiple tensor observables constructed via matmul
        with the observable occuring on the left hand side."""

        with QuantumTape() as tape:
            op = qml.RX(1.0, wires=0)
            t_obs1 = qml.PauliZ(1) @ qml.PauliX(0)
            t_obs2 = qml.Hadamard(2) @ t_obs1
            m = qml.expval(t_obs2)

        assert tape.operations == [op]
        assert tape.observables == [t_obs2]
        assert tape.measurements[0].return_type is qml.operation.Expectation
        assert tape.measurements[0].obs is t_obs2
Beispiel #6
0
    def test_tensor_observables_tensor_init(self):
        """Test that tensor observables are correctly processed from the annotated
        queue. Here, we test multiple tensor observables constructed via explicit
        Tensor creation."""

        with QuantumTape() as tape:
            op = qml.RX(1.0, wires=0)
            t_obs1 = qml.PauliZ(1) @ qml.PauliX(0)
            t_obs2 = qml.operation.Tensor(t_obs1, qml.Hadamard(2))
            m = qml.expval(t_obs2)

        assert tape.operations == [op]
        assert tape.observables == [t_obs2]
        assert tape.measurements[0].return_type is qml.operation.Expectation
        assert tape.measurements[0].obs is t_obs2
    def test_same_hash(self):
        """Test that executing the same tape twice produces the same circuit
        hash."""
        dev = qml.device("default.qubit", wires=2)

        with QuantumTape() as tape0:
            qml.RZ(0.3, wires=[0])
            qml.expval(qml.PauliX(0))

        tape0.execute(dev)
        orig_hash = dev.circuit_hash

        tape0.execute(dev)
        new_hash = dev.circuit_hash
        assert orig_hash == new_hash
Beispiel #8
0
    def test_execution(self):
        """Test execution"""
        a = torch.tensor(0.1, requires_grad=True)
        dev = qml.device("default.qubit", wires=1)

        with TorchInterface.apply(QuantumTape()) as tape:
            qml.RY(a, wires=0)
            qml.RX(torch.tensor(0.2), wires=0)
            qml.expval(qml.PauliZ(0))

        assert tape.trainable_params == {0}
        res = tape.execute(dev)

        assert isinstance(res, torch.Tensor)
        assert res.shape == (1, )
Beispiel #9
0
    def test_multiple_observables_same_wire(self):
        """Test if an error is raised when multiple observables are evaluated on the same wire
        without first running tape.expand()."""
        dev = qml.device("default.qubit", wires=2)

        with QuantumTape() as tape:
            qml.expval(qml.PauliX(0) @ qml.PauliZ(1))
            qml.expval(qml.PauliX(0))

        with pytest.raises(qml.QuantumFunctionError,
                           match="Multiple observables are being"):
            tape.execute(dev)

        new_tape = tape.expand()
        new_tape.execute(dev)
Beispiel #10
0
def to_pennylane(circuit: Circuit) -> QuantumTape:
    """Returns a QuantumTape equivalent to the input Mitiq circuit.

    Args:
        circuit: Mitiq circuit to convert to a Pennylane QuantumTape.

    Returns:
        QuantumTape object equivalent to the input Mitiq circuit.
    """
    qfunc = pennylane_from_qasm(to_qasm(circuit))

    with QuantumTape() as tape:
        qfunc(wires=Wires(range(len(circuit.all_qubits()))))

    return tape
Beispiel #11
0
    def test_decomposition_removing_parameters(self):
        """Test that decompositions which reduce the number of parameters
        on the tape retain tape consistency."""
        with QuantumTape() as tape:
            qml.BasisState(np.array([1]), wires=0)

        new_tape = tape.expand()

        assert len(new_tape.operations) == 1
        assert new_tape.operations[0].name == "PauliX"
        assert new_tape.operations[0].wires.tolist() == [0]
        assert new_tape.num_params == 0
        assert new_tape.get_parameters() == []

        assert isinstance(new_tape.operations[0], qml.PauliX)
Beispiel #12
0
    def test_three_layers_one_wire(self):
        """Tests the positions when multiple gates are all on the same wire."""

        with QuantumTape() as tape:
            qml.PauliX(0)
            qml.PauliX(0)
            qml.PauliX(0)

        _, ax = tape_mpl(tape)

        for layer, box in enumerate(ax.patches):
            assert box.get_xy() == (layer - 0.4, -0.4)

        for t in ax.texts[1:]:
            assert t.get_text() == "X"
Beispiel #13
0
    def test_sampling(self):
        """Test sampling works as expected"""
        dev = qml.device("default.qubit.tf", wires=2, shots=10)

        with tf.GradientTape() as tape:
            with QuantumTape() as qtape:
                qml.Hadamard(wires=[0])
                qml.CNOT(wires=[0, 1])
                qml.sample(qml.PauliZ(0))
                qml.sample(qml.PauliX(1))

            res = qtape.execute(dev)

        assert res.shape == (2, 10)
        assert isinstance(res, tf.Tensor)
Beispiel #14
0
def test_controlled_template_and_operations():
    """Test that a combination of controlled templates and operations correctly expands
    on a device that doesn't support it"""

    weights = np.ones([3, 2])

    def ansatz(weights, wires):
        qml.PauliX(wires=wires[0])
        qml.templates.BasicEntanglerLayers(weights, wires=wires)

    with QuantumTape() as tape:
        ctrl(ansatz, 0)(weights, wires=[1, 2])

    tape = expand_tape(tape)
    assert len(tape.operations) == 10
    assert all(o.name in {"CNOT", "CRX", "Toffoli"} for o in tape.operations)
Beispiel #15
0
    def wrapper(*args, **kwargs):
        with get_active_tape().stop_recording(), QuantumTape() as tape:
            fn(*args, **kwargs)

        if not tape.operations:
            tape = fn(*args, **kwargs)

        for op in reversed(tape.operations):
            try:
                op.adjoint()
            except NotImplementedError:
                # Expand the operation and adjoint the result.
                # We do not do anything with the output since
                # calling adjoint on the expansion will automatically
                # queue the new operations.
                adjoint(op.expand)()
Beispiel #16
0
    def test_get_parameters(self):
        """Test that the get parameters function correctly sets and returns the
        trainable parameters"""
        a = torch.tensor(0.1, requires_grad=True)
        b = torch.tensor(0.2)
        c = torch.tensor(0.3, requires_grad=True)
        d = 0.4

        with TorchInterface.apply(QuantumTape()) as tape:
            qml.Rot(a, b, c, wires=0)
            qml.RX(d, wires=1)
            qml.CNOT(wires=[0, 1])
            qml.expval(qml.PauliX(0))

        assert tape.trainable_params == {0, 2}
        assert np.all(tape.get_parameters() == [a, c])
Beispiel #17
0
    def test_execution(self):
        """Test execution"""
        a = tf.Variable(0.1)
        dev = qml.device("default.qubit", wires=1)

        with tf.GradientTape() as tape:
            with TFInterface.apply(QuantumTape()) as qtape:
                qml.RY(a, wires=0)
                qml.RX(0.2, wires=0)
                qml.expval(qml.PauliZ(0))

            assert qtape.trainable_params == {0}
            res = qtape.execute(dev)

        assert isinstance(res, tf.Tensor)
        assert res.shape == (1, )
Beispiel #18
0
    def test_three_layers(self):
        """Test wire length when circuit has three layers."""

        with QuantumTape() as tape:
            qml.PauliX(0)
            qml.PauliX(0)
            qml.PauliX(0)

        _, ax = tape_mpl(tape)

        assert len(ax.lines) == 1
        assert ax.lines[0].get_xdata() == (-1, 3
                                           )  # from -1 to number of layers
        assert ax.lines[0].get_ydata() == (0, 0)

        plt.close()
Beispiel #19
0
    def test_decomposition_adding_parameters(self):
        """Test that decompositions which increase the number of parameters
        on the tape retain tape consistency."""
        with QuantumTape() as tape:
            qml.PauliX(wires=0)

        new_tape = tape.expand()

        assert len(new_tape.operations) == 3

        assert new_tape.operations[0].name == "PhaseShift"
        assert new_tape.operations[1].name == "RX"
        assert new_tape.operations[2].name == "PhaseShift"

        assert new_tape.num_params == 3
        assert new_tape.get_parameters() == [np.pi / 2, np.pi, np.pi / 2]
Beispiel #20
0
    def test_tensor_observables_tensor_matmul(self):
        """Test that tensor observables are correctly processed from the annotated
        queue". Here, wetest multiple tensor observables constructed via matmul
        between two tensor observables."""

        with QuantumTape() as tape:
            op = qml.RX(1.0, wires=0)
            t_obs1 = qml.PauliZ(0) @ qml.PauliX(1)
            t_obs2 = qml.PauliY(2) @ qml.PauliZ(3)
            t_obs = t_obs1 @ t_obs2
            m = qml.var(t_obs)

        assert tape.operations == [op]
        assert tape.observables == [t_obs]
        assert tape.measurements[0].return_type is qml.operation.Variance
        assert tape.measurements[0].obs is t_obs
Beispiel #21
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",
    )
Beispiel #22
0
    def test_single_output_value(self, tol):
        """Tests correct execution and output shape for a CV tape
        with a single expval output"""
        dev = qml.device("default.gaussian", wires=2)
        x = 0.543
        y = -0.654

        with QuantumTape() as tape:
            qml.Displacement(x, 0, wires=[0])
            qml.Squeezing(y, 0, wires=[1])
            qml.Beamsplitter(np.pi / 4, 0, wires=[0, 1])
            qml.expval(qml.NumberOperator(0))

        assert tape.output_dim == 1

        res = tape.execute(dev)
        assert res.shape == (1, )
Beispiel #23
0
    def test_samples_expval(self):
        """Test that multiple arrays of values are returned
        for combinations of samples and statistics"""
        dev = qml.device("default.qubit", wires=2, shots=10)
        x = 0.543
        y = -0.654

        with QuantumTape() as tape:
            qml.RX(x, wires=[0])
            qml.RY(y, wires=[1])
            qml.CNOT(wires=[0, 1])
            qml.sample(qml.PauliZ(0))
            qml.expval(qml.PauliZ(1))

        res = tape.execute(dev)
        assert res[0].shape == (10, )
        assert isinstance(res[1], float)
Beispiel #24
0
    def test_recording_stopped(self):
        """Test that recording is stopped within a tape context"""

        with QuantumTape() as tape:
            op0 = qml.RX(0, wires=0)
            assert tape.active_context() is tape

            with tape.stop_recording():
                op1 = qml.RY(1.0, wires=1)
                assert tape.active_context() is None

            op2 = qml.RZ(2, wires=1)
            assert tape.active_context() is tape

        assert len(tape.operations) == 2
        assert tape.operations[0] == op0
        assert tape.operations[1] == op2
Beispiel #25
0
def test_pl_to_braket_circuit():
    """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.PauliZ(0))

    braket_circuit_true = (Circuit().rx(0, 0.2).rx(1, 0.3).cnot(
        0, 1).add_result_type(
            result_types.Expectation(observable=Observable.Z(), target=0)))

    braket_circuit = dev._pl_to_braket_circuit(tape)

    assert braket_circuit_true == braket_circuit
Beispiel #26
0
    def test_blocking_IsingXX(self):
        """Tests the position of layers when a multiwire gate is blocking another gate on its empty wire."""

        with QuantumTape() as tape:
            qml.PauliX(0)
            qml.IsingXX(1.234, wires=(0, 2))
            qml.PauliX(1)

        _, ax = tape_mpl(tape, wire_order=[0, 1, 2])

        assert ax.patches[0].get_xy() == (-0.4, -0.4)  # layer=0, wire=0
        assert ax.patches[1].get_xy() == (0.6, -0.4)  # layer=1, wire=0
        assert ax.patches[2].get_xy() == (1.6, 0.6)  # layer=2, wire=1

        assert ax.texts[3].get_text() == "X"
        assert ax.texts[4].get_text() == "IsingXX"
        assert ax.texts[5].get_text() == "X"
Beispiel #27
0
    def test_get_parameters(self):
        """Test that the get_parameters function correctly gets the trainable parameters and all
        parameters, depending on the trainable_only argument"""
        a = np.array(0.1, requires_grad=True)
        b = np.array(0.2, requires_grad=False)
        c = np.array(0.3, requires_grad=True)
        d = np.array(0.4, requires_grad=False)

        with AutogradInterface.apply(QuantumTape()) as tape:
            qml.Rot(a, b, c, wires=0)
            qml.RX(d, wires=1)
            qml.CNOT(wires=[0, 1])
            qml.expval(qml.PauliX(0))

        assert tape.trainable_params == {0, 2}
        assert np.all(tape.get_parameters(trainable_only=True) == [a, c])
        assert np.all(tape.get_parameters(trainable_only=False) == [a, b, c, d])
Beispiel #28
0
    def test_single_layer(self):
        """Test a single layer with multiple wires. Check that the expected number
        of wires are drawn, and they are in the correct location."""

        with QuantumTape() as tape:
            qml.PauliX(0)
            qml.PauliY(1)
            qml.PauliZ(2)

        _, ax = tape_mpl(tape)

        assert len(ax.lines) == 3
        for wire, line in enumerate(ax.lines):
            assert line.get_xdata() == (-1, 1)  # from -1 to number of layers
            assert line.get_ydata() == (wire, wire)

        plt.close()
Beispiel #29
0
    def test_get_parameters(self):
        """Test that the get parameters function correctly sets and returns the
        trainable parameters"""
        a = tf.Variable(0.1)
        b = tf.constant(0.2)
        c = tf.Variable(0.3)
        d = 0.4

        with tf.GradientTape() as tape:
            with TFInterface.apply(QuantumTape()) as qtape:
                qml.Rot(a, b, c, wires=0)
                qml.RX(d, wires=1)
                qml.CNOT(wires=[0, 1])
                qml.expval(qml.PauliX(0))

        assert qtape.trainable_params == {0, 2}
        assert np.all(qtape.get_parameters() == [a, c])
    def test_analytic_method(self, mocker):
        """Test that calling the Jacobian with method=analytic correctly
        calls the analytic_pd method"""
        mock = mocker.patch("pennylane.tape.JacobianTape._grad_method")
        mock.return_value = "A"

        with JacobianTape() as tape:
            qml.RX(0.543, wires=[0])
            qml.RY(-0.654, wires=[0])
            qml.expval(qml.PauliY(0))

        dev = qml.device("default.qubit", wires=1)
        tape.analytic_pd = mocker.Mock()
        tape.analytic_pd.return_value = [[QuantumTape()], lambda res: np.array([1.0])]

        tape.jacobian(dev, method="analytic")
        assert len(tape.analytic_pd.call_args_list) == 2