Skip to content

Commit 25b3362

Browse files
authored
Fix diagram for Identity with no qubits (#6926)
* 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: #6768
1 parent 3e16e15 commit 25b3362

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

cirq-core/cirq/ops/identity.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ def _mul_with_qubits(self, qubits: Tuple['cirq.Qid', ...], other):
135135
_rmul_with_qubits = _mul_with_qubits
136136

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

140142
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:

cirq-core/cirq/ops/identity_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,3 +214,21 @@ def test_identity_commutes():
214214
assert cirq.commutes(cirq.I, cirq.X)
215215
with pytest.raises(TypeError):
216216
cirq.commutes(cirq.I, "Gate")
217+
218+
219+
def test_identity_diagram():
220+
cirq.testing.assert_has_diagram(
221+
cirq.Circuit(cirq.IdentityGate(3).on_each(cirq.LineQubit.range(3))),
222+
"""
223+
0: ───I───
224+
225+
1: ───I───
226+
227+
2: ───I───
228+
""",
229+
)
230+
cirq.testing.assert_has_diagram(
231+
cirq.Circuit(cirq.IdentityGate(0)()),
232+
"""
233+
I(0)""",
234+
)

cirq-core/cirq/protocols/circuit_diagram_info_protocol.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def _op_info_with_fallback(
342342
rows: List[LabelEntity] = list(op.qubits)
343343
if args.label_map is not None:
344344
rows += protocols.measurement_keys_touched(op) & args.label_map.keys()
345-
if info is not None:
345+
if info is not None and info.wire_symbols:
346346
if max(1, len(rows)) != len(info.wire_symbols):
347347
raise ValueError(f'Wanted diagram info from {op!r} for {rows!r}) but got {info!r}')
348348
return info

0 commit comments

Comments
 (0)