Skip to content
Open
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
145 changes: 102 additions & 43 deletions cirq-core/cirq/contrib/svg/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

from collections import defaultdict
from collections.abc import Iterable
from typing import cast, TYPE_CHECKING

import matplotlib.font_manager
Expand Down Expand Up @@ -73,16 +75,33 @@ def _rect(
y: float,
boxwidth: float,
boxheight: float,
fill: str = 'white',
fill: str = 'none',
strokewidth: float = 1,
):
) -> str:
"""Draw an SVG <rect> rectangle."""
return (
f'<rect x="{x}" y="{y}" width="{boxwidth}" height="{boxheight}" '
f'stroke="black" fill="{fill}" stroke-width="{strokewidth}" />'
)


def _subtract_intervals(
start: float, end: float, cutouts: Iterable[tuple[float, float]]
) -> list[tuple[float, float]]:
"""Return ascending sub-intervals of [min(start, end), max(start, end)] outside all cutouts."""
cursor, limit = min(start, end), max(start, end)
segments: list[tuple[float, float]] = []
for c_start, c_end in sorted(cutouts):
if c_start >= c_end or c_end <= cursor or c_start >= limit:
continue
if cursor < c_start:
segments.append((cursor, c_start))
cursor = max(cursor, c_end)
if cursor < limit:
segments.append((cursor, limit))
return segments


def _text(x: float, y: float, text: str, fontsize: int = 14):
"""Draw SVG <text> text."""
return (
Expand Down Expand Up @@ -197,6 +216,57 @@ def _debug_spacing(col_starts, row_starts): # pragma: no cover
return t


def _render_entries(
tdd: cirq.TextDiagramDrawer,
col_starts: list[float],
col_widths: list[float],
row_starts: list[float],
row_heights: list[float],
yi_map: dict[float, int],
ref_boxheight: float,
col_padding: float,
) -> tuple[list[str], dict[int, list[tuple[float, float]]], dict[int, list[tuple[float, float]]]]:
"""Render diagram entries and collect per-row and per-column wire cutouts."""
row_cutouts: defaultdict[int, list[tuple[float, float]]] = defaultdict(list)
col_cutouts: defaultdict[int, list[tuple[float, float]]] = defaultdict(list)
parts: list[str] = []

for (xi, raw_yi), v in tdd.entries.items():
yi = yi_map[raw_yi]
x = col_starts[xi] + col_widths[xi] / 2
y = row_starts[yi] + row_heights[yi] / 2

# Pass-through symbols let wires cross underneath without clipping.
if xi != 0:
match v.text:
case '@':
parts.append(f'<circle cx="{x}" cy="{y}" r="{ref_boxheight / 8}" />')
continue
case '×':
parts.append(_text(x, y + 1.5, '×', fontsize=20))
continue
case '':
continue

boxheight = ref_boxheight
boxwidth = col_widths[xi] - tdd.horizontal_padding.get(xi, col_padding)
boxx = x - boxwidth / 2
boxy = y - boxheight / 2
row_cutouts[yi].append((boxx, boxx + boxwidth))
col_cutouts[xi].append((boxy, boxy + boxheight))

if xi == 0:
# Qubits omit a <rect> but still register a cutout so wires start after the label.
parts.append(_text(x, y, v.text))
continue

parts.append(_rect(boxx, boxy, boxwidth, boxheight))
fontsize = 14 if len(v.text) > 1 and '\n' not in v.text else 18
parts.append(_text(x, y, v.text, fontsize=fontsize))

return parts, row_cutouts, col_cutouts


def tdd_to_svg(
tdd: cirq.TextDiagramDrawer,
ref_boxwidth: float = 40,
Expand All @@ -211,70 +281,59 @@ def tdd_to_svg(
tdd=tdd, ref_boxwidth=ref_boxwidth, col_padding=col_padding
)

t = (
# Render entries first so wire segments can be clipped around transparent
# boxes and qubit labels instead of relying on opaque white fills to hide wires.
entry_parts, row_cutouts, col_cutouts = _render_entries(
tdd=tdd,
col_starts=col_starts,
col_widths=col_widths,
row_starts=row_starts,
row_heights=row_heights,
yi_map=yi_map,
ref_boxheight=ref_boxheight,
col_padding=col_padding,
)

svg_header = (
f'<svg xmlns="http://www.w3.org/2000/svg" '
f'width="{col_starts[-1]}" height="{row_starts[-1]}">'
)
svg_parts: list[str] = [svg_header]

# Developers: uncomment below to draw green lines to debug
# col_starts and row_starts
# t += _debug_spacing(col_starts, row_starts)
# svg_parts.append(_debug_spacing(col_starts, row_starts))

for yi, xi1, xi2, _, doubled in tdd.horizontal_lines:
for raw_yi, xi1, xi2, _, doubled in tdd.horizontal_lines:
xi1 = cast(int, xi1)
xi2 = cast(int, xi2)
x1 = col_starts[xi1] + col_widths[xi1] / 2
x2 = col_starts[xi2] + col_widths[xi2] / 2

yi = yi_map[yi]
yi = yi_map[raw_yi]
y = row_starts[yi] + row_heights[yi] / 2

t += _line(x1, y, x2, y, doubled=doubled)
for seg_x1, seg_x2 in _subtract_intervals(x1, x2, row_cutouts.get(yi, ())):
svg_parts.append(_line(seg_x1, y, seg_x2, y, doubled=doubled))

for xi, yi1, yi2, _, doubled in tdd.vertical_lines:
for raw_xi, yi1, yi2, _, doubled in tdd.vertical_lines:
yi1 = yi_map[yi1]
yi2 = yi_map[yi2]
y1 = row_starts[yi1] + row_heights[yi1] / 2
y2 = row_starts[yi2] + row_heights[yi2] / 2

xi = cast(int, xi)
xi = cast(int, raw_xi)
x = col_starts[xi] + col_widths[xi] / 2

# Use stroke-width="1" for doubled lines so the paired lines stay separated by a clear gap.
t += _line(x, y1, x, y2, strokewidth=1 if doubled else 3, doubled=doubled)

for (xi, yi), v in tdd.entries.items():
yi = yi_map[yi]

x = col_starts[xi] + col_widths[xi] / 2
y = row_starts[yi] + row_heights[yi] / 2

boxheight = ref_boxheight
boxwidth = col_widths[xi] - tdd.horizontal_padding.get(xi, col_padding)
boxx = x - boxwidth / 2
boxy = y - boxheight / 2

if xi == 0:
# Qubits
t += _rect(boxx, boxy, boxwidth, boxheight, strokewidth=0)
t += _text(x, y, v.text)
continue
for seg_y1, seg_y2 in _subtract_intervals(y1, y2, col_cutouts.get(xi, ())):
# Use stroke-width="1" for doubled lines so the paired lines stay separated by a gap.
svg_parts.append(
_line(x, seg_y1, x, seg_y2, strokewidth=1 if doubled else 3, doubled=doubled)
)

if v.text == '@':
t += f'<circle cx="{x}" cy="{y}" r="{ref_boxheight / 8}" />'
continue
if v.text == '×':
t += _text(x, y + 1.5, '×', fontsize=20)
continue
if v.text == '':
continue

t += _rect(boxx, boxy, boxwidth, boxheight)
fontsize = 14 if len(v.text) > 1 and '\n' not in v.text else 18
t += _text(x, y, v.text, fontsize=fontsize)

t += '</svg>'
return t
svg_parts.extend(entry_parts)
svg_parts.append('</svg>')
return ''.join(svg_parts)


def _validate_circuit(circuit: cirq.Circuit):
Expand Down
44 changes: 37 additions & 7 deletions cirq-core/cirq/contrib/svg/svg_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,20 +120,38 @@ def test_svg_classical_controls_doubled_lines() -> None:
)
root = ET.fromstring(circuit_to_svg(circuit))
lines = [el.attrib for el in root.findall(f'{_SVG_NS}line')]
horiz = sorted((a for a in lines if a['y1'] == a['y2']), key=lambda a: float(a['y1']))
vert = sorted((a for a in lines if a['x1'] == a['x2']), key=lambda a: float(a['x1']))
horiz = sorted(
(a for a in lines if a['y1'] == a['y2']), key=lambda a: (float(a['y1']), float(a['x1']))
)
vert = sorted(
(a for a in lines if a['x1'] == a['x2']), key=lambda a: (float(a['x1']), float(a['y1']))
)
texts = {
el.text.strip(): (float(el.attrib['x']), float(el.attrib['y']))
for el in root.findall(f'{_SVG_NS}text')
if el.text
}
rects = [el.attrib for el in root.findall(f'{_SVG_NS}rect')]
box_half_h = float(rects[0]['height']) / 2
offset = DOUBLED_LINE_OFFSET
y0, y1, ym = texts['0:'][1], texts['1:'][1], texts['m:'][1]

assert len(horiz) + len(vert) == len(lines)
assert [float(a['y1']) for a in horiz] == [y0, y1, ym - offset, ym + offset]
assert len({(a['x1'], a['x2']) for a in horiz}) == 1
assert float(horiz[3]['y1']) - float(horiz[2]['y1']) > float(horiz[2]['stroke-width'])
assert [float(a['y1']) for a in horiz] == [
y0,
y0,
y1,
y1,
y1,
ym - offset,
ym - offset,
ym + offset,
ym + offset,
]
m_top = [a for a in horiz if float(a['y1']) == ym - offset]
m_bot = [a for a in horiz if float(a['y1']) == ym + offset]
assert [(a['x1'], a['x2']) for a in m_top] == [(a['x1'], a['x2']) for a in m_bot]
assert float(m_bot[0]['y1']) - float(m_top[0]['y1']) > float(m_top[0]['stroke-width'])
assert all(a['stroke-width'] == '1' for a in horiz)

x_cnot, x_meas, x_ctrl = texts['X'][0], texts['M'][0], texts['^'][0]
Expand All @@ -144,8 +162,20 @@ def test_svg_classical_controls_doubled_lines() -> None:
x_ctrl - offset,
x_ctrl + offset,
]
assert [float(a['y1']) for a in vert] == [y0, y0, y0, y1, y1]
assert [float(a['y2']) for a in vert] == [y1, ym, ym, ym, ym]
assert [float(a['y1']) for a in vert] == [
y0,
y0 + box_half_h,
y0 + box_half_h,
y1 + box_half_h,
y1 + box_half_h,
]
assert [float(a['y2']) for a in vert] == [
y1 - box_half_h,
ym,
ym,
ym - box_half_h,
ym - box_half_h,
]
assert [a['stroke-width'] for a in vert] == ['3', '1', '1', '1', '1']


Expand Down
Loading