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
152 changes: 130 additions & 22 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

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

import matplotlib.font_manager
Expand All @@ -15,6 +17,12 @@
# Half-spacing between paired strokes of a doubled line; paired with
# stroke-width="1" this leaves a 2 px gap so the two lines stay visually distinct.
DOUBLED_LINE_OFFSET = 1.5
# Clear space (px) left in a horizontal wire on each side of a vertical line
# that crosses it without interacting.
CROSSING_GAP = 4.0
HORIZONTAL_LINE_STROKE_WIDTH = 1
VERTICAL_LINE_STROKE_WIDTH = 3
DOUBLED_VERTICAL_LINE_STROKE_WIDTH = 1


def fixup_text(text: str) -> str:
Expand Down Expand Up @@ -68,6 +76,66 @@ def _line(
)


def _split_segment(
start: float, end: float, cuts: Iterable[tuple[float, float]]
) -> list[tuple[float, float]]:
"""Removes gap intervals from the 1-D span [min(start, end), max(start, end)].

Overlapping or touching cuts are merged, and all cuts are clipped to the
span. Only strictly positive-length surviving segments are returned.

Args:
start: One endpoint of the span.
end: The other endpoint of the span.
cuts: Gap intervals to remove, each as `(cut_start, cut_end)`.

Returns:
Surviving `(seg_start, seg_end)` segments in increasing order.
"""
lo, hi = (start, end) if start <= end else (end, start)
segments: list[tuple[float, float]] = []
pos = lo
for cut_lo, cut_hi in sorted(cuts):
if cut_lo >= cut_hi or cut_hi <= pos or cut_lo >= hi:
continue
if cut_lo > pos:
segments.append((pos, cut_lo))
pos = max(pos, cut_hi)
if pos < hi:
segments.append((pos, hi))
return segments


def _crossing_columns(
tdd: cirq.TextDiagramDrawer, y: float, x1: float, x2: float
) -> dict[float, bool]:
"""Finds columns where vertical lines cross a horizontal line without interacting.

A crossing at `(x, y)` is non-interacting when `(x, y)` lies strictly
inside both lines and the diagram has no entry at `(x, y)`. Endpoints
(T-junctions, moment-group corners) and cells holding any entry (control
dots, gate boxes, swap crosses, or empty wire symbols `''`) represent
interactions and are excluded.

Args:
tdd: The text diagram being rendered.
y: Raw TDD row coordinate of the horizontal line.
x1: One raw TDD column endpoint of the horizontal line.
x2: The other raw TDD column endpoint of the horizontal line.

Returns:
Mapping from raw TDD column coordinates to whether any crossing
vertical line in that column is doubled.
"""
x_lo, x_hi = (x1, x2) if x1 <= x2 else (x2, x1)
columns: dict[float, bool] = {}
for vx, vy1, vy2, _, v_doubled in tdd.vertical_lines:
y_lo, y_hi = (vy1, vy2) if vy1 <= vy2 else (vy2, vy1)
if x_lo < vx < x_hi and y_lo < y < y_hi and (vx, y) not in tdd.entries:
columns[vx] = columns.get(vx, False) or v_doubled
return columns


def _rect(
x: float,
y: float,
Expand Down Expand Up @@ -203,14 +271,44 @@ def tdd_to_svg(
ref_boxheight: float = 40,
col_padding: float = 20,
row_padding: float = 10,
crossing_gap: float = CROSSING_GAP,
) -> str:
"""Render a TextDiagramDrawer as an SVG string.

Args:
tdd: The text diagram drawer to render.
ref_boxwidth: Minimum width of a gate box, in px.
ref_boxheight: Height of a gate box, in px.
col_padding: Default horizontal space between columns, in px.
row_padding: Vertical space between rows, in px.
crossing_gap: Clear space in px left in a horizontal line on each side
of a vertical line that crosses it without interacting. Pass `0`
to draw horizontal lines unbroken.

Returns:
An SVG document string representing `tdd`.

Raises:
ValueError: If `crossing_gap` is negative or not finite.
"""
if not math.isfinite(crossing_gap) or crossing_gap < 0:
raise ValueError(f'crossing_gap must be finite and non-negative, got {crossing_gap!r}.')

row_starts, row_heights, yi_map = _fit_vertical(
tdd=tdd, ref_boxheight=ref_boxheight, row_padding=row_padding
)
col_starts, col_widths = _fit_horizontal(
tdd=tdd, ref_boxwidth=ref_boxwidth, col_padding=col_padding
)

def col_x(xi: float) -> float:
idx = int(xi)
return col_starts[idx] + col_widths[idx] / 2

def row_y(yi: float) -> float:
idx = yi_map[yi]
return row_starts[idx] + row_heights[idx] / 2

t = (
f'<svg xmlns="http://www.w3.org/2000/svg" '
f'width="{col_starts[-1]}" height="{row_starts[-1]}">'
Expand All @@ -220,34 +318,44 @@ def tdd_to_svg(
# col_starts and row_starts
# t += _debug_spacing(col_starts, row_starts)

for 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]
y = row_starts[yi] + row_heights[yi] / 2
single_half_opening = VERTICAL_LINE_STROKE_WIDTH / 2 + crossing_gap
doubled_half_opening = (
DOUBLED_LINE_OFFSET + DOUBLED_VERTICAL_LINE_STROKE_WIDTH / 2 + crossing_gap
)

t += _line(x1, y, x2, y, doubled=doubled)
for yi, xi1, xi2, _, doubled in tdd.horizontal_lines:
x1 = col_x(xi1)
x2 = col_x(xi2)
y = row_y(yi)

crossing_cols = _crossing_columns(tdd, yi, xi1, xi2) if crossing_gap > 0 else {}
if crossing_cols:
cuts = []
for vx, v_doubled in crossing_cols.items():
half = doubled_half_opening if v_doubled else single_half_opening
cx = col_x(vx)
cuts.append((cx - half, cx + half))
segments = _split_segment(x1, x2, cuts)
else:
# Preserve exact endpoint order when no gaps cut the wire so
# crossing_gap=0 and crossing-free wires stay byte-identical to main.
segments = [(x1, x2)]
for seg_x1, seg_x2 in segments:
t += _line(
seg_x1, y, seg_x2, y, strokewidth=HORIZONTAL_LINE_STROKE_WIDTH, doubled=doubled
)

for 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)
x = col_starts[xi] + col_widths[xi] / 2

x = col_x(xi)
y1 = row_y(yi1)
y2 = row_y(yi2)
# 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)
strokewidth = DOUBLED_VERTICAL_LINE_STROKE_WIDTH if doubled else VERTICAL_LINE_STROKE_WIDTH
t += _line(x, y1, x, y2, strokewidth=strokewidth, 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
x = col_x(xi)
y = row_y(yi)

boxheight = ref_boxheight
boxwidth = col_widths[xi] - tdd.horizontal_padding.get(xi, col_padding)
Expand Down
Loading
Loading