Qualtran icon indicating copy to clipboard operation
Qualtran copied to clipboard

`OnEach` does not preserve data type

Open anurudhp opened this issue 1 year ago • 4 comments

This breaks classical simulation which needs the precise data type to convert between values and bits.

from qualtran import QInt
from qualtran.bloqs.arithmetic.bitwise import BitwiseNot


def test_bitwise_not(inp, expected_result):
    bloq = BitwiseNot(QInt(4))
    (result,) = bloq.call_classically(x=inp)
    assert result == expected_result
test_bitwise_not(0, expected_result=-1)
# ValueError: Too-large classical QInt(4): 15 encountered in BitwiseNot<0>.x
test_bitwise_not(-1, expected_result=0)
# ValueError: Negative classical value encountered in val

anurudhp avatar Jul 31 '24 17:07 anurudhp

Would specifying a dtype for OnEach solve the problem?

fdmalone avatar Jul 31 '24 18:07 fdmalone

Would specifying a dtype for OnEach solve the problem?

Yep I think so, by updating the signature. and passing the dtype to the split in the decomp. https://github.com/quantumlib/Qualtran/blob/157459ef8c267b18d3a7f79fe4bd5d7653a21636/qualtran/bloqs/basic_gates/on_each.py#L63-L69

But by changing bloq attribute n to dtype, we need to update all call sites, and this may make things more verbose. Especially because a user who wants to apply OnEach usually doesn't care about the dtype.

anurudhp avatar Jul 31 '24 18:07 anurudhp

A somewhat hacky fix would be to add an optional dtype to the constructor and then use that if it's not None, or add a specialized version for typed registers.

fdmalone avatar Jul 31 '24 19:07 fdmalone

Another solution would be a factory method, but this would also require every call site to be changed I think.

fdmalone avatar Jul 31 '24 19:07 fdmalone

I think this was fixed by #1283 but the new parameter is not documented! cc @NoureldinYosri

mpharrigan avatar Aug 23 '24 21:08 mpharrigan