Qualtran icon indicating copy to clipboard operation
Qualtran copied to clipboard

Constructing a series of And gates with same target but different control

Open kjm538 opened this issue 4 months ago • 2 comments

Consider the following bloq which yields one And gate per qubit in the control register, all with the same target.

@attrs.frozen
class myBloq(Bloq):
    bitsize: int

    @cached_property
    def signature(self) -> Signature:
        return Signature(
            [   Register("control", QBit(), shape=(self.bitsize,)),
                Register("ancilla", QBit(), shape=(self.bitsize,)),
                Register("target", QBit(), side=Side.RIGHT),
            ]
        )

    def build_composite_bloq(
        self, bb: BloqBuilder, control, ancilla
    ):

        for i in range(self.bitsize):
            (control[i], ancilla[i]), target = bb.add(And(cv1=1,cv2=0),ctrl=[control[i],ancilla[i]])

        return {'control': control,'ancilla': ancilla, 'target': target}

At first this may seem wrong since the target of the And gate must be clean by definition, and trying to decompose this bloq does lead to the error

---------------------------------------------------------------------------
BloqError                                 Traceback (most recent call last)
      bloq_ex = myBloq(2)
----> bloq_ex.decompose_bloq()
  File "/Users/.../qualtran/_infra/bloq.py", line 142, in decompose_bloq
    return _decompose_from_build_composite_bloq(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/.../qualtran/_infra/bloq.py", line 52, in _decompose_from_build_composite_bloq
    return bb.finalize(**out_soqs)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/.../qualtran/_infra/composite_bloq.py", line 1072, in finalize
    return self._finalize_strict(**final_soqs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/.../qualtran/_infra/composite_bloq.py", line 1111, in _finalize_strict
    raise BloqError(
qualtran._infra.composite_bloq.BloqError: During finalization, {Soquet(binst=BloqInstance(bloq=And(cv1=1, cv2=0, uncompute=False), i=0), reg=Register(name='target', dtype=QBit(), _shape=(), side=<Side.RIGHT: 2>), idx=())} Soquets were not used.

which I think is due to this reason. However, if I have prepared my control register such that it's in a state where only one bit is 1 (ie |01> + |10> for bitsize=2), then algorithmically this construction is okay since the target will only be turned 'ON' once per state. A simple solution would be to just build my bloq using the Toffoli, however this is not ideal for resource counting purposes. Do you have any suggestions or thoughts on how to construct this?

kjm538 avatar Oct 07 '24 20:10 kjm538