Skip to content

Add _qasm_ transpilation to CircuitOperation, and use it in If - #8418

Open
Acciaccatura wants to merge 4 commits into
quantumlib:mainfrom
Acciaccatura:issue8839a
Open

Acciaccatura wants to merge 4 commits into
quantumlib:mainfrom
Acciaccatura:issue8839a

Conversation

@Acciaccatura

@Acciaccatura Acciaccatura commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

hello! while working on #8839, it seems like CircuitOperation may be used more and more to represent circuit control flow bodies of more than one operation (e.g. below):

if more_operations or not isinstance(sub_operation, raw_types.Operation):
# Multiple operations: wrap in a CircuitOperation
# Inline import to prevent circular dependency.
from cirq.circuits import Circuit, CircuitOperation
c = Circuit(sub_operation, *more_operations)
self._conditions: tuple[cirq.Condition, ...] = conds_tuple
self._sub_operation: cirq.Operation = CircuitOperation(c.freeze())

right now, CircuitOperation does not implement the QASM protocol, so any control flow operator will fail to transpile to QASM unless they explicitly handle transpiling CircuitOperations themselves. maybe it would be useful to just implement this protocol to avoid some code deduplication? in this PR:

  • CircuitOperation implements _qasm_, which simply outputs its contents decomposed. ex:
[ 0: ───H───@─── ]
[           │    ]
[ 1: ───────X─── ]

becomes:

h q0;
cx q0,q1;

  • If is updated to conditionally show braces when _sub_operation is a CircuitOperation. ex:
0: ───M───────────────────────────────
      ║
1: ───╫───If(a, [ 1: ───X───Z─── ])───
      ║   ║
a: ═══@═══╩═══════════════════════════

becomes:

// Generated from Cirq v1.8.0.dev0

OPENQASM 2.0;
include "qelib1.inc";


// Qubits: [q(0), q(1)]
qreg q[2];
creg m_a[1];


measure q[0] -> m_a[0];

// Operation: If(a, [ 1: ───X───Z─── ])
if (m_a==1) {
    x q[1];
    z q[1];
}
  • the examples used above have been turned into test cases for the respective operations.

@github-actions github-actions Bot added the size: S 10< lines changed <50 label Oct 8, 2026
@Acciaccatura
Acciaccatura marked this pull request as ready for review October 8, 2026 10:05
@Acciaccatura
Acciaccatura requested a review from a team as a code owner October 8, 2026 10:05
@codecov

codecov Bot commented Oct 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.59%. Comparing base (1403830) to head (2121e08).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #8418   +/-   ##
=======================================
  Coverage   99.59%   99.59%           
=======================================
  Files        1133     1133           
  Lines      103919   103936   +17     
=======================================
+ Hits       103498   103515   +17     
  Misses        421      421           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mhucka mhucka 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.

@Acciaccatura Thank you for working on this, and i'm sorry it took so long to review this. Here's a preliminary set of comments. I think there are a couple of other places that may need changes, but it would be best to merge the branch and address these initial points, and then there can be another round of reviews.

Comment on lines +267 to +269
if isinstance(self._sub_operation, CircuitOperation):
subop_qasm_body = ''.join(f' {line}\n' for line in subop_qasm.strip().split('\n'))
subop_qasm = f'{{\n{subop_qasm_body}}}'

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.

I think this will not produce syntactically correct output in openqasm 2.0. It will produce if (m_a==1) {\n x q[1];\n z q[1];\n}, but the { ... } are not part of openqasm 2.0.

It may be worth looking at how ClassicallyControlledOperation.qasm handles multi-statement conditional QASM output.

return None
from cirq.circuits import CircuitOperation

if isinstance(self._sub_operation, CircuitOperation):

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.

I think this currently will miss multi-statement single operations and also not handle 0- or 1-operation CircuitOperations correctly. A single gate operation whose _qasm_ emits multiple statements, such as cirq.If('a', cirq.CCZ(q0, q1, q2)) or cirq.If('a', cirq.CCY(q0, q1, q2)), is a GateOperation, not a CircuitOperation. Using isinstance(self._sub_operation, CircuitOperation), the If('a', cirq.CCZ(q0, q1, q2)) will leave the 2nd and 3rd statements unguarded; i.e., if (m_a==1) h q[2];\nccx q[0],q[1],q[2];\nh q[2];\n), reproducing #8329.

Conversely, cirq.If('a', [cirq.X(q1)]) will wrap the 1-element list in a CircuitOperation and emit braces, whereas cirq.If('a', cirq.X(q1)) will not. And an empty cirq.If('a', []) (which has subop_qasm == "") will end up with "".strip().split('\n'), which is [''], which produces 'if (m_a==1) {\n \n}' instead of "".

# TODO: Implement transpilation for additional controls.
if self.repetitions != 1 or self.repeat_until is not None:
return None # pragma: no cover
return ''.join(protocols.qasm(op, args=args, qubits=qubits) for op in self._decompose_())

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.

Whoops, this is problematic. CircuitOperation._qasm_ will end up raising TypeError instead of returning None when a sub-operation needs decomposition or does not directly implement _qasm_. This will break existing QasmOutput decomposition.

If self._decompose_() contains any operation whose _qasm_ is unimplemented or returns None to request decomposition, such as cirq.CNOT(q0, q1).controlled_by(q2)) or a 2-qubit MatrixGate, the protocols.qasm(op, ...) will raise TypeError.

To fix it, an approach may be to query each decomposed operation with default=None and return None if any sub-operation cannot be directly formatted to QASM (allowing QasmOutput to fall back to full decomposition).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size: S 10< lines changed <50

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants