Skip to content

feat: Add methods for generating random angles #979

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

Merged
merged 2 commits into from
May 27, 2025
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
12 changes: 12 additions & 0 deletions guppylang/std/qsystem/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
)
from guppylang.std._internal.compiler.tket2_exts import QSYSTEM_RANDOM_EXTENSION
from guppylang.std._internal.util import external_op
from guppylang.std.angles import angle, pi
from guppylang.std.builtins import array, mem_swap, owned, panic
from guppylang.std.option import Option

qsystem_random = GuppyModule("qsystem.random")

qsystem_random.load(angle, pi) # type: ignore[arg-type]

SHUFFLE_N = guppy.nat_var("SHUFFLE_N", module=qsystem_random)
SHUFFLE_T = guppy.type_var(
Expand Down Expand Up @@ -67,6 +69,16 @@ def random_int_bounded(self: "RNG", bound: int) -> int:
"""
return self._random_int_bounded(bound)

@guppy(qsystem_random)
def random_angle(self: "RNG") -> angle:
"""Generate a random angle in the range [-pi, pi)."""
return (2.0 * self._random_float() - 1.0) * pi

@guppy(qsystem_random)
def random_clifford_angle(self: "RNG") -> angle:
"""Generate a random Clifford angle (multiple of pi/2)."""
return self.random_int_bounded(4) * pi / 2

@guppy.hugr_op(
external_op("DeleteRNGContext", [], ext=QSYSTEM_RANDOM_EXTENSION),
module=qsystem_random,
Expand Down
6 changes: 4 additions & 2 deletions tests/integration/test_qsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def test_qsystem_random(validate): # type: ignore[no-untyped-def]
"""Compile various operations from the qsystem random extension."""

@compile_qsystem_guppy
def test() -> tuple[int, float, int, int]:
def test() -> tuple[int, float, int, int, angle, angle]:
rng = RNG(42)
rint = rng.random_int()
rfloat = rng.random_float()
Expand All @@ -71,8 +71,10 @@ def test() -> tuple[int, float, int, int]:
_ = measure_array(ar)
dist = make_discrete_distribution(array(0.0, 1.0, 2.0, 3.0))
rint_discrete = dist.sample(rng)
rangle = rng.random_angle()
rcangle = rng.random_clifford_angle()
rng.discard()

return rint, rfloat, rint_bnd, rint_discrete
return rint, rfloat, rint_bnd, rint_discrete, rangle, rcangle

validate(test)
Loading