Skip to content

diagram

SVG diagram rendering for quantum circuits.

Diagram

Diagram(svg: str)

Wrapper for SVG diagram with Jupyter notebook display support.

Source code in src/tsim/utils/diagram.py
16
17
18
def __init__(self, svg: str):
    """Create a diagram from SVG markup."""
    self._svg = svg

__str__

__str__() -> str

Return the raw SVG string.

Source code in src/tsim/utils/diagram.py
20
21
22
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

required
placeholder_id_to_labels dict[float, GateLabel]

Mapping from identifier (float), i.e. the p values of

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
 96
 97
 98
 99
100
101
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
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_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
) -> Diagram

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

Source code in src/tsim/utils/diagram.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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,
) -> 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)
    wrapped = wrap_svg(svg, width=width, height=height)
    return Diagram(wrapped)

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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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

Optionally wrap an SVG string in a scrolling container.

Parameters:

Name Type Description Default
svg str

Raw SVG markup.

required
width float | None

Explicit width for the container.

None
height float | None

Desired height; used to infer width from viewBox if width is not given.

None
Source code in src/tsim/utils/diagram.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def wrap_svg(
    svg: str,
    *,
    width: float | None = None,
    height: float | None = None,
) -> str:
    """Optionally wrap an SVG string in a scrolling container.

    Args:
        svg: Raw SVG markup.
        width: Explicit width for the container.
        height: Desired height; used to infer width from viewBox if width is not given.

    """
    computed_width = width
    if (
        computed_width is None
        and height is not None
        and isinstance(height, (float, int))
    ):
        computed_width = _width_from_viewbox(svg, float(height))

    if computed_width is None:
        return svg

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