Esempio n. 1
0
def test_phase():
    dev = qml.device("default.qubit", analytic=True, wires=1)
    theta = 0.2

    @qml.qnode(dev)
    def circuit():
        qml.PhaseShift(theta, wires=[
            0,
        ])
        return (qml.expval(qml.PauliX(0)))

    qc = QuantumCircuit(2, [
        Phase(wires=[
            0,
        ], value=[
            theta,
        ]),
    ],
                        device="CPU")
    obs = [Observable("x", wires=[
        0,
    ])]
    phi = qc.circuit(qc.phi)
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    qc_tf = qc._sess.run(expval_layer(phi))
    qc_tf = qc_tf.flatten()
    qc_pl = circuit()
    assert all(np.isclose(qc_pl, qc_tf))
Esempio n. 2
0
def sampling_double_qubit():

    qc = QuantumCircuit(2, [Hadamard(wires=[
        0,
    ]), Hadamard(wires=[
        1,
    ])],
                        device='CPU')
    obs = [
        Observable("x", wires=[
            0,
        ]),
        Observable("z", wires=[
            0,
        ]),
        Observable("x", wires=[
            1,
        ]),
        Observable("z", wires=[
            1,
        ])
    ]
    phi = qc.circuit(qc.phi)
    qc.initialize()
    expval_layer = SampleExpectationValue(obs, number_of_samples=200)
    expvals = qc._sess.run(expval_layer(phi))
    print(expvals.shape)
    for e in expvals:
        print(e)
Esempio n. 3
0
def test_batching_wave_functions_and_parameters():
    N = 3
    d = 13
    qc = QuantumCircuit(N, [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])],
                        batch_params=True,
                        device="CPU")
    psi = tf.placeholder(dtype=tf.complex64,
                         shape=(None, *[2 for _ in range(N)]))
    theta = tf.convert_to_tensor([np.pi, np.pi])
    with pytest.raises(
            AssertionError,
            match=
            "expected tensor with 3 dimensions, received tensor with shape"):
        qc.set_parameters(theta)
    qc.set_parameters(tf.reshape(theta, (1, 2, 1)))
    with pytest.raises(
            AssertionError,
            match=
            "We cannot have a batch of wave functions and a batch of parameters at the same time"
    ):
        qc.circuit(psi)
Esempio n. 4
0
def test_batching_works_correctly():
    N = 2
    qc = QuantumCircuit(N, [Hadamard(wires=[
        0,
    ]), Hadamard(wires=[
        1,
    ])],
                        device="CPU")
    obs = [Observable("x", wires=[
        0,
    ]), Observable("x", wires=[
        1,
    ])]
    phi = tf.placeholder(dtype=tf.complex64,
                         shape=(None, *[2 for _ in range(N)]))
    expval_layer = ExpectationValue(obs)

    phi_batch = qc.circuit(phi)
    expvals = expval_layer(phi_batch)

    # four basis states
    states = np.eye(int(2**N))
    qc.initialize()
    out_batch = qc._sess.run(
        [expvals], feed_dict={phi: states.reshape(-1,
                                                  *[2 for _ in range(N)])})[0]
    out_batch = out_batch.reshape((-1, ))
    assert np.allclose(out_batch, np.array([1, 1, 1, -1, -1, 1, -1, -1]))
Esempio n. 5
0
def test_toffoli():
    dev = qml.device("default.qubit", analytic=True, wires=3)

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

    @qml.qnode(dev)
    def circuity():
        qml.Hadamard(wires=0)
        qml.Hadamard(wires=1)
        qml.Hadamard(wires=2)
        qml.Toffoli(wires=[0, 1, 2])
        return qml.expval(qml.PauliY(2))

    @qml.qnode(dev)
    def circuitz():
        qml.Hadamard(wires=0)
        qml.Hadamard(wires=1)
        qml.Hadamard(wires=2)
        qml.Toffoli(wires=[0, 1, 2])
        return qml.expval(qml.PauliZ(2))

    qc_pl = np.array([circuitx(), circuity(), circuitz()])
    qc = QuantumCircuit(3, [
        Hadamard(wires=[
            0,
        ]),
        Hadamard(wires=[
            1,
        ]),
        Hadamard(wires=[
            2,
        ]),
        Toffoli(wires=[0, 2, 1])
    ],
                        device="CPU")
    obs = [
        Observable("x", wires=[
            2,
        ]),
        Observable("y", wires=[
            2,
        ]),
        Observable("z", wires=[
            2,
        ])
    ]
    phi = qc.circuit(qc.phi)
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    qc_tf = qc._sess.run(expval_layer(phi))
    qc_tf = qc_tf.flatten()
    assert all(np.isclose(qc_pl, qc_tf))
Esempio n. 6
0
def test_rotations_and_cnot():
    dev = qml.device("default.qubit", analytic=True, wires=2)
    theta = 0.1
    phi = 0.2

    @qml.qnode(dev)
    def circuitx():
        qml.RX(theta, wires=0)
        qml.RY(phi, wires=1)
        qml.CNOT(wires=[1, 0])
        return qml.expval(qml.PauliX(0))

    @qml.qnode(dev)
    def circuity():
        qml.RX(theta, wires=0)
        qml.RY(phi, wires=1)
        qml.CNOT(wires=[1, 0])
        return qml.expval(qml.PauliY(0))

    @qml.qnode(dev)
    def circuitz():
        qml.RX(theta, wires=0)
        qml.RY(phi, wires=1)
        qml.CNOT(wires=[1, 0])
        return qml.expval(qml.PauliZ(0))

    qc_pl = np.array([circuitx(), circuity(), circuitz()])
    qc = QuantumCircuit(2, [
        RX(wires=[
            0,
        ], value=[theta]),
        RY(wires=[
            1,
        ], value=[phi]),
        CNOT(wires=[1, 0])
    ],
                        device="CPU")
    obs = [
        Observable("x", wires=[
            0,
        ]),
        Observable("y", wires=[
            0,
        ]),
        Observable("z", wires=[
            0,
        ])
    ]
    phi = qc.circuit(qc.phi)
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    qc_tf = qc._sess.run(expval_layer(phi))
    qc_tf = qc_tf.flatten()
    assert all(np.isclose(qc_pl, qc_tf))
Esempio n. 7
0
def test_batch_params_batch_dim():
    N = 3
    qc = QuantumCircuit(N, [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])],
                        batch_params=True)
    with pytest.raises(
            AssertionError,
            match="batch_params=True, but no external input provided."):
        qc.circuit(qc.phi)
Esempio n. 8
0
def test_batch_params_argument():
    N = 3
    theta = tf.placeholder(dtype=tf.float32, shape=(None, 2, 1))
    qc = QuantumCircuit(N, [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])])
    with pytest.raises(
            AssertionError,
            match=
            " pass the batch_params=True argument to the QuantumCircuit class to enable batches of parameters."
    ):
        qc.set_parameters(theta)
        qc.circuit(qc.phi)
Esempio n. 9
0
def test_tutorial_1():
    gates = [Hadamard(wires=[
        0,
    ]), PauliZ(wires=[
        0,
    ])]
    qc = QuantumCircuit(nqubits=1, gates=gates, device="CPU")
    qc.initialize()
    phi = qc.circuit(qc.phi)

    qc_tf = qc._sess.run(phi)
    obs = [Observable("x", wires=[
        0,
    ])]
    expval_layer = ExpectationValue(obs)
    measurements = qc._sess.run(expval_layer(phi))
Esempio n. 10
0
def sampling_single_qubit():

    qc = QuantumCircuit(1, [Hadamard(wires=[
        0,
    ])], device='CPU')
    obs = [Observable("x", wires=[
        0,
    ]), Observable("z", wires=[
        0,
    ])]
    phi = qc.circuit(qc.phi)

    expval_layer = SampleExpectationValue(obs)
    qc.initialize()
    expvals = qc._sess.run(expval_layer(phi))
    print(expvals)
Esempio n. 11
0
def test_external_input_dtype():
    N = 3
    qc = QuantumCircuit(N, [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])],
                        batch_params=True,
                        device="CPU")
    with pytest.raises(TypeError,
                       match="External input Tensor must have type "):
        theta = tf.placeholder(dtype=tf.complex64, shape=(None, 2, 1))
        qc.set_parameters(theta)
    with pytest.raises(TypeError,
                       match="External input Tensor must have type "):
        theta = tf.placeholder(dtype=tf.float64, shape=(None, 2, 1))
        qc.set_parameters(theta)
Esempio n. 12
0
def test_tutorial_2():
    gates = [
        Hadamard(wires=[
            0,
        ]),
        Phase(wires=[
            0,
        ], value=[np.pi / 8]),
        Hadamard(wires=[
            1,
        ]),
        Phase(wires=[
            1,
        ], value=[np.pi / 8]),
        CNOT(wires=[0, 1])
    ]

    qc = QuantumCircuit(nqubits=2, gates=gates, tensorboard=True, device="CPU")

    phi = qc.circuit(qc.phi)
    qc.circuit.summary()
    obs = [
        Observable("X", wires=[
            0,
        ]),
        Observable("x", wires=[
            1,
        ]),
        Observable("y", wires=[
            0,
        ]),
        Observable("y", wires=[
            1,
        ]),
        Observable("z", wires=[
            0,
        ]),
        Observable("z", wires=[
            1,
        ])
    ]
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    measurements = qc._sess.run(expval_layer(phi))
Esempio n. 13
0
def test_batching_wave_functions():
    N = 3
    d = 13
    qc = QuantumCircuit(N, [Hadamard(wires=[
        0,
    ]), Hadamard(wires=[
        1,
    ])],
                        device="CPU")
    psi = tf.placeholder(dtype=tf.complex64,
                         shape=(None, *[2 for _ in range(N)]))
    phi_dim_1 = qc.circuit(qc.phi)
    phi_batch = qc.circuit(psi)
    qc.initialize()
    phi_feed = np.zeros([2 for _ in range(N)])
    phi_feed[0, ] = 1
    phi_feed = np.stack([phi_feed for _ in range(d)]).astype(np.complex64)
    out_1, out_batch = qc._sess.run([phi_dim_1, phi_batch],
                                    feed_dict={psi: phi_feed})
Esempio n. 14
0
def test_batching_learning_observables():
    N = 3
    d = 13
    qc = QuantumCircuit(N, [Hadamard(wires=[
        0,
    ]), Hadamard(wires=[
        1,
    ])],
                        device="CPU")
    psi = tf.placeholder(dtype=tf.complex64,
                         shape=(None, *[2 for _ in range(N)]))
    phi_dim_1 = qc.circuit(qc.phi)
    phi_batch = qc.circuit(psi)
    qc.initialize()
    obs = [
        Observable("x", wires=[
            0,
        ]),
        Observable("x", wires=[
            1,
        ]),
        Observable("x", wires=[
            2,
        ]),
        Observable("y", wires=[
            0,
        ]),
        Observable("y", wires=[
            1,
        ]),
        Observable("y", wires=[
            2,
        ])
    ]
    expval_layer = ExpectationValue(obs)
    phi_feed = np.zeros([2 for _ in range(N)])
    phi_feed[0, ] = 1
    phi_feed = np.stack([phi_feed for _ in range(d)]).astype(np.complex64)
    out_1, out_batch = qc._sess.run(
        [expval_layer(phi_dim_1),
         expval_layer(phi_batch)],
        feed_dict={psi: phi_feed})
Esempio n. 15
0
def test_hybrid_neural_network_gradient_tracking():
    N = 2
    gates = [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])]
    qc = QuantumCircuit(N, gates=gates, tensorboard=True, device="CPU")

    # Make a neural network
    NN = tf.keras.Sequential([
        tf.keras.layers.Dense(qc.nparams * 10,
                              activation=tf.keras.activations.tanh),
        tf.keras.layers.Dense(2, activation=tf.keras.activations.tanh),
        tf.keras.layers.Lambda(lambda x: x * 2 * np.pi)
    ])
    x_in = tf.ones((qc.nparams, 1)) * 0.01
    theta = NN(x_in)
    theta = tf.reduce_mean(theta, axis=0)
    theta = tf.reshape(theta, (1, -1, 1))

    qc.set_parameters(theta)
    phi = qc.circuit(qc.phi)
    obs = Observable("x", wires=[
        0,
    ]), Observable("x", wires=[
        1,
    ]), Observable("z", wires=[
        1,
    ])
    expval_layer = ExpectationValue(obs)
    expvals = expval_layer(phi)

    # Get energy for each timstep
    energy = tf.reduce_sum(expvals)

    opt = tf.compat.v1.train.AdamOptimizer(0.0001)
    grads = opt.compute_gradients(energy)
    qc.initialize()

    g = qc._sess.run(grads)
Esempio n. 16
0
def test_pauli_x():
    dev = qml.device("default.qubit", analytic=True, wires=1)

    @qml.qnode(dev)
    def circuitx():
        qml.PauliX(wires=0)
        return qml.expval(qml.PauliX(0))

    @qml.qnode(dev)
    def circuity():
        qml.PauliX(wires=0)
        return qml.expval(qml.PauliY(0))

    @qml.qnode(dev)
    def circuitz():
        qml.PauliX(wires=0)
        return qml.expval(qml.PauliZ(0))

    qc_pl = np.array([circuitx(), circuity(), circuitz()])
    qc = QuantumCircuit(1, [PauliX(wires=[
        0,
    ])], device="CPU")
    obs = [
        Observable("x", wires=[
            0,
        ]),
        Observable("y", wires=[
            0,
        ]),
        Observable("z", wires=[
            0,
        ])
    ]
    phi = qc.circuit(qc.phi)
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    qc_tf = qc._sess.run(expval_layer(phi))
    qc_tf = qc_tf.flatten()
    assert all(np.isclose(qc_pl, qc_tf))
Esempio n. 17
0
def test_swap():
    dev = qml.device("default.qubit", analytic=True, wires=2)
    theta = 0.2
    phi = 0.2
    delta = 0.2

    @qml.qnode(dev)
    def circuit():
        qml.Rot(theta, phi, delta, wires=0)
        qml.Rot(theta, phi, delta, wires=1)
        qml.SWAP(wires=[0, 1])
        return (
            qml.expval(qml.PauliX(0)),
            qml.expval(qml.PauliX(1)),
        )

    qc = QuantumCircuit(2, [
        R3(wires=[
            0,
        ], value=[theta, phi, delta]),
        R3(wires=[
            1,
        ], value=[theta, phi, delta]),
        Swap(wires=[0, 1])
    ],
                        device="CPU")
    obs = [Observable("x", wires=[
        0,
    ]), Observable("x", wires=[
        1,
    ])]
    psi = qc.circuit(qc.phi)
    expval_layer = ExpectationValue(obs)
    qc.initialize()
    qc_tf = qc._sess.run(expval_layer(psi))
    qc_tf = qc_tf.flatten()
    qc_pl = circuit()
    assert all(np.isclose(qc_pl, qc_tf))
Esempio n. 18
0
def test_multiple_thetas():
    N = 3
    d = 13
    theta = tf.placeholder(dtype=tf.float32, shape=(None, 2, 1))
    qc = QuantumCircuit(N, [RX(wires=[
        0,
    ]), RX(wires=[
        1,
    ])],
                        batch_params=True,
                        device="CPU")
    qc.set_parameters(theta)
    phi_dim_1 = qc.circuit(qc.phi)
    obs = [
        Observable("x", wires=[
            0,
        ]),
        Observable("x", wires=[
            1,
        ]),
        Observable("x", wires=[
            2,
        ]),
        Observable("y", wires=[
            0,
        ]),
        Observable("y", wires=[
            1,
        ]),
        Observable("y", wires=[
            2,
        ])
    ]
    expval_layer = ExpectationValue(obs)

    expvals_dim_1 = expval_layer(phi_dim_1)
    qc.initialize()
    qc._sess.run([expvals_dim_1], feed_dict={theta: np.random.randn(d, 2, 1)})
Esempio n. 19
0
def test_same_wire_gates():
    qc = QuantumCircuit(2, [RX(wires=[
        0,
    ]) for i in range(10)], device="CPU")
    qc.initialize()
    qc.circuit(qc.phi)
Esempio n. 20
0
from zyglrox.core.circuit import QuantumCircuit
from zyglrox.core.gates import *
import numpy as np

qc = QuantumCircuit(
    10, [Hadamard(wires=[
        i,
    ]) for i in np.random.randint(0, 9, 100)],
    device='GPU',
    ngpus=1,
    tensorboard=True)
output = qc.execute()
qc.initialize()
print(qc._sess.run(output))
Esempio n. 21
0
]) for i in range(N)])
for l in range(p):
    for j in range(0, N - 1, 2):
        gates.append(ZZ(wires=[j, j + 1]))

    for j in range(1, N - 1, 2):
        gates.append(ZZ(wires=[j, j + 1]))

    gates.append(ZZ(wires=[N - 1, 0]))
    gates.extend([RX(wires=[
        i,
    ]) for i in range(N)])

qc = QuantumCircuit(N,
                    gates,
                    circuit_order='layer',
                    get_phi_per_layer=True,
                    tensorboard=True)
# print(qc.phi_per_layer)
phi = qc.execute()
all_ptr_rhos = partial_trace(qc.phi_per_layer, [0, 1],
                             [-1] + [2 for _ in range(N)])
# vn_entropies = von_neumann_entropy(all_ptr_rhos)
# ry_entropies = renyi_entropy(all_ptr_rhos, alpha=0.99)
qc.initialize()
lam, _ = qc._sess.run(tf.linalg.eigh(all_ptr_rhos))
print(np.sum(lam, axis=1))
#
# rhos, vns, rys = qc._sess.run([all_ptr_rhos, vn_entropies, ry_entropies])
# for p in rhos:
#     print(p)