Skip to content

Commit

Permalink
feat: add QubitPauliOperator.get_dict (#1755)
Browse files Browse the repository at this point in the history
* add dict export to QPO

* add a test

* update changelog

* update docstring with suggestion

Co-authored-by: Alec Edgington <[email protected]>

* shorten docstring for pylint

* update assert

* update changelog

* fix sympy equality check

* fix float

---------

Co-authored-by: Alec Edgington <[email protected]>
  • Loading branch information
CalMacCQ and cqc-alec authored Jan 27, 2025
1 parent 7eaf926 commit 995cff7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions pytket/docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Unreleased
Features:

* Add Python 3.13 support to the ZX module.
* Add :py:meth:`QubitPauliOperator.get_dict` method.

Fixes:

Expand Down
10 changes: 10 additions & 0 deletions pytket/pytket/utils/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,16 @@ def subs(self, symbol_dict: dict[Symbol, complex]) -> None:
for key, value in self._dict.items():
self._dict[key] = value.subs(symbol_dict)

def get_dict(self) -> dict[QubitPauliString, Expr]:
"""Generate a dict representation of QubitPauliOperator,
mapping each :py:class:`QubitPauliString` in the support
to its corresponding value.
:return: A dict of Pauli strings and their coefficients
as key-value pairs
"""
return self._dict

def to_list(self) -> list[dict[str, Any]]:
"""Generate a list serialized representation of QubitPauliOperator,
suitable for writing to JSON.
Expand Down
10 changes: 9 additions & 1 deletion pytket/tests/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from hypothesis import HealthCheck, given, settings, strategies
from hypothesis.strategies._internal import SearchStrategy
from simulator import TketSimBackend, TketSimShotBackend # type: ignore
from sympy import symbols
from sympy import I, symbols

from pytket.backends.backend import Backend
from pytket.circuit import Circuit, OpType, Qubit
Expand Down Expand Up @@ -90,6 +90,14 @@ def test_all_paulis() -> None:
assert len(list(circs)) == 3


def test_dict_export() -> None:
qps1 = QubitPauliString(Qubit(0), Pauli.Y)
qps2 = QubitPauliString(Qubit(0), Pauli.X)
op = QubitPauliOperator({qps1: 1j, qps2: 0.5})
# Do equality check with a sympy "I" for the imaginary part
assert op.get_dict() == {qps1: 1.0 * I, qps2: 0.5}


def test_shots_to_counts() -> None:
shot_table = np.asarray([[0, 0], [0, 1], [0, 0]])
counts = counts_from_shot_table(shot_table)
Expand Down

0 comments on commit 995cff7

Please sign in to comment.