Skip to content

Commit

Permalink
Raise TypeError when a dictionary is passed to MeasurementResult cons…
Browse files Browse the repository at this point in the history
…tructor (#2523)

* add missing license statement

* raise error when passing dict to MeasurementResult

it's natural to think that you can pass results directly from some
sort of experiment into the MeasurementResult class.

* add instatiation example

* upgrade note to warning
  • Loading branch information
natestemen authored Oct 8, 2024
1 parent d7f3b5b commit 0526250
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
5 changes: 5 additions & 0 deletions mitiq/tests/test_measurement_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ def test_measurement_result_not_bits():
MeasurementResult(result=[[0, 0], [0, 1], [-1, 0]])


def test_measurement_result_invoked_with_dict():
with pytest.raises(TypeError, match="from_counts"):
MeasurementResult({"001": 123, "010": 456})


def test_filter_qubits():
result = MeasurementResult([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
assert np.allclose(result.filter_qubits([0]), np.array([[0], [0], [1]]))
Expand Down
5 changes: 5 additions & 0 deletions mitiq/tests/test_typing.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.

import os

from mitiq.typing import SUPPORTED_PROGRAM_TYPES
Expand Down
12 changes: 11 additions & 1 deletion mitiq/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,12 @@ class MeasurementResult:
``tuple(range(self.nqubits))``, where ``self.nqubits``
is the bitstring length deduced from ``result``.
Note:
Example:
>>> mr = MeasurementResult(["001", "010", "001"])
>>> mr.get_counts()
{'001': 2, '010': 1}
Warning:
Use caution when selecting the default option for ``qubit_indices``,
especially when estimating an :class:`.Observable`
acting on a subset of qubits. In this case Mitiq
Expand All @@ -125,6 +130,11 @@ class MeasurementResult:

def __post_init__(self) -> None:
# Validate arguments
if isinstance(self.result, dict):
raise TypeError(
"Use the MeasurementResult.from_counts method to instantiate "
"a MeasurementResult object from a dictionary."
)
symbols = set(b for bits in self.result for b in bits)
if not (symbols.issubset({0, 1}) or symbols.issubset({"0", "1"})):
raise ValueError("Bitstrings should look like '011' or [0, 1, 1].")
Expand Down

0 comments on commit 0526250

Please sign in to comment.