Skip to content
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

Bugfixes in cirq interop #963

Closed
Closed
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
15 changes: 9 additions & 6 deletions qualtran/_infra/adjoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,15 @@ def decompose_bloq(self) -> 'CompositeBloq':
"""The decomposition is the adjoint of `subbloq`'s decomposition."""
return self.subbloq.decompose_bloq().adjoint()

def decompose_from_registers(
self, *, context: cirq.DecompositionContext, **quregs: NDArray[cirq.Qid] # type: ignore[type-var]
) -> cirq.OP_TREE:
if isinstance(self.subbloq, GateWithRegisters):
return cirq.inverse(self.subbloq.decompose_from_registers(context=context, **quregs))
return super().decompose_from_registers(context=context, **quregs)
# def decompose_from_registers(
# self, *, context: cirq.DecompositionContext, **quregs: NDArray[cirq.Qid] # type: ignore[type-var]
# ) -> cirq.OP_TREE:
# if isinstance(self.subbloq, GateWithRegisters) or hasattr(
# self.subbloq, 'decompose_from_registers'
# ):
# yield cirq.inverse(self.subbloq.decompose_from_registers(context=context, **quregs))
# else:
# yield super().decompose_from_registers(context=context, **quregs)

def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
Expand Down
1 change: 1 addition & 0 deletions qualtran/bloqs/mcmt/and_bloq.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ def _decompose_via_tree(
def decompose_from_registers(
self, *, context: cirq.DecompositionContext, **quregs: NDArray[cirq.Qid]
) -> Iterator[cirq.OP_TREE]:
assert 'junk' in quregs
control, ancilla, target = (
quregs['ctrl'].flatten(),
quregs.get('junk', np.array([])).flatten(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,16 @@ def test_prepare_uniform_superposition_consistent_protocols():
PrepareUniformSuperposition(5, cvs=()),
PrepareUniformSuperposition(5, cvs=[]),
)


def test_prepare_uniform_superposition_adjoint():
n = 3
target = cirq.NamedQubit.range((n - 1).bit_length(), prefix='target')
control = [cirq.NamedQubit('control')]
op = PrepareUniformSuperposition(n, cvs=(0,)).on_registers(ctrl=control, target=target)
gqm = cirq.GreedyQubitManager(prefix="_ancilla", maximize_reuse=True)
context = cirq.DecompositionContext(gqm)
circuit = cirq.Circuit(op, cirq.decompose(cirq.inverse(op), context=context))
identity = cirq.Circuit(cirq.identity_each(*circuit.all_qubits())).final_state_vector()
result = cirq.Simulator(dtype=np.complex128).simulate(circuit)
np.testing.assert_allclose(result.final_state_vector, identity, atol=1e-8)
15 changes: 15 additions & 0 deletions qualtran/bloqs/util_bloqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,15 @@ def wire_symbol(self, reg: Register, idx: Tuple[int, ...] = tuple()) -> 'WireSym
assert reg.name == 'reg'
return directional_text_box('alloc', Side.RIGHT)

def as_cirq_op(
self, qubit_manager: 'cirq.QubitManager'
) -> Tuple[Union['cirq.Operation', None], Dict[str, 'CirqQuregT']]:
shape = (*self.signature[0].shape, self.signature[0].bitsize)
return (
None,
{'reg': np.array(qubit_manager.qalloc(self.signature.n_qubits())).reshape(shape)},
)


@frozen
class Free(Bloq):
Expand Down Expand Up @@ -415,6 +424,12 @@ def wire_symbol(self, reg: Register, idx: Tuple[int, ...] = tuple()) -> 'WireSym
assert reg.name == 'reg'
return directional_text_box('free', Side.LEFT)

def as_cirq_op(
self, qubit_manager: 'cirq.QubitManager', reg: 'CirqQuregT'
) -> Tuple[Union['cirq.Operation', None], Dict[str, 'CirqQuregT']]:
qubit_manager.qfree(reg.flatten().tolist())
return (None, {})


@frozen
class ArbitraryClifford(Bloq):
Expand Down
2 changes: 1 addition & 1 deletion qualtran/cirq_interop/_bloq_to_cirq_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def test_bloq_as_cirq_gate_left_register():
bb.free(q)
cbloq = bb.finalize()
circuit = cbloq.to_cirq_circuit()
cirq.testing.assert_has_diagram(circuit, """_c(0): ───alloc───X───free───""")
cirq.testing.assert_has_diagram(circuit, """_c(0): ───X───""")


def test_bloq_as_cirq_gate_for_mod_exp():
Expand Down
24 changes: 22 additions & 2 deletions qualtran/cirq_interop/_interop_qubit_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,30 @@ def __init__(self, qm: Optional[cirq.QubitManager] = None):
self._managed_qubits: Set[cirq.Qid] = set()

def qalloc(self, n: int, dim: int = 2) -> List['cirq.Qid']:
return self._qm.qalloc(n, dim)
ret = []
qubits_to_free = []
while len(ret) < n:
new_alloc = self._qm.qalloc(n - len(ret), dim)
for q in new_alloc:
if q in self._managed_qubits:
qubits_to_free.append(q)
else:
ret.append(q)
self._qm.qfree(qubits_to_free)
return ret

def qborrow(self, n: int, dim: int = 2) -> List['cirq.Qid']:
return self._qm.qborrow(n, dim)
ret = []
qubits_to_free = []
while len(ret) < n:
new_alloc = self._qm.qborrow(n - len(ret), dim)
for q in new_alloc:
if q in self._managed_qubits:
qubits_to_free.append(q)
else:
ret.append(q)
self._qm.qfree(qubits_to_free)
return ret

def manage_qubits(self, qubits: Iterable[cirq.Qid]):
self._managed_qubits |= set(qubits)
Expand Down
Loading