Skip to content

Commit

Permalink
refactor: use OutcomeArray.from_ints in HShots.to_pytket (#647)
Browse files Browse the repository at this point in the history
just a drive by I happened to do while debugging something else.
Performance gains are not a bottleneck but it is more readable so might
as well.
  • Loading branch information
ss2165 authored Nov 14, 2024
1 parent f4e5655 commit 8d8c8b1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
13 changes: 8 additions & 5 deletions guppylang/hresult.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,14 +194,17 @@ def to_pytket(self) -> BackendResult:
raise ImportError(
"Pytket is an optional dependency, install with the `pytket` extra"
) from e
counts = self.register_bitstrings(strict_lengths=True, strict_names=True)
reg_shots = self.register_bitstrings(strict_lengths=True, strict_names=True)
reg_sizes: dict[str, int] = {
reg: len(next(iter(counts[reg]), "")) for reg in counts
reg: len(next(iter(reg_shots[reg]), "")) for reg in reg_shots
}
registers = list(counts.keys())
registers = list(reg_shots.keys())
bits = [Bit(reg, i) for reg in registers for i in range(reg_sizes[reg])]

int_shots = [
[ord(bitval) - 48 for reg in registers for bitval in counts[reg][i]]
int("".join(reg_shots[reg][i] for reg in registers), 2)
for i in range(len(self.results))
]
return BackendResult(shots=OutcomeArray.from_readouts(int_shots), c_bits=bits)
return BackendResult(
shots=OutcomeArray.from_ints(int_shots, width=len(bits)), c_bits=bits
)
10 changes: 6 additions & 4 deletions tests/test_hresult.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,19 @@ def test_pytket():
shot results."""
pytest.importorskip("pytket", reason="pytket not installed")

hsim_shots = HShots(([("c", [1, 0]), ("d", [1, 0])], [("c", [0, 0]), ("d", [1, 0])]))
hsim_shots = HShots(
([("c", [1, 0]), ("d", [1, 0, 0])], [("c", [0, 0]), ("d", [1, 0, 1])])
)

pytket_result = hsim_shots.to_pytket()

from pytket._tket.unit_id import Bit
from pytket.backends.backendresult import BackendResult
from pytket.utils.outcomearray import OutcomeArray

bits = [Bit("c", 0), Bit("c", 1), Bit("d", 0), Bit("d", 1)]
bits = [Bit("c", 0), Bit("c", 1), Bit("d", 0), Bit("d", 1), Bit("d", 2)]
expected = BackendResult(
c_bits=bits, shots=OutcomeArray.from_readouts([[1, 0, 1, 0], [0, 0, 1, 0]])
c_bits=bits,
shots=OutcomeArray.from_readouts([[1, 0, 1, 0, 0], [0, 0, 1, 0, 1]]),
)

assert pytket_result == expected
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8d8c8b1

Please sign in to comment.