Exemplo n.º 1
0
def test_invalid_wires():
    """Test that an exception is raised if a wire in the wire
    ordering does not exist on the device"""
    dev = qml.device("default.qubit", wires=["a", -1, "q2"])

    @qml.qnode(dev)
    def circuit():
        qml.Hadamard(wires=-1)
        qml.CNOT(wires=["a", "q2"])
        qml.RX(0.2, wires="a")
        return qml.expval(qml.PauliX(wires="q2"))

    with pytest.raises(ValueError, match="contains wires not contained on the device"):
        qml.draw(circuit, wire_order=["q2", 5])()
Exemplo n.º 2
0
def test_show_all_wires_error():
    """Test that show_all_wires will raise an error if the provided wire
    order does not contain all wires on the device"""

    dev = qml.device('default.qubit', wires=[-1, "a", "q2", 0])

    @qml.qnode(dev)
    def circuit():
        qml.Hadamard(wires=-1)
        qml.CNOT(wires=[-1, "q2"])
        return qml.expval(qml.PauliX(wires="q2"))

    with pytest.raises(ValueError, match="must contain all wires"):
        qml.draw(circuit, show_all_wires=True, wire_order=[-1, "a"])()
Exemplo n.º 3
0
def test_drawing_ascii():
    """Test circuit drawing when using ASCII characters"""
    from pennylane import numpy as np

    x = np.array(0.1, requires_grad=True)
    y = np.array([0.2, 0.3], requires_grad=True)
    z = np.array(0.4, requires_grad=True)

    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev, interface="autograd")
    def circuit(p1, p2=y, **kwargs):
        qml.RX(p1, wires=0)
        qml.RY(p2[0] * p2[1], wires=1)
        qml.RX(kwargs["p3"], wires=0)
        qml.CNOT(wires=[0, 1])
        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))

    result = qml.draw(circuit, charset="ascii")(p1=x, p3=z)
    expected = """\
 0: --RX(0.1)---RX(0.4)--+C--+| <Z @ X> 
 1: --RY(0.06)-----------+X--+| <Z @ X> 
"""

    assert result == expected
Exemplo n.º 4
0
def test_drawing_jax():
    """Test circuit drawing when using JAX"""
    jax = pytest.importorskip("jax")
    jnp = jax.numpy

    x = jnp.array(0.1)
    y = jnp.array([0.2, 0.3])
    z = jnp.array(0.4)

    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev, interface="jax")
    def circuit(p1, p2=y, **kwargs):
        qml.RX(p1, wires=0)
        qml.RY(p2[0] * p2[1], wires=1)
        qml.RX(kwargs["p3"], wires=0)
        qml.CNOT(wires=[0, 1])
        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))

    result = qml.draw(circuit)(p1=x, p3=z)
    expected = """\
 0: ──RX(0.1)───RX(0.4)──╭C──╭┤ ⟨Z ⊗ X⟩ 
 1: ──RY(0.06)───────────╰X──╰┤ ⟨Z ⊗ X⟩ 
"""

    assert result == expected
Exemplo n.º 5
0
def test_drawing_tf():
    """Test circuit drawing when using TensorFlow"""
    tf = pytest.importorskip("tensorflow")

    x = tf.constant(0.1)
    y = tf.constant([0.2, 0.3])
    z = tf.Variable(0.4)

    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev, interface="tf")
    def circuit(p1, p2=y, **kwargs):
        qml.RX(p1, wires=0)
        qml.RY(p2[0] * p2[1], wires=1)
        qml.RX(kwargs["p3"], wires=0)
        qml.CNOT(wires=[0, 1])
        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))

    result = qml.draw(circuit)(p1=x, p3=z)
    expected = """\
 0: ──RX(0.1)───RX(0.4)──╭C──╭┤ ⟨Z ⊗ X⟩ 
 1: ──RY(0.06)───────────╰X──╰┤ ⟨Z ⊗ X⟩ 
"""

    assert result == expected
Exemplo n.º 6
0
def test_drawing_torch():
    """Test circuit drawing when using Torch"""
    torch = pytest.importorskip("torch")

    x = torch.tensor(0.1, requires_grad=True)
    y = torch.tensor([0.2, 0.3], requires_grad=True)
    z = torch.tensor(0.4, requires_grad=True)

    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev, interface="torch")
    def circuit(p1, p2=y, **kwargs):
        qml.RX(p1, wires=0)
        qml.RY(p2[0] * p2[1], wires=1)
        qml.RX(kwargs["p3"], wires=0)
        qml.CNOT(wires=[0, 1])
        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))

    result = qml.draw(circuit)(p1=x, p3=z)
    expected = """\
 0: ──RX(0.1)───RX(0.4)──╭C──╭┤ ⟨Z ⊗ X⟩ 
 1: ──RY(0.06)───────────╰X──╰┤ ⟨Z ⊗ X⟩ 
"""

    assert result == expected
def simple_circuits_50(angle):
    """The code you write for this challenge should be completely contained within this function
        between the # QHACK # comment markers.

    In this function:
        * Create the standard Bell State
        * Rotate the first qubit around the y-axis by angle
        * Measure the expectation value of the tensor observable `qml.PauliZ(0) @ qml.PauliZ(1)`

    Args:
        angle (float): how much to rotate a state around the y-axis

    Returns:
        float: the expectation value of the tensor observable
    """

    expectation_value = 0.0

    # QHACK #

    # Step 1 : initialize a device
    dev = qml.device('default.qubit', wires=2)

    # Step 2 : Create a quantum circuit and qnode
    @qml.qnode(dev)
    def circuit_50(param):
        # Bell state
        qml.Hadamard(wires=0)
        qml.CNOT(wires=[0, 1])

        qml.RY(param, wires=0)
        return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))

    # Step 3 : Run the qnode
    # expectation_value = ?
    expectation_value = circuit_50(angle)

    # debug
    qml.draw(circuit_50)

    # QHACK #
    return expectation_value
Exemplo n.º 8
0
def test_missing_wire():
    """Test that wires not specifically mentioned in the wire
    reordering are appended at the bottom of the circuit drawing"""

    dev = qml.device("default.qubit", wires=["a", -1, "q2"])

    @qml.qnode(dev)
    def circuit():
        qml.Hadamard(wires=-1)
        qml.CNOT(wires=["a", "q2"])
        qml.RX(0.2, wires="a")
        return qml.expval(qml.PauliX(wires="q2"))

    # test one missing wire
    res = qml.draw(circuit, wire_order=["q2", "a"])()
    expected = [
        " q2: ──╭X───────────┤ ⟨X⟩ ",
        "  a: ──╰C──RX(0.2)──┤     ",
        " -1: ───H───────────┤     \n",
    ]

    assert res == "\n".join(expected)

    # test one missing wire
    res = qml.draw(circuit, wire_order=["q2", -1])()
    expected = [
        " q2: ─────╭X───────────┤ ⟨X⟩ ",
        " -1: ──H──│────────────┤     ",
        "  a: ─────╰C──RX(0.2)──┤     \n",
    ]

    assert res == "\n".join(expected)

    # test multiple missing wires
    res = qml.draw(circuit, wire_order=["q2"])()
    expected = [
        " q2: ─────╭X───────────┤ ⟨X⟩ ",
        " -1: ──H──│────────────┤     ",
        "  a: ─────╰C──RX(0.2)──┤     \n",
    ]

    assert res == "\n".join(expected)
Exemplo n.º 9
0
def test_matrix_parameter_template():
    """Assert draw method handles templates with matrix valued parameters."""
    dev = qml.device("default.qubit", wires=1)

    @qml.qnode(dev)
    def circuit():
        qml.AmplitudeEmbedding(np.array([0, 1]), wires=0)
        return qml.state()

    expected = " 0: ──AmplitudeEmbedding(M0)──┤ State \nM0 =\n[0.+0.j 1.+0.j]\n"
    assert qml.draw(circuit)() == expected
Exemplo n.º 10
0
    def qnode():
        for i in range(3):
            qml.Hadamard(wires=i)
            qml.RX(i * 0.1, wires=i)
            qml.RY(i * 0.1, wires=i)
            qml.RZ(i * 0.1, wires=i)
        return qml.expval(qml.PauliZ(0))

        expected = (" 0: ──H──RX(0)────RY(0)────RZ(0)────┤ ⟨Z⟩\n" +
                    " 1: ──H──RX(0.1)──RY(0.1)──RZ(0.1)──┤    \n" +
                    " 2: ──H──RX(0.2)──RY(0.2)──RZ(0.2)──┤    \n")
        assert qml.draw(qnode, max_length=60)() == expected
Exemplo n.º 11
0
def test_direct_qnode_integration():
    """Test that a QNode renders correctly."""
    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev)
    def qfunc(a, w):
        qml.Hadamard(0)
        qml.CRX(a, wires=[0, 1])
        qml.Rot(w[0], w[1], w[2], wires=[1])
        qml.CRX(-a, wires=[0, 1])

        return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))

    a, w = 2.3, [1.2, 3.2, 0.7]

    assert qml.draw(qfunc)(a, w) == (
        " 0: ──H──╭C────────────────────────────╭C─────────╭┤ ⟨Z ⊗ Z⟩ \n" +
        " 1: ─────╰RX(2.3)──Rot(1.2, 3.2, 0.7)──╰RX(-2.3)──╰┤ ⟨Z ⊗ Z⟩ \n")

    assert qml.draw(qfunc, charset="ascii")(a, w) == (
        " 0: --H--+C----------------------------+C---------+| <Z @ Z> \n" +
        " 1: -----+RX(2.3)--Rot(1.2, 3.2, 0.7)--+RX(-2.3)--+| <Z @ Z> \n")
Exemplo n.º 12
0
    def test_circuit_drawer(self):
        """Test that the circuit drawer displays Hamiltonians well."""
        dev = qml.device("default.qubit", wires=3)
        coeffs = [1.0, 1.0, 1.0]
        observables1 = [qml.PauliZ(0), qml.PauliY(0), qml.PauliZ(2)]
        H1 = qml.Hamiltonian(coeffs, observables1)

        @qml.qnode(dev)
        def circuit1():
            qml.Hadamard(wires=0)
            return qml.expval(H1)

        res = qml.draw(circuit1)()
        expected = " 0: ──H──╭┤ ⟨Hamiltonian(1, 1, 1)⟩ \n" + " 2: ─────╰┤ ⟨Hamiltonian(1, 1, 1)⟩ \n"
        assert res == expected
Exemplo n.º 13
0
def test_draw_batch_transform(transform):
    """Test that drawing a batch transform works correctly"""
    dev = qml.device("default.qubit", wires=1)

    @transform
    @qml.qnode(dev)
    def circuit(x):
        qml.Hadamard(wires=0)
        qml.RX(x, wires=0)
        return qml.expval(qml.PauliZ(wires=0))

    # the parameter-shift transform will create two circuits; one with x+0.2
    # and one with x-0.2.
    res = qml.draw(circuit)(0.6)
    expected = [" 0: ──H──RX(0.8)──┤ ⟨Z⟩ ", "", " 0: ──H──RX(0.4)──┤ ⟨Z⟩ ", ""]
    assert res == "\n".join(expected)
Exemplo n.º 14
0
    def test_no_ops_draws(self):
        """Test that a QNode with no operations still draws correctly"""
        dev = qml.device("default.qubit", wires=3)

        @qml.qnode(dev)
        def qnode():
            return qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[2]))

        res = qml.draw(qnode)()
        expected = [
            " 0: ──╭┤ ⟨X ⊗ X ⊗ X⟩ \n",
            " 1: ──├┤ ⟨X ⊗ X ⊗ X⟩ \n",
            " 2: ──╰┤ ⟨X ⊗ X ⊗ X⟩ \n",
        ]

        assert res == "".join(expected)
Exemplo n.º 15
0
    def test_approx_time_evolution(self):
        """Test that a QNode with the ApproxTimeEvolution template draws
        correctly when having the expansion strategy set."""
        H = qml.PauliX(0) + qml.PauliZ(1) + 0.5 * qml.PauliX(0) @ qml.PauliX(1)

        @qml.qnode(qml.device("default.qubit", wires=2))
        def circuit(t):
            qml.ApproxTimeEvolution(H, t, 2)
            return qml.probs(wires=0)

        res = qml.draw(circuit, expansion_strategy="device")(0.5)
        expected = [
            " 0: ──H────────RZ(0.5)──H──H──╭RZ(0.25)──H──H────────RZ(0.5)──H──H──╭RZ(0.25)──H──┤ Probs \n",
            " 1: ──RZ(0.5)──H──────────────╰RZ(0.25)──H──RZ(0.5)──H──────────────╰RZ(0.25)──H──┤       \n",
        ]

        assert res == "".join(expected)
Exemplo n.º 16
0
    def test_default_ordering(self):
        """Test that the default wire ordering matches the device"""

        dev = qml.device("default.qubit", wires=["a", -1, "q2"])

        @qml.qnode(dev)
        def circuit():
            qml.Hadamard(wires=-1)
            qml.CNOT(wires=["a", "q2"])
            qml.RX(0.2, wires="a")
            return qml.expval(qml.PauliX(wires="q2"))

        res = qml.draw(circuit)()
        expected = [
            "  a: ─────╭C──RX(0.2)──┤     ",
            " -1: ──H──│────────────┤     ",
            " q2: ─────╰X───────────┤ ⟨X⟩ \n",
        ]

        assert res == "\n".join(expected)
Exemplo n.º 17
0
    def test_wire_reordering(self):
        """Test that wires are correctly reordered"""

        dev = qml.device("default.qubit", wires=["a", -1, "q2"])

        @qml.qnode(dev)
        def circuit():
            qml.Hadamard(wires=-1)
            qml.CNOT(wires=["a", "q2"])
            qml.RX(0.2, wires="a")
            return qml.expval(qml.PauliX(wires="q2"))

        res = qml.draw(circuit, wire_order=["q2", "a", -1])()
        expected = [
            " q2: ──╭X───────────┤ ⟨X⟩ ",
            "  a: ──╰C──RX(0.2)──┤     ",
            " -1: ───H───────────┤     \n",
        ]

        assert res == "\n".join(expected)
Exemplo n.º 18
0
    def test_include_empty_wires(self):
        """Test that empty wires are correctly included"""

        dev = qml.device("default.qubit", wires=[-1, "a", "q2", 0])

        @qml.qnode(dev)
        def circuit():
            qml.Hadamard(wires=-1)
            qml.CNOT(wires=[-1, "q2"])
            return qml.expval(qml.PauliX(wires="q2"))

        res = qml.draw(circuit, show_all_wires=True)()
        expected = [
            " -1: ──H──╭C──┤     ",
            "  a: ─────│───┤     ",
            " q2: ─────╰X──┤ ⟨X⟩ ",
            "  0: ─────────┤     \n",
        ]

        assert res == "\n".join(expected)
Exemplo n.º 19
0
def test_same_wire_multiple_measurements():
    """Test that drawing a QNode with multiple measurements on certain wires works correctly."""
    dev = qml.device("default.qubit", wires=4)

    @qml.qnode(dev)
    def qnode(x, y):
        qml.RY(x, wires=0)
        qml.Hadamard(0)
        qml.RZ(y, wires=0)
        return [
            qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[2])),
            qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[3])),
        ]

    expected = (
        " 0: ──RY(1)──H──RZ(2)──╭┤ ⟨X ⊗ X ⊗ X⟩ ╭┤ ⟨X ⊗ X⟩ \n"
        + " 1: ───────────────────├┤ ⟨X ⊗ X ⊗ X⟩ │┤         \n"
        + " 2: ───────────────────╰┤ ⟨X ⊗ X ⊗ X⟩ │┤         \n"
        + " 3: ────────────────────┤             ╰┤ ⟨X ⊗ X⟩ \n"
    )
    assert qml.draw(qnode)(1.0, 2.0) == expected
Exemplo n.º 20
0
def test_same_wire_multiple_measurements_many_obs():
    """Test that drawing a QNode with multiple measurements on certain
    wires works correctly when there are more observables than the number of
    observables for any wire.
    """
    dev = qml.device("default.qubit", wires=4)

    @qml.qnode(dev)
    def qnode(x, y):
        qml.RY(x, wires=0)
        qml.Hadamard(0)
        qml.RZ(y, wires=0)
        return [
            qml.expval(qml.PauliZ(0)),
            qml.expval(qml.PauliZ(1)),
            qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)),
        ]

    expected = (" 0: ──RY(0.3)──H──RZ(0.2)──┤ ⟨Z⟩ ┤     ╭┤ ⟨Z ⊗ Z⟩ \n" +
                " 1: ───────────────────────┤     ┤ ⟨Z⟩ ╰┤ ⟨Z ⊗ Z⟩ \n")
    assert qml.draw(qnode)(0.3, 0.2) == expected
Exemplo n.º 21
0
def test_drawing():
    """Test circuit drawing"""

    x = np.array(0.1, requires_grad=True)
    y = np.array([0.2, 0.3], requires_grad=True)
    z = np.array(0.4, requires_grad=True)

    dev = qml.device("default.qubit", wires=2)

    @qml.qnode(dev, interface="autograd")
    def circuit(p1, p2=y, **kwargs):
        qml.RX(p1, wires=0)
        qml.RY(p2[0] * p2[1], wires=1)
        qml.RX(kwargs["p3"], wires=0)
        qml.CNOT(wires=[0, 1])
        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))

    result = qml.draw(circuit)(p1=x, p3=z)
    expected = """\
 0: ──RX(0.1)───RX(0.4)──╭C──╭┤ ⟨Z ⊗ X⟩ 
 1: ──RY(0.06)───────────╰X──╰┤ ⟨Z ⊗ X⟩ 
"""

    assert result == expected
Exemplo n.º 22
0
    print(opt_cost)

    return weights


if __name__ == "__main__":
    np.random.seed(0)

    n_layers = 1
    how_many = 500
    X, Y, weights = hrcn.get_data_and_weights(dev_expval.wires, n_layers, how_many)
    #print(X)
    #print(Y)
    print(weights)

    drawer = qml.draw(combined_expval_train)
    print(drawer(weights, X[0], wires=dev_expval.wires))

    k = 1
    steps = 50
    batch_size = 10
    opt_weights = train(weights, dev_expval.wires, X, Y, steps, batch_size, k)
    #print(opt_weights)
    
    drawer = qml.draw(combined_expval_train)
    print(drawer(opt_weights, X[0], wires=dev_expval.wires))

    #
    # Accuracy on unseen test set
    #
    X_test, Y_test, not_used = hrcn.get_data_and_weights(dev_expval.wires, n_layers, 1000)
Exemplo n.º 23
0

if __name__ == "__main__":
    dev_expval = qml.device("default.qubit", wires=range(3))
    print(dev_expval)

    dev_1shot = qml.device("default.qubit", wires=range(3), shots=1)
    print(dev_1shot)

    @qml.qnode(dev_expval)
    def my_combined_expval(weights, x, wires):
        return combined_expval(weights, x, wires)

    @qml.qnode(dev_1shot)
    def my_combined_1shot(weights, x, wires):
        return combined_1shot(weights, x, wires)

    X, Y, weights = get_data_and_weights(dev_expval.wires, 2, 5)
    print(X)
    print(Y)
    print(weights)

    drawer = qml.draw(my_combined_expval)
    print(drawer(weights, X[0], wires=dev_expval.wires))

    # expval classifier output for sensor data x (weights were not optimized)
    print(my_combined_expval(weights, X[0], wires=dev_expval.wires))

    # 1shot classifier output for sensor data x (weights were not optimized)
    print(my_combined_1shot(weights, X[0], wires=dev_1shot.wires))
Exemplo n.º 24
0
 def draw(self):
     drawer = qml.draw(self._embedding_circuit_vector)
     dummy_features = np.ones(self.feature_shape)
     dummy_weights = np.ones(self.weight_shape)
     print(drawer(dummy_features, dummy_weights))
Exemplo n.º 25
0
    return weights


if __name__ == "__main__":
    np.random.seed(0)  ### This ensures results are reproducible

    n_layers = 1  ### number of layers, more than 1 makes sense when n_qubits > 1, or we use data re-upload
    how_many = 500  ### size of training set, random points on Bloch sphere
    X, Y, weights = hrcn.get_data_and_weights(dev_expval.wires, n_layers,
                                              how_many)
    #print(X)
    #print(Y)
    print(weights)

    drawer = qml.draw(combined_expval_train)
    print(drawer(weights, X[0], wires=dev_expval.wires))

    k = 1  ### power in cost function, 1 is the best, surprisingly
    steps = 50
    batch_size = 10
    opt_weights = train(weights, dev_expval.wires, X, Y, steps, batch_size, k)
    #print(opt_weights)

    drawer = qml.draw(
        combined_expval_train
    )  ### Sensor has RX and RY gates, then each classifier layer has RX, RY, and RZ, plus CNOTS (if n_qubits > 1)
    print(drawer(opt_weights, X[0], wires=dev_expval.wires))

    #
    # Accuracy on unseen test set
        for j in range(n_qubits):
            if x[j, 0] <= 0.0:
                n_east += 1
            else:
                n_west += 1

        # majority voting
        if n_west > n_east:
            Y[i] = -1

    return X, Y


if __name__ == "__main__":
    dev = qml.device("default.qubit", wires=range(3))

    @qml.qnode(dev)
    def my_circuit(x, wires):
        circuit(x, wires)
        return qml.expval(qml.PauliY(0))

    X, Y = get_labelled_dataset(dev.wires, 5)
    print(X)
    print(Y)

    drawer = qml.draw(my_circuit)
    print(drawer(X[0], dev.wires))

    x = np.array([[-np.pi / 2, 0.0], [0, 0], [0, 0]], dtype=np.float64)
    print(my_circuit(x, dev.wires))