Skip to content

Commit

Permalink
fix: raise error when initial state shape is wrong
Browse files Browse the repository at this point in the history
  • Loading branch information
stavros11 committed Jun 13, 2024
1 parent ebd6fb2 commit 0f5fa80
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/qibo/backends/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,16 @@ def execute_circuit(self, circuit, initial_state=None, nshots=1000):
return self.execute_circuit(initial_state + circuit, None, nshots)
elif initial_state is not None:
initial_state = self.cast(initial_state)
if circuit.density_matrix:
valid_shape = 2 * (2**circuit.nqubits,)
else:
valid_shape = (2**circuit.nqubits,)
if tuple(initial_state.shape) != valid_shape:
raise_error(
ValueError,
f"Given initial state has shape {initial_state.shape} instead of "
f"the expected {valid_shape}.",
)

if circuit.repeated_execution:
if circuit.measurements or circuit.has_collapse:
Expand Down
14 changes: 12 additions & 2 deletions tests/test_models_circuit_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pytest

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


def test_eager_execute(backend, accelerators):
Expand Down Expand Up @@ -91,8 +92,6 @@ def test_final_state_property(backend):


def test_density_matrix_circuit(backend):
from qibo.quantum_info import random_density_matrix

initial_rho = random_density_matrix(2**3, backend=backend)

c = Circuit(3, density_matrix=True)
Expand Down Expand Up @@ -146,3 +145,14 @@ def test_initial_state_error(backend):

with pytest.raises(ValueError):
backend.execute_circuit(c, c1)


@pytest.mark.parametrize("density_matrix", [False, True])
def test_initial_state_shape_error(backend, density_matrix):
nqubits = 2
c = Circuit(nqubits, density_matrix=density_matrix)
c.add(gates.X(i) for i in range(nqubits))

initial_state = random_density_matrix(2, backend=backend)
with pytest.raises(ValueError):
backend.execute_circuit(c, initial_state=initial_state)

0 comments on commit 0f5fa80

Please sign in to comment.