From 79a880bc6e8c4069a9871cafe83a28911675083e Mon Sep 17 00:00:00 2001 From: Noureldin Date: Thu, 27 Jun 2024 13:52:37 -0700 Subject: [PATCH] Implement classical action of Cast bloq (#1093) --- qualtran/bloqs/bookkeeping/cast.py | 10 ++++++++-- qualtran/bloqs/bookkeeping/cast_test.py | 13 ++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/qualtran/bloqs/bookkeeping/cast.py b/qualtran/bloqs/bookkeeping/cast.py index 92c5fe62f4..f7a4f34096 100644 --- a/qualtran/bloqs/bookkeeping/cast.py +++ b/qualtran/bloqs/bookkeeping/cast.py @@ -25,6 +25,7 @@ CompositeBloq, DecomposeTypeError, QDType, + QFxp, Register, Side, Signature, @@ -100,8 +101,13 @@ def add_my_tensors( ) def on_classical_vals(self, reg: int) -> Dict[str, 'ClassicalValT']: - # TODO: Actually cast the values https://github.com/quantumlib/Qualtran/issues/734 - return {'reg': reg} + if isinstance(self.out_dtype, QFxp): + res = reg + elif isinstance(self.inp_dtype, QFxp): + res = int(reg) + else: + res = self.out_dtype.from_bits(self.inp_dtype.to_bits(reg)) + return {'reg': res} def as_cirq_op(self, qubit_manager, reg: 'CirqQuregT') -> Tuple[None, Dict[str, 'CirqQuregT']]: return None, {'reg': reg} diff --git a/qualtran/bloqs/bookkeeping/cast_test.py b/qualtran/bloqs/bookkeeping/cast_test.py index 6fd50c6bef..d34da56998 100644 --- a/qualtran/bloqs/bookkeeping/cast_test.py +++ b/qualtran/bloqs/bookkeeping/cast_test.py @@ -13,7 +13,7 @@ # limitations under the License. import subprocess -from qualtran import QFxp, QInt +from qualtran import QFxp, QInt, QUInt from qualtran.bloqs.bookkeeping import Cast from qualtran.bloqs.bookkeeping.cast import _cast from qualtran.bloqs.for_testing import TestCastToFrom @@ -40,6 +40,17 @@ def test_cast_classical_sim(): assert a == 7 assert b == 9 + c = Cast(QFxp(8, 8), QUInt(8)) + assert c.call_classically(reg=1.2) == (1,) # type: ignore + + +def test_cast_unsiged_signed(): + c = Cast(QUInt(5), QInt(5)) + assert c.call_classically(reg=31) == (-1,) + + c = Cast(QInt(5), QUInt(5)) + assert c.call_classically(reg=-1) == (31,) + def test_no_circular_import(): subprocess.check_call(['python', '-c', 'from qualtran.bloqs.bookkeeping import cast'])