Skip to content

diagram

SVG diagram rendering for quantum circuits.

Diagram

Diagram(svg: str, html: str)

Wrapper for SVG diagram with Jupyter notebook display support.

Parameters:

Name Type Description Default
svg str

Raw SVG markup suitable for saving to .svg files.

required
html str

HTML-wrapped version for interactive Jupyter display.

required
Source code in src/tsim/utils/diagram.py
23
24
25
26
27
28
29
30
31
32
def __init__(self, svg: str, html: str):
    """Create a diagram from raw SVG markup and an HTML-wrapped version.

    Args:
        svg: Raw SVG markup suitable for saving to ``.svg`` files.
        html: HTML-wrapped version for interactive Jupyter display.

    """
    self._svg = svg
    self._html = html

__str__

__str__() -> str

Return the raw SVG string.

Source code in src/tsim/utils/diagram.py
34
35
36
def __str__(self) -> str:
    """Return the raw SVG string."""
    return self._svg

GateLabel dataclass

GateLabel(label: str, annotation: str | None = None)

Label for a gate in the SVG diagram.

placeholders_to_t

placeholders_to_t(
    svg_string: str,
    placeholder_id_to_labels: dict[float, GateLabel],
) -> str

Replace I_ERROR placeholder gates in an SVG diagram with actual gate names.

Supported gates are T, T†, R_Z, R_X, R_Y, U_3.

Parameters:

Name Type Description Default
svg_string str

The SVG string from stim's diagram() method containing I_ERROR placeholder gates whose p-value are used as identifiers.

required
placeholder_id_to_labels dict[float, GateLabel]

Mapping from identifier (float), i.e. the p values of I_ERROR gates, to GateLabel.

required

Returns:

Type Description
str

Modified SVG string with I_ERROR gates replaced by the actual gate names.

Source code in src/tsim/utils/diagram.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def placeholders_to_t(
    svg_string: str, placeholder_id_to_labels: dict[float, GateLabel]
) -> str:
    """Replace I_ERROR placeholder gates in an SVG diagram with actual gate names.

    Supported gates are T, T†, R_Z, R_X, R_Y, U_3.

    Args:
        svg_string: The SVG string from stim's diagram() method containing I_ERROR
            placeholder gates whose p-value are used as identifiers.
        placeholder_id_to_labels: Mapping from identifier (float), i.e. the p values of
            I_ERROR gates, to GateLabel.

    Returns:
        Modified SVG string with I_ERROR gates replaced by the actual gate names.

    """
    root = etree.fromstring(svg_string.encode())

    # Collect all red text elements (the identifier labels)
    red_texts = []
    for elem in root.iter():
        if elem.tag.endswith("text") and elem.get("stroke") == "red" and elem.text:
            red_texts.append(elem)

    # Collect all replacements needed (without modifying the tree)
    replacements: list[tuple[etree._Element, etree._Element, GateLabel]] = []

    for placeholder_id, gate_label in placeholder_id_to_labels.items():
        for red_text in red_texts:
            if str(placeholder_id) in red_text.text:
                err_text = red_text.getprevious()
                if err_text is not None and _is_err_element(err_text):
                    replacements.append((red_text, err_text, gate_label))
                break

    # Perform all modifications
    for red_text, err_text, gate_label in replacements:
        x = err_text.get("x")
        y = err_text.get("y")

        # Create the replacement text element
        new_text = etree.Element(err_text.tag)
        new_text.set("dominant-baseline", "central")
        new_text.set("text-anchor", "middle")
        new_text.set("font-family", "monospace")
        new_text.set("font-size", "30")
        new_text.set("x", x)
        new_text.set("y", y)

        # Handle labels that may contain XML markup
        label = gate_label.label
        if "<" in label:
            fragment = etree.fromstring(f"<root>{label}</root>")
            new_text.text = fragment.text
            for child in fragment:
                new_text.append(child)
        else:
            new_text.text = label

        # Replace ERR element
        parent = err_text.getparent()
        if parent is not None:
            parent.replace(err_text, new_text)

        # Handle red text: remove or update
        if gate_label.annotation is None:
            red_parent = red_text.getparent()
            if red_parent is not None:
                red_parent.remove(red_text)
        else:
            red_text.text = gate_label.annotation
            red_text.set("stroke", "black")

    return etree.tostring(root, encoding="unicode")

render_pyzx_d3

render_pyzx_d3(
    stim_circ: Circuit, kwargs: dict[str, Any]
) -> GraphS

Render a stim circuit as a pyzx ZX diagram using d3.js.

Parameters:

Name Type Description Default
stim_circ Circuit

The stim circuit to render.

required
kwargs dict[str, Any]

Additional keyword arguments passed to the underlying diagram renderer.

required

Returns:

Type Description
GraphS

A pyzx ZX diagram.

Source code in src/tsim/utils/diagram.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def render_pyzx_d3(stim_circ: stim.Circuit, kwargs: dict[str, Any]) -> GraphS:
    """Render a stim circuit as a pyzx ZX diagram using d3.js.

    Args:
        stim_circ: The stim circuit to render.
        kwargs: Additional keyword arguments passed to the underlying diagram renderer.

    Returns:
        A pyzx ZX diagram.

    """
    built = parse_stim_circuit(stim_circ, track_classical_wires=True)
    g = built.graph

    if len(g.vertices()) == 0:
        return g

    g = g.clone()
    if built.last_vertex:
        max_row = max(g.row(v) for v in built.last_vertex.values())
        for q in built.last_vertex:
            g.set_row(built.last_vertex[q], max_row)

    for v in list(g.vertices()):
        phase_vars = g._phaseVars[v]
        if len(phase_vars) != 1:
            continue
        phase = next(iter(phase_vars))
        if phase.startswith("det") or phase.startswith("obs"):
            row = g.row(v)
            qubit = -2 if phase.startswith("det") else -2.5
            vb = g.add_vertex(
                zx.utils.VertexType.BOUNDARY,
                qubit=qubit,
                row=row,
            )
            g.add_edge((v, vb))
        if phase.startswith("m["):
            g.set_phase(v, 0)

    if kwargs.get("scale_horizontally", False):
        scale_horizontally(g, kwargs.pop("scale_horizontally", 1.0))
    zx.draw(g, **kwargs)
    return g

render_svg

render_svg(
    c: Circuit,
    type: str,
    *,
    tick: int | range | None = None,
    filter_coords: Iterable[Iterable[float] | DemTarget] = (
        (),
    ),
    rows: int | None = None,
    width: float | None = None,
    height: float | None = None,
    zoomable: bool = True
) -> Diagram

Render a stim circuit timeline/timeslice diagram with custom labels.

Source code in src/tsim/utils/diagram.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def render_svg(
    c: stim.Circuit,
    type: str,
    *,
    tick: int | range | None = None,
    filter_coords: Iterable[Iterable[float] | stim.DemTarget] = ((),),
    rows: int | None = None,
    width: float | None = None,
    height: float | None = None,
    zoomable: bool = True,
) -> Diagram:
    """Render a stim circuit timeline/timeslice diagram with custom labels."""
    modified_circ, placeholder_id_to_labels = tagged_gates_to_placeholder(c)
    svg_with_placeholders = str(
        modified_circ.diagram(type, tick=tick, filter_coords=filter_coords, rows=rows)
    )
    svg = placeholders_to_t(svg_with_placeholders, placeholder_id_to_labels)
    svg = _deduplicate_doubled_spp(svg)

    # Compute the missing dimension from the SVG viewBox aspect ratio.
    if width is None and height is not None:
        width = _width_from_viewbox(svg, height)
    elif height is None and width is not None:
        size = _viewbox_size(svg)
        if size is not None and size[0] != 0:
            height = width / size[0] * size[1]

    if zoomable:
        html = wrap_svg_zoomable(
            svg, width=width, height=height if height is not None else 700
        )
    else:
        html = wrap_svg(svg, width=width, height=height)
    return Diagram(svg, html)

tagged_gates_to_placeholder

tagged_gates_to_placeholder(
    circuit: Circuit,
) -> tuple[stim.Circuit, dict[float, GateLabel]]

Replace tagged gates with I_ERROR placeholder gates for rendering.

Converts S[T], S_DAG[T], I[R_X(...)], I[R_Y(...)], I[R_Z(...)], I[U3(...)] to I_ERROR placeholder gates whose p-values are used as identifiers.

Parameters:

Name Type Description Default
circuit Circuit

The stim circuit to replace tagged gates with I_ERROR placeholder gates.

required

Returns:

Type Description
Circuit

A tuple containing the modified circuit and a dictionary mapping the p-values

dict[float, GateLabel]

of the I_ERROR placeholder gates to the actual gate names.

Source code in src/tsim/utils/diagram.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def tagged_gates_to_placeholder(
    circuit: stim.Circuit,
) -> tuple[stim.Circuit, dict[float, GateLabel]]:
    """Replace tagged gates with I_ERROR placeholder gates for rendering.

    Converts S[T], S_DAG[T], I[R_X(...)], I[R_Y(...)], I[R_Z(...)], I[U3(...)]
    to I_ERROR placeholder gates whose p-values are used as identifiers.

    Args:
        circuit: The stim circuit to replace tagged gates with I_ERROR placeholder gates.

    Returns:
        A tuple containing the modified circuit and a dictionary mapping the p-values
        of the I_ERROR placeholder gates to the actual gate names.

    """
    replace_dict: dict[float, GateLabel] = {}
    modified_circ = _replace_tagged_gates(circuit, replace_dict)
    return modified_circ, replace_dict

wrap_svg

wrap_svg(
    svg: str,
    *,
    width: float | None = None,
    height: float | None = None
) -> str

Wrap an SVG string in a container div.

Parameters:

Name Type Description Default
svg str

Raw SVG markup.

required
width float | None

Width of the container in pixels.

None
height float | None

Height of the container in pixels (unused, kept for API symmetry with :func:wrap_svg_zoomable).

None
Source code in src/tsim/utils/diagram.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def wrap_svg(
    svg: str,
    *,
    width: float | None = None,
    height: float | None = None,
) -> str:
    """Wrap an SVG string in a container div.

    Args:
        svg: Raw SVG markup.
        width: Width of the container in pixels.
        height: Height of the container in pixels (unused, kept for API
            symmetry with :func:`wrap_svg_zoomable`).

    """
    if width is None:
        return f"""
        <div style="background: white">
        {svg}
        </div>
        """

    return f"""
    <div style="overflow-x: scroll; background: white; width: fit-content;">
    <div style="width: {width}px">
    {svg}
    </div>
    </div>
    """

wrap_svg_zoomable

wrap_svg_zoomable(
    svg: str,
    *,
    width: float | None = None,
    height: float = 700
) -> str

Wrap an SVG in a zoomable, scrollable container.

The container has the given pixel dimensions. When width is None the container fills the available width. Users can pan by scrolling and zoom with pinch-zoom (trackpad) or Ctrl/Cmd + wheel. Zoom is anchored at the cursor position.

Parameters:

Name Type Description Default
svg str

Raw SVG markup.

required
width float | None

Pixel width of the container, or None for full width.

None
height float

Pixel height of the container.

700
Source code in src/tsim/utils/diagram.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def wrap_svg_zoomable(
    svg: str, *, width: float | None = None, height: float = 700
) -> str:
    """Wrap an SVG in a zoomable, scrollable container.

    The container has the given pixel dimensions.  When *width* is ``None``
    the container fills the available width.  Users can pan by scrolling
    and zoom with pinch-zoom (trackpad) or Ctrl/Cmd + wheel.  Zoom is
    anchored at the cursor position.

    Args:
        svg: Raw SVG markup.
        width: Pixel width of the container, or ``None`` for full width.
        height: Pixel height of the container.

    """
    size = _viewbox_size(svg)
    if size is None or size[1] == 0:
        nat_w, nat_h = 800.0, 200.0
    else:
        nat_w, nat_h = size

    # Stim SVGs only have a viewBox, no explicit width/height. Inside an
    # inline-block container they collapse, so force the SVG to render at its
    # natural pixel size.
    sized_svg = re.sub(
        r"<svg\b",
        f'<svg width="{nat_w}" height="{nat_h}"',
        svg,
        count=1,
    )

    # Initial scale fits the SVG into the container.
    scale_h = height / nat_h if nat_h > 0 else 1.0
    if width is not None and nat_w > 0:
        initial_scale = min(scale_h, width / nat_w)
    else:
        initial_scale = scale_h
    init_w = nat_w * initial_scale
    init_h = nat_h * initial_scale

    width_style = f"width:{width}px" if width is not None else "width:100%"
    uid = uuid.uuid4().hex[:12]
    return f"""
<div data-tsim-zoom="{uid}" style="{width_style}; height:{height}px; overflow:auto; background:white; border:1px solid #eee; position:relative;">
  <div style="display:inline-block; overflow:hidden; width:{init_w}px; height:{init_h}px;">
    <div style="transform-origin:0 0; display:block; width:{nat_w}px; height:{nat_h}px; transform:scale({initial_scale});">
      {sized_svg}
    </div>
  </div>
</div>
<script>
(function() {{
  var wrap = document.querySelector('[data-tsim-zoom="{uid}"]');
  if (!wrap || wrap.dataset.tsimZoomInit) return;
  wrap.dataset.tsimZoomInit = "1";
  var size = wrap.firstElementChild;
  var xform = size.firstElementChild;
  var natW = {nat_w};
  var natH = {nat_h};
  var scale = {initial_scale};
  var cw = wrap.clientWidth;
  if (cw > 0 && natW > 0) {{
    scale = cw / natW;
  }}
  function apply() {{
    xform.style.transform = 'scale(' + scale + ')';
    size.style.width = (natW * scale) + 'px';
    size.style.height = (natH * scale) + 'px';
  }}
  apply();
  wrap.addEventListener('wheel', function(e) {{
    if (e.ctrlKey || e.metaKey) {{
      e.preventDefault();
      var rect = wrap.getBoundingClientRect();
      var mx = e.clientX - rect.left + wrap.scrollLeft;
      var my = e.clientY - rect.top + wrap.scrollTop;
      var factor = Math.exp(-e.deltaY * 0.01);
      var newScale = Math.min(Math.max(0.02, scale * factor), 40);
      var ratio = newScale / scale;
      scale = newScale;
      apply();
      wrap.scrollLeft = mx * ratio - (e.clientX - rect.left);
      wrap.scrollTop = my * ratio - (e.clientY - rect.top);
    }}
  }}, {{ passive: false }});
}})();
</script>
"""