Skip to content

Commit

Permalink
[SVG Circuits] Give up gracefully on gates with big labels (#3007)
Browse files Browse the repository at this point in the history
`MatrixGate` tries to print its whole matrix which is just huge. This PR hacks in a check that uses `?` for any gate whose label includes a newline. I will quickly remind reviewers that this functionality is in contrib, xref #2313 if anyone wants to "productionize" this functionality.
  • Loading branch information
mpharrigan committed May 15, 2020
1 parent 5d6b8bc commit 93ecd24
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 6 additions & 0 deletions cirq/contrib/svg/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@


def _get_text_width(t: str) -> float:
if '\n' in t:
return _get_text_width('?')
tp = matplotlib.textpath.TextPath((0, 0), t, size=14, prop='Arial')
bb = tp.get_extents()
return bb.width + 10
Expand Down Expand Up @@ -206,6 +208,10 @@ def tdd_to_svg(
if v.text == '×':
t += _text(x, y + 3, '×', fontsize=40)
continue
if '\n' in v.text:
t += _rect(boxx, boxy, boxwidth, boxheight)
t += _text(x, y, '?', fontsize=18)
continue

t += _rect(boxx, boxy, boxwidth, boxheight)
t += _text(x, y, v.text, fontsize=14 if len(v.text) > 1 else 18)
Expand Down
10 changes: 8 additions & 2 deletions cirq/contrib/svg/svg_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
import numpy as np

import cirq
from cirq.contrib.svg import circuit_to_svg
Expand All @@ -9,9 +10,14 @@ def test_svg():

svg_text = circuit_to_svg(
cirq.Circuit(
cirq.CNOT(a, b), cirq.CZ(b, c), cirq.SWAP(a, c),
cirq.CNOT(a, b),
cirq.CZ(b, c),
cirq.SWAP(a, c),
cirq.PhasedXPowGate(exponent=0.123, phase_exponent=0.456).on(c),
cirq.Z(a), cirq.measure(a, b, c, key='z')))
cirq.Z(a),
cirq.measure(a, b, c, key='z'),
cirq.MatrixGate(np.eye(2)).on(a),
))
assert '<svg' in svg_text
assert '</svg>' in svg_text

Expand Down

0 comments on commit 93ecd24

Please sign in to comment.