Skip to content

Emit parametric gate tags in the positional form - #280

Merged
rafaelha merged 4 commits into
mainfrom
refactor/positional-parametric-tags
Nov 27, 2026
Merged

rafaelha merged 4 commits into
mainfrom
refactor/positional-parametric-tags

Conversation

@rafaelha

@rafaelha rafaelha commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Tsim had two tag formats for parametric gates: the keyword form I[R_X(theta=0.1*pi)] and the positional form I[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() and shorthand_to_stim.
  • Every way a circuit comes in rewrites legacy keyword tags to the positional form, including inside REPEAT blocks: circuit text, append(..., tag=...) on I/SPP/SPP_DAG, appending a stim.CircuitInstruction, and a stim.Circuit passed to Circuit(...), from_stim_program, += or approx_equals. So Circuit(stim.Circuit("I[R_X(theta=0.1*pi)] 0")) == Circuit("R_X(0.1) 0"), and Circuit(str(c)) == c holds for circuits loaded from older files. Internal operations use a private _wrap that skips the rewrite. The check takes about 12 ms for a 17k-instruction circuit.
  • stim_to_shorthand now 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 as X[note I[R_X(0.1)] 0) is left alone. It also no longer turns SPP[R_PAULI(a)] X0*X1 Z2 into the invalid R_XX(a) 0 1 Z2.
  • An angle of -0.0 is written as 0.0, the value parsing gives back.
  • stim-timeline-text only draws keyword-form tags (it drew -I- for positional ones). The timeline-text diagram 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_circuit and other written tags differ from before. The CHANGELOG entry is under Unreleased → Changed.

Testing

  • Full suite: 2570 passed. One failure, test_kernels.py::test_the_calling_thread_keeps_parallel_kernels_after_run_tasks, also fails on main locally.
  • Pre-commit passes, including pyright.
  • Added tests for reading legacy tags, the R_PAULI pair rewrite, and append rewriting legacy tags.

🤖 Generated with Claude Code

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>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T12:20:04.321606Z 649e023 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/tsim/core/tags.py Outdated
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)})"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread src/tsim/utils/program_text.py Resolved

@rafaelha rafaelha left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/tsim/circuit.py
tag = format_parametric_tag("R_PAULI", alpha)
name = "SPP"
arg = None
elif name in ("I", "SPP", "SPP_DAG") and tag:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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   # False

On 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.

Comment thread src/tsim/core/tags.py Outdated
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)})"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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   # False

Suggested 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.

Comment thread src/tsim/utils/program_text.py Outdated
replace_pauli_pair,
text,
)
text = re.sub(r"\bI\[([^\]\n]*)\]", replace_single_qubit, text)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

\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.

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

☂️ Code Coverage

current status: ✅

Overall Coverage

Statements Covered Coverage Threshold Status
7268 6239 86% 0% 🟢

New Files

No new covered files...

Modified Files

File Coverage Status
src/tsim/circuit.py 95% 🟢
src/tsim/core/parse.py 97% 🟢
src/tsim/core/tags.py 96% 🟢
src/tsim/utils/diagram.py 96% 🟢
src/tsim/utils/program_text.py 97% 🟢
TOTAL 96% 🟢

updated for commit: 5a6564e by action🐍

- 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>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:30
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Tag canonicalization can change circuit behavior by rounding exact rotation values and can raise OverflowError when processing unrelated gates’ metadata.

2 open issues
1 resolved since last review

Review effort: Balanced

Comment thread src/tsim/core/tags.py
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)})"
Comment thread src/tsim/utils/program_text.py Outdated
Comment on lines +353 to +356
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

codecov Bot commented Nov 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.52174% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/tsim/utils/diagram.py 84.61% 2 Missing ⚠️
src/tsim/core/tags.py 87.50% 1 Missing ⚠️
src/tsim/utils/program_text.py 98.43% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@rafaelha
rafaelha merged commit dbb0fd3 into main Nov 27, 2026
15 checks passed
@rafaelha
rafaelha deleted the refactor/positional-parametric-tags branch November 27, 2026 01:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants