Skip to content

Commit

Permalink
Fix diagram for Identity with no qubits (quantumlib#6926)
Browse files Browse the repository at this point in the history
* Fix diagram for Identity with no qubits

- An IdentityGate with 0 qubits used to raise an exception
in the circuit drawer.
- This PR fixes the issue and displays the gate similar to a
GlobalPhaseGate.

Fixes: quantumlib#6768
  • Loading branch information
dstrain115 authored Jan 8, 2025
1 parent 3e16e15 commit 25b3362
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 2 additions & 0 deletions cirq-core/cirq/ops/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ def _mul_with_qubits(self, qubits: Tuple['cirq.Qid', ...], other):
_rmul_with_qubits = _mul_with_qubits

def _circuit_diagram_info_(self, args) -> Tuple[str, ...]:
if self.num_qubits() <= 0:
return NotImplemented
return ('I',) * self.num_qubits()

def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
Expand Down
18 changes: 18 additions & 0 deletions cirq-core/cirq/ops/identity_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,21 @@ def test_identity_commutes():
assert cirq.commutes(cirq.I, cirq.X)
with pytest.raises(TypeError):
cirq.commutes(cirq.I, "Gate")


def test_identity_diagram():
cirq.testing.assert_has_diagram(
cirq.Circuit(cirq.IdentityGate(3).on_each(cirq.LineQubit.range(3))),
"""
0: ───I───
1: ───I───
2: ───I───
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit(cirq.IdentityGate(0)()),
"""
I(0)""",
)
2 changes: 1 addition & 1 deletion cirq-core/cirq/protocols/circuit_diagram_info_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def _op_info_with_fallback(
rows: List[LabelEntity] = list(op.qubits)
if args.label_map is not None:
rows += protocols.measurement_keys_touched(op) & args.label_map.keys()
if info is not None:
if info is not None and info.wire_symbols:
if max(1, len(rows)) != len(info.wire_symbols):
raise ValueError(f'Wanted diagram info from {op!r} for {rows!r}) but got {info!r}')
return info
Expand Down

0 comments on commit 25b3362

Please sign in to comment.