Repository navigation
Emit parametric gate tags in the positional form - #280
Conversation
Tags are now the Tsim instruction itself, e.g. I[R_X(0.1)] and I[U3(0.1, 0.2, 0.3)], instead of I[R_X(theta=0.1*pi)]. All writers (append, inverse, shorthand conversion) go through format_parametric_tag. The keyword form is still read, and circuit text and append rewrite it. stim_to_shorthand now parses tags instead of matching the keyword form with regexes, so it reads both forms; it also no longer turns SPP[R_PAULI(a)] X0*X1 Z2 into an invalid R_XX(a) 0 1 Z2. stim_timeline_text only draws keyword-form tags, so the timeline-text diagram rewrites tags to that form before rendering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 649e0236c2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| f"{gate_name} takes {len(expected)} angles ({', '.join(expected)}), " | ||
| f"got {len(angles)}" | ||
| ) | ||
| return f"{gate_name}({', '.join(str(float(a)) for a in angles)})" |
There was a problem hiding this comment.
Preserve angles outside the float range
Avoid converting every parsed Fraction through float: a syntactically valid tag such as I[R_X(1e309)] 0 parses exactly but now raises OverflowError while being canonicalized, rendered by stim_to_shorthand, or prepared for a timeline diagram. The previous canonicalizer caught this formatting overflow and retained the original tag, so circuits using large periodic rotation angles could still be constructed; format parsed fractions without a float conversion, or restore overflow handling around formatting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
🟡 Changes recommended
The R_PAULI lookahead copies all remaining circuit text for each match, causing quadratic copying in str(circuit) and repr(circuit) for circuits with many Pauli rotations.
1 open issue
What changed in this PR
This PR standardizes Tsim’s emitted parametric gate tags on positional syntax with angles in units of pi, while retaining support for reading legacy keyword tags.
Changes:
- Centralizes positional tag formatting across circuit construction, append, inverse, and text conversion.
- Updates shorthand parsing and prevents invalid two-qubit shorthand for multi-product Pauli rotations.
- Adds a legacy-format compatibility shim for timeline-text diagrams, updates tests, and documents the output change.
| File | Description |
|---|---|
test/unit/utils/test_program_text.py |
Updates positional output expectations and covers legacy input and Pauli-product conversion. |
test/unit/test_circuit.py |
Checks legacy-tag compatibility and append normalization. |
test/unit/core/test_parse.py |
Updates the expected malformed-tag guidance. |
src/tsim/utils/program_text.py |
Normalizes tags and parses both formats when producing shorthand. |
src/tsim/utils/diagram.py |
Converts tags to keyword syntax for timeline-text rendering. |
src/tsim/core/tags.py |
Provides positional formatting and a legacy-format helper. |
src/tsim/core/parse.py |
Updates parser documentation and comments to emphasize positional syntax. |
src/tsim/circuit.py |
Uses shared tag formatting and the timeline-text wrapper. |
CHANGELOG.md |
Documents the breaking output change and compatibility behavior. |
Review effort: Balanced
rafaelha
left a comment
There was a problem hiding this comment.
A few findings from checking round trips and the construction paths. Most things hold up: REPEAT blocks, multiple Pauli products, ! inversions, the lone-pair rule for R_XX/R_YY/R_ZZ, and U3/R_PAULI inverse() all round-trip. The timeline-text shim produces the same output as rendering the legacy text directly, and no keyword-form emitters are left in src or docs.
| tag = format_parametric_tag("R_PAULI", alpha) | ||
| name = "SPP" | ||
| arg = None | ||
| elif name in ("I", "SPP", "SPP_DAG") and tag: |
There was a problem hiding this comment.
append("I", tag=...) and circuit text canonicalize legacy tags, but Circuit(stim.Circuit), from_stim_program, append(stim.CircuitInstruction) and += stim.Circuit don't. As a result, Circuit(str(c)) == c now fails for circuits that come from the .stim files Tsim wrote before this change:
a = Circuit(stim.Circuit("I[R_X(theta=0.25*pi)] 0"))
Circuit(str(a)) == a # False here, True on main
c = Circuit(); c.append(stim.Circuit("I[R_X(theta=0.25*pi)] 0")[0])
Circuit(str(c)) == c # FalseOn main it was the other way round: positional tags from Stim broke the round trip. Legacy tags are what existing saved circuits contain, though. Could we canonicalize tags on those paths too (walk the instructions and rewrite I/SPP/SPP_DAG tags, recursing into REPEAT bodies)? Then the != in test_legacy_tag_from_stim_matches_shorthand would become ==. Another option is to make __eq__ compare canonicalized tags.
| f"{gate_name} takes {len(expected)} angles ({', '.join(expected)}), " | ||
| f"got {len(angles)}" | ||
| ) | ||
| return f"{gate_name}({', '.join(str(float(a)) for a in angles)})" |
There was a problem hiding this comment.
str(float(a)) keeps -0.0, but canonical_parametric_tag and stim_to_shorthand go through Fraction, which turns it into 0.0. So the two paths disagree, and since stim_to_shorthand now re-formats the angle instead of copying it, this is a new round-trip failure (main passes it):
c = Circuit("R_X(-0.0) 0") # tag R_X(-0.0)
str(c) # 'R_X(0.0) 0'
Circuit(str(c)) == c # False
Circuit("I[R_X(-0.0)] 0") == c # FalseSuggested fix: normalize here, e.g. x = float(a); x = 0.0 if x == 0 else x. While you're here, consider rejecting non-finite angles too. Circuit("R_X(1e400) 0") and append("R_X", [0], float("nan")) produce R_X(inf)/R_X(nan) tags that the parser then rejects. That happened before this PR as well.
| replace_pauli_pair, | ||
| text, | ||
| ) | ||
| text = re.sub(r"\bI\[([^\]\n]*)\]", replace_single_qubit, text) |
There was a problem hiding this comment.
\bI\[ (and \bSPP\[ below) also match inside another instruction's tag. The positional form is natural to write in a note, so this now triggers more easily. The old regexes needed theta=...*pi:
c = Circuit(); c.append("X", [0], tag="note I[R_X(0.1)")
str(c) # 'X[note R_X(0.1) 0' -> unparseable(Stim escapes ] in tags as \C, so the inner tag can't contain one, but the outer tag's closing ] completes the match.) Anchoring both patterns to the start of the instruction would fix it, e.g. (?m)^(\s*)I\[([^\]\n]*)\] with the indent kept. The S[T]/SPP[T] rewrites have the same issue already on main.
☂️ Code Coverage
Overall Coverage
New FilesNo new covered files... Modified Files
|
- Circuit(stim.Circuit), from_stim_program, += stim.Circuit, appending a stim.CircuitInstruction/CircuitRepeatBlock and approx_equals now rewrite legacy keyword-form parametric tags (also inside REPEAT blocks), so Circuit(str(c)) == c holds for circuits loaded from older Stim files. Internal operations use a private _wrap that skips the rewrite. - format_parametric_tag writes -0.0 as 0.0, matching what parsing gives back. - stim_to_shorthand works line by line and only rewrites the gate at the start of an instruction, so gate-like text inside another instruction's tag (e.g. X[note I[R_X(0.1)] or X[a S[T]) is left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| f"got {len(angles)}" | ||
| ) | ||
| # `+ 0.0` turns -0.0 into 0.0, which is what parsing the tag gives back. | ||
| return f"{gate_name}({', '.join(str(float(a) + 0.0) for a in angles)})" |
| parsed = _try_parse_parametric_tag(tag) | ||
| if parsed is None: | ||
| return line | ||
| shorthand = format_parsed_parametric_tag(*parsed) |
Formatting a tag whose angle overflows a float raised OverflowError when a circuit was built; keep such tags unchanged, as before this branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |


Tsim had two tag formats for parametric gates: the keyword form
I[R_X(theta=0.1*pi)]and the positional formI[R_X(0.1)]. This PR makes the positional form, which is the Tsim instruction itself with angles in units of pi, the only one Tsim writes. The keyword form is still read.Changes
format_parametric_tag(gate, *angles)now writes the positional form. Every place that writes a tag uses it:Circuit.append(R_X/R_Y/R_Z, U3, R_XX/R_YY/R_ZZ, R_PAULI),inverse()andshorthand_to_stim.append(..., tag=...)onI/SPP/SPP_DAG, appending astim.CircuitInstruction, and astim.Circuitpassed toCircuit(...),from_stim_program,+=orapprox_equals. SoCircuit(stim.Circuit("I[R_X(theta=0.1*pi)] 0")) == Circuit("R_X(0.1) 0"), andCircuit(str(c)) == cholds for circuits loaded from older files. Internal operations use a private_wrapthat skips the rewrite. The check takes about 12 ms for a 17k-instruction circuit.stim_to_shorthandnow works line by line and parses each instruction's tag, so it reads both forms. It only rewrites the gate at the start of an instruction, so gate-like text inside another instruction's tag (such asX[note I[R_X(0.1)] 0) is left alone. It also no longer turnsSPP[R_PAULI(a)] X0*X1 Z2into the invalidR_XX(a) 0 1 Z2.-0.0is written as0.0, the value parsing gives back.stim-timeline-textonly draws keyword-form tags (it drew-I-for positional ones). Thetimeline-textdiagram now rewrites tags to that form before rendering. Once the upstream renderer supports the positional form, this shim can be removed.This is a breaking change in output:
stim_circuitand other written tags differ from before. The CHANGELOG entry is under Unreleased → Changed.Testing
test_kernels.py::test_the_calling_thread_keeps_parallel_kernels_after_run_tasks, also fails onmainlocally.appendrewriting legacy tags.🤖 Generated with Claude Code