Skip to content

Commit af205e9

Browse files
committed
chore: update expectation_value, add matrix validation checks
1 parent a42e62d commit af205e9

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

mpqp/core/instruction/measurement/expectation_value.py

+19-6
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class to define your observable, and a :class:`ExpectationMeasure` to perform
2323
from mpqp.core.languages import Language
2424
from mpqp.tools.display import one_lined_repr
2525
from mpqp.tools.errors import NumberQubitsError
26-
from mpqp.tools.generics import Matrix, OneOrMany
26+
from mpqp.tools.generics import Matrix
2727
from mpqp.tools.maths import is_diagonal, is_hermitian, is_power_of_two
2828

2929
if TYPE_CHECKING:
@@ -155,7 +155,19 @@ def diagonal_elements(self) -> npt.NDArray[np.float32]:
155155

156156
@matrix.setter
157157
def matrix(self, matrix: Matrix):
158-
# TODO: add some checks on the matrix (square, power of two, hermitian)
158+
shape = matrix.shape
159+
if len(shape) != 2 or shape[0] != shape[1]:
160+
raise ValueError(f"The matrix must be square, but got shape {shape}.")
161+
162+
size_1 = shape[0]
163+
if not is_power_of_two(size_1):
164+
raise ValueError(f"Matrix dimension {size_1} must be a power of two.")
165+
166+
if not is_hermitian(matrix):
167+
raise ValueError(
168+
"The matrix is not hermitian (cannot define an observable)."
169+
)
170+
159171
self._matrix = matrix
160172
self._pauli_string = None
161173
self._diag_elements = None
@@ -170,7 +182,10 @@ def pauli_string(self, pauli_string: PauliString):
170182

171183
@diagonal_elements.setter
172184
def diagonal_elements(self, diag_elements: list[Real] | npt.NDArray[np.float64]):
173-
# TODO: add some checks on the diagonal elements (size power of 2)
185+
if not is_power_of_two(len(diag_elements)):
186+
raise ValueError(
187+
"The size of the diagonal elements of the matrix is not a power of two."
188+
)
174189

175190
self._diag_elements = diag_elements
176191
self._is_diagonal = True
@@ -312,9 +327,7 @@ class ExpectationMeasure(Measure):
312327

313328
def __init__(
314329
self,
315-
observable: Union[
316-
Observable, list[Observable]
317-
], # TODO : handle the multi_observable case
330+
observable: Union[Observable, list[Observable]],
318331
targets: Optional[list[int]] = None,
319332
shots: int = 0,
320333
label: Optional[str] = None,

0 commit comments

Comments
 (0)