A sentinel-based loop repeats a program body until a specific condition (the sentinel) is met. This is useful for probabilistic algorithms where you want to repeat an attempt until a desired outcome is achieved.
Pattern for implementation:
- Define the Body: The quantum circuit you want to repeat.
- Define Reset Logic: A program to reset qubits to a known state if the outcome was unsuccessful.
- Define the Sentinel Condition: Use
if_then to check the measurement. If the condition is met (e.g., result is 1), execute the reset and a Jump back to a Label at the start of the loop. If the condition is not met (e.g., result is 0), execute a Halt instruction to end the program. - Compose: Use
pyquil.quilbase.Label and pyquil.quilbase.Jump to create the loop structure manually, or use if_then to manage the branches.
from pyquil import Program, get_qc
from pyquil.gates import CNOT, H, X
from pyquil.quilbase import Halt, Qubit, MemoryReference, JumpTarget, Jump
from pyquil.quilatom import Label
def sentinel_program(qubits: Tuple[Qubit, Qubit]) -> Program:
start_label = Label("start-loop")
program = Program(JumpTarget(start_label))
measures = program.declare("measures", "BIT", 2)
# Add body
program += body(qubits, measures)
# Define reset and jump back
reset = Program(
reset_bell_state(qubits, measures),
Jump(start_label)
)
# Enforce sentinel: if measures[0] is 1, run reset; else Halt
program += enforce_sentinel(measures[0], reset)
program.resolve_label_placeholders()
return program