# Repeat until success

## Background

This tutorial demonstrates the current capabilities of IBM dynamic-circuit backends to use mid-circuit measurements to produce a circuit that repeatedly attempts its setup until a syndrome measurement reveals that it has been successful.

We will build an abstract circuit that uses the non-parametrized gate set $\{H,\,X,\,S,\,\text{Toffoli}\}$ to construct a heralded $R_X(\theta)$ gate on a target qubit, where $\theta$ satisfies $\cos\theta = \frac35$. Each iteration of the circuit only has a finite chance of success, but successes are heralded, so we will use our dynamic-circuit capabilities to repeat the setup until it succeeds.

## Setup

Output:

Output:

```
<IBMBackend('ibm_rensselaer')>
```

## Build problem

A single trial of the probabalistic gate has the following form:

Output:

Output:

If *both* measurements of the control bits return $0$, the applied gate is $R_X(\theta)$ with $\cos\theta = \frac35$. If any of the measurements are $1$, then the applied gate is simply $X$, which is a failure. This is our heralding; we can tell from the measurement whether we applied the correct gate, without disturbing the coherence of the target qubit. Without fully reproducing the mathematics, the success probability of this gate is:

If there is a failure, we should reset the dirty state, and start again. Since we know what is applied in the case of a failure, we can use this knowledge to perform the reset efficiently, without using a general hardware reset. For the two auxiliary qubits, this is just an $X$ gate conditioned on its respective measurement being $1$. IBM hardware has a special fast-path for when qubits are conditioned on the result of their own measurement, so this is more efficient than most control flow.

Output:

Qiskit cannot directly represent an *inequality* condition, which is what we require. We only need to do the repeat if the mid-circuit measurement result was not the bitstring

Output:

## Optimize the circuits

To prepare the circuit to run on real hardware, we use Qiskit's

Output: