Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise error when initial state shape is wrong #1361

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/qibo/backends/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,17 @@ 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)
valid_shape = (
2 * (2**circuit.nqubits,)
if circuit.density_matrix
else (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)
Loading