# Does Stim support classical-bit controlled gates?

Does Stim support classical-bit controlled gates?

I want to apply a gate based on a certain measurement outcome, e.g. do Z^a on qubit B, where a is the measurement outcome (0 or 1) of qubit A. That is, we do nothing if we measure a '0' on qubit A, and we apply a Z gate on qubit B if we measure a '1' on qubit A.

This kind of classical-bit controlled gate is very useful in many schemes such as lattice surgery and teleportation. So I want to know how to implement this kind of gate in Stim. I checked it here Gates supported by Stim, and it seems Stim doesn't include it directly. So it seems we have to use tricks like if else to implement it.

So how could I implement this kind of gate by Stim?

You can classically control X, Y, or Z gates by specifying a measurement result as the control of CX, CY, or CZ. In circuit files this looks like CX rec[-2] 3. In python it looks like circuit.append("CX", [stim.target_rec(-2), 3]).

For example, here is a teleportation circuit:

# Create entanglement between Alice and Bob
H 1
CX 1 9

# Alice prepares a state to send
H 0
S 0

# Alice does a Bell basis measurement
CX 0 1
H 0
M 0 1

# Alice communicates the bits to Bob, who performs the corrections
CZ rec[-2] 9
CX rec[-1] 9

# Bob now has the qubit that Alice prepared
# Bob reverses Alice's preparations to check the qubit's state
S_DAG 9
H 9
M 9
DETECTOR rec[-1]

Output from stim.Circuit(...).diagram('timeline-svg'):

Stim circuits only allow Pauli gates to be classically controlled, because classically controlling other gates breaks the algorithmic trick Stim uses to sample thousands of times faster after an initial reference sample is acquired.

This kind of classical-bit controlled gate is very useful in many schemes such as lattice surgery and teleportation.

Fun fact: Pauli gate feedback in stabilizer circuits is so well behaved that it can be automatically removed. The method stim.Circuit.with_inlined_feedback takes a circuit with feedback and returns a circuit with no feedback, which has exactly equivalent error correction structure (the detectors and observables cover the same circuit locations, by folding feedback into the list of measurements they depend upon). This lets you write QEC circuits as if feedback was available, and then derive an equivalent circuit that can run on hardware that has no feedback. Try it on the teleportation circuit.

Although feedback is a useful shorthand when defining behavior, it is almost never actually required. In fact, many many constructions become much easier to grok if you start just ignoring feedback and Paulis altogether knowing they can be solved later. This is one of the key features that makes the stabilizer ZX calculus such a useful tool for understanding things like lattice surgery.