Misaligned two-qubit gate diagrams for deep circuits
Description of the issue
Lines connecting two qubits get gradually misaligned for deep circuits in Google colab (with a supposedly monospaced font).

How to reproduce the issue
import cirq
q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit([cirq.CZ(q0, q1)] * 200)
print(circuit)
Cirq version 0.15.0
I think this is a font issue, but we could look at the actual strings and check whether they are aligned to be sure.
@maffoo yeah I agree. Seems to be a macOs and/or Colab issue since I only see this is on my MacBook and not on my linux desktop. So can probably close this issue
Actual strings are aligned.
The problem occurs because the output is inside the <pre> HTML element. By default, it has the property font-family: monospace. Which monospace font will be used depends on the browser and OS.
On macOS, Chromium-based browsers seem to select the old Courier font, which lacks box-drawing characters │ and ─. These characters get displayed in Menlo, which is also monospaced but has a different character width.
The solution is to change the font to one that supports box drawing. Menlo, which is the default monospace font in Firefox for macOS, might be a good option.
The problem occurs in two scenarios:
circuit = cirq.Circuit([cirq.CZ(q0, q1)] * 200)
print(circuit) # calls circuit.__str__
# <misaligned output>
In the first scenario, we can't do anything since circuit.__str__() must return plain text. We can only contact Colab or Chrome developers and ask them to change the font.
circuit = cirq.Circuit([cirq.CZ(q0, q1)] * 200)
circuit # calls circuit._repr_html_
# <misaligned output>
The second scenario produces misaligned output not only in Colab on Chrome but also in Safari and VS Code on macOS.
Fortunately, here we have control over font.
For example, instead of this:
https://github.com/quantumlib/Cirq/blob/65ebb4a4d4a7b8b15e766b486e19582c634c1641/cirq-core/cirq/circuits/circuit.py#L290-L296
we can write this:
def _repr_html_(self) -> str:
"""Print ASCII diagram in Jupyter notebook without wrapping lines."""
return (
'<pre style="overflow: auto; white-space: pre; font-family: Menlo, monospace;">'
+ html.escape(self.to_text_diagram())
+ '</pre>'
)
Almost all Mac users have the Menlo font preinstalled and it will be used for them. Most non-Mac users don't have this font. For them, the browser-default monospace font will be used, as before.
This will fix the problem in the second scenario.
This seems like a good first issue for anyone with a mac device that can test.