Skip to content

Commit

Permalink
changes in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
renatomello committed Oct 31, 2024
1 parent a5fcf8d commit cc892a1
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 142 deletions.
28 changes: 14 additions & 14 deletions tests/test_backends_torch_gradients.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import numpy as np
import pytest

from qibo import gates, models
from qibo import Circuit, gates
from qibo.backends import PyTorchBackend, construct_backend
from qibo.quantum_info import infidelity

Expand All @@ -16,21 +16,21 @@ def test_torch_gradients():
target_state = backend.np.rand(4, dtype=backend.np.complex128)
target_state = target_state / backend.np.norm(target_state)
params = backend.np.rand(4, dtype=backend.np.float64, requires_grad=True)
c = models.Circuit(2)
c.add(gates.RX(0, params[0]))
c.add(gates.RY(1, params[1]))
c.add(gates.U2(1, params[2], params[3]))
circuit = Circuit(2)
circuit.add(gates.RX(0, params[0]))
circuit.add(gates.RY(1, params[1]))
circuit.add(gates.U2(1, params[2], params[3]))

initial_params = params.clone()
initial_loss = infidelity(
target_state, backend.execute_circuit(c).state(), backend=backend
target_state, backend.execute_circuit(circuit).state(), backend=backend
)

optimizer = optimizer([params], lr=0.01)
for _ in range(nepochs):
optimizer.zero_grad()
c.set_parameters(params)
final_state = backend.execute_circuit(c).state()
circuit.set_parameters(params)
final_state = backend.execute_circuit(circuit).state()
loss = infidelity(target_state, final_state, backend=backend)
loss.backward()
grad = params.grad.clone().norm()
Expand All @@ -51,13 +51,13 @@ def test_torch_tensorflow_gradients():

target_state = backend.np.tensor([0.0, 1.0], dtype=backend.np.complex128)
param = backend.np.tensor([0.1], dtype=backend.np.float64, requires_grad=True)
c = models.Circuit(1)
c.add(gates.RX(0, param[0]))
circuit = Circuit(1)
circuit.add(gates.RX(0, param[0]))

optimizer = backend.np.optim.SGD
optimizer = optimizer([param], lr=1)
c.set_parameters(param)
final_state = backend.execute_circuit(c).state()
final_state = backend.execute_circuit(circuit).state()
loss = infidelity(target_state, final_state, backend=backend)
loss.backward()
torch_param_grad = param.grad.clone().item()
Expand All @@ -66,14 +66,14 @@ def test_torch_tensorflow_gradients():

target_state = tf_backend.tf.constant([0.0, 1.0], dtype=tf_backend.tf.complex128)
param = tf_backend.tf.Variable([0.1], dtype=tf_backend.tf.float64)
c = models.Circuit(1)
c.add(gates.RX(0, param[0]))
c = Circuit(1)
circuit.add(gates.RX(0, param[0]))

optimizer = tf_backend.tf.optimizers.SGD(learning_rate=1.0)

with tf_backend.tf.GradientTape() as tape:
c.set_parameters(param)
final_state = tf_backend.execute_circuit(c).state()
final_state = tf_backend.execute_circuit(circuit).state()
loss = infidelity(target_state, final_state, backend=tf_backend)

grads = tape.gradient(loss, [param])
Expand Down
12 changes: 7 additions & 5 deletions tests/test_hamiltonians_terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import numpy as np
import pytest

from qibo import gates, matrices, models
from qibo import Circuit, gates, matrices
from qibo.hamiltonians import terms
from qibo.quantum_info import random_density_matrix, random_statevector

Expand Down Expand Up @@ -49,15 +49,17 @@ def test_hamiltonian_term_gates(backend):

initial_state = random_statevector(2**nqubits, backend=backend)
final_state = term(backend, backend.np.copy(initial_state), nqubits)
c = models.Circuit(nqubits)
c.add(gates.Unitary(matrix, 1, 2))
target_state = backend.execute_circuit(c, backend.np.copy(initial_state)).state()
circuit = Circuit(nqubits)
circuit.add(gates.Unitary(matrix, 1, 2))
target_state = backend.execute_circuit(
circuit, backend.np.copy(initial_state)
).state()
backend.assert_allclose(final_state, target_state)


def test_hamiltonian_term_exponentiation(backend):
"""Test exp gate application of ``HamiltonianTerm``."""
from scipy.linalg import expm
from scipy.linalg import expm # pylint: disable=C0415

matrix = np.random.random((2, 2))
term = terms.HamiltonianTerm(matrix, 1)
Expand Down
40 changes: 20 additions & 20 deletions tests/test_measurements_collapse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import numpy as np
import pytest

from qibo import gates, models
from qibo import Circuit, gates
from qibo.quantum_info import random_density_matrix, random_statevector


Expand All @@ -13,7 +13,7 @@
)
def test_measurement_collapse(backend, nqubits, targets):
initial_state = random_statevector(2**nqubits, backend=backend)
c = models.Circuit(nqubits)
c = Circuit(nqubits)
for q in np.random.randint(nqubits, size=np.random.randint(nqubits, size=1)):
c.add(gates.H(q))
r = c.add(gates.M(*targets, collapse=True))
Expand All @@ -39,7 +39,7 @@ def assign_value(rho, index, value):
return rho

initial_rho = random_density_matrix(2**nqubits, backend=backend)
c = models.Circuit(nqubits, density_matrix=True)
c = Circuit(nqubits, density_matrix=True)
r = c.add(gates.M(*targets, collapse=True))
final_rho = backend.execute_circuit(c, backend.np.copy(initial_rho), nshots=1)

Expand All @@ -60,23 +60,23 @@ def assign_value(rho, index, value):


def test_measurement_collapse_bitflip_noise(backend):
c = models.Circuit(4)
c = Circuit(4)
with pytest.raises(NotImplementedError):
output = c.add(gates.M(0, 1, p0=0.2, collapse=True))


@pytest.mark.parametrize("density_matrix", [True, False])
@pytest.mark.parametrize("effect", [False, True])
def test_measurement_result_parameters(backend, effect, density_matrix):
c = models.Circuit(4, density_matrix=density_matrix)
c = Circuit(4, density_matrix=density_matrix)
if effect:
c.add(gates.X(0))
r = c.add(gates.M(0, collapse=True))
c.add(gates.RX(1, theta=np.pi * r.symbols[0] / 4))
if not density_matrix:
c.add(gates.M(0))

target_c = models.Circuit(4, density_matrix=density_matrix)
target_c = Circuit(4, density_matrix=density_matrix)
if effect:
target_c.add(gates.X(0))
target_c.add(gates.RX(1, theta=np.pi / 4))
Expand All @@ -94,7 +94,7 @@ def test_measurement_result_parameters(backend, effect, density_matrix):
def test_measurement_result_parameters_random(backend):
initial_state = random_density_matrix(2**4, backend=backend)
backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
r = c.add(gates.M(1, collapse=True))
c.add(gates.RY(0, theta=np.pi * r.symbols[0] / 5))
c.add(gates.RX(2, theta=np.pi * r.symbols[0] / 4))
Expand All @@ -103,13 +103,13 @@ def test_measurement_result_parameters_random(backend):
)

backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
m = c.add(gates.M(1, collapse=True))
target_state = backend.execute_circuit(
c, initial_state=backend.np.copy(initial_state), nshots=1
).state()
if int(m.symbols[0].outcome()):
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
c.add(gates.RY(0, theta=np.pi / 5))
c.add(gates.RX(2, theta=np.pi / 4))
target_state = backend.execute_circuit(c, initial_state=target_state)
Expand All @@ -120,7 +120,7 @@ def test_measurement_result_parameters_random(backend):
def test_measurement_result_parameters_repeated_execution(backend, use_loop):
initial_state = random_density_matrix(2**4, backend=backend)
backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
r = c.add(gates.M(1, collapse=True))
c.add(gates.RX(2, theta=np.pi * r.symbols[0] / 4))
if use_loop:
Expand All @@ -139,7 +139,7 @@ def test_measurement_result_parameters_repeated_execution(backend, use_loop):
backend.set_seed(123)
target_states = []
for _ in range(20):
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
m = c.add(gates.M(1, collapse=True))
target_state = backend.execute_circuit(
c, backend.np.copy(initial_state), nshots=1
Expand All @@ -157,7 +157,7 @@ def test_measurement_result_parameters_repeated_execution(backend, use_loop):
def test_measurement_result_parameters_repeated_execution_final_measurements(backend):
initial_state = random_density_matrix(2**4, backend=backend)
backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
r = c.add(gates.M(1, collapse=True))
c.add(gates.RY(0, theta=np.pi * r.symbols[0] / 3))
c.add(gates.RY(2, theta=np.pi * r.symbols[0] / 4))
Expand All @@ -170,12 +170,12 @@ def test_measurement_result_parameters_repeated_execution_final_measurements(bac
backend.set_seed(123)
target_samples = []
for _ in range(30):
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
m = c.add(gates.M(1, collapse=True))
target_state = backend.execute_circuit(
c, backend.np.copy(initial_state), nshots=1
).state()
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
if int(m.symbols[0].outcome()):
c.add(gates.RY(0, theta=np.pi / 3))
c.add(gates.RY(2, theta=np.pi / 4))
Expand All @@ -188,14 +188,14 @@ def test_measurement_result_parameters_repeated_execution_final_measurements(bac
def test_measurement_result_parameters_multiple_qubits(backend):
initial_state = random_density_matrix(2**4, backend=backend)
backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
r = c.add(gates.M(0, 1, 2, collapse=True))
c.add(gates.RY(1, theta=np.pi * r.symbols[0] / 5))
c.add(gates.RX(3, theta=np.pi * r.symbols[2] / 3))
final_state = backend.execute_circuit(c, backend.np.copy(initial_state), nshots=1)

backend.set_seed(123)
c = models.Circuit(4, density_matrix=True)
c = Circuit(4, density_matrix=True)
m = c.add(gates.M(0, 1, 2, collapse=True))
target_state = backend.execute_circuit(
c, backend.np.copy(initial_state), nshots=1
Expand All @@ -217,7 +217,7 @@ def test_measurement_result_parameters_multiple_qubits(backend):
@pytest.mark.parametrize("nqubits,targets", [(5, [2, 4]), (6, [3, 5])])
def test_measurement_collapse_distributed(backend, accelerators, nqubits, targets):
initial_state = random_density_matrix(2**nqubits, backend=backend)
c = models.Circuit(nqubits, accelerators, density_matrix=True)
c = Circuit(nqubits, accelerators, density_matrix=True)
m = c.add(gates.M(*targets, collapse=True))
result = backend.execute_circuit(c, np.copy(initial_state), nshots=1).state()
slicer = 2 * nqubits * [slice(None)]
Expand All @@ -235,13 +235,13 @@ def test_measurement_collapse_distributed(backend, accelerators, nqubits, target

def test_collapse_after_measurement(backend):
qubits = [0, 2, 3]
c = models.Circuit(5, density_matrix=True)
c = Circuit(5, density_matrix=True)
c.add(gates.H(i) for i in range(5))
m = c.add(gates.M(*qubits, collapse=True))
c.add(gates.H(i) for i in range(5))
final_state = backend.execute_circuit(c, nshots=1)

ct = models.Circuit(5, density_matrix=True)
ct = Circuit(5, density_matrix=True)
bitstring = [r.outcome() for r in m.symbols]
for i, r in zip(qubits, bitstring):
if r:
Expand All @@ -252,7 +252,7 @@ def test_collapse_after_measurement(backend):


def test_collapse_error(backend):
c = models.Circuit(1)
c = Circuit(1)
m = c.add(gates.M(0, collapse=True))
with pytest.raises(Exception) as exc_info:
backend.execute_circuit(c)
Expand Down
Loading

0 comments on commit cc892a1

Please sign in to comment.