1
$\begingroup$

Is there a way on cirq that I can make a measurement on a qubit, and depending on the outcome of that measurement act with another gate on that qubit. So, I want to measure a qubit (in the computational basis) and then apply a gate (say the Y gate) on that qubit if the measurement outcome was $|1\rangle$. Is this possible?

$\endgroup$

2 Answers 2

4
$\begingroup$

Use cirq.Operation.with_classical_controls.

import cirq
q = cirq.LineQubit(0)
c = cirq.Circuit(
    cirq.H(q),
    cirq.measure(q, key="before"),
    cirq.X(q).with_classical_controls("before"),
    cirq.measure(q, key="after"),
)
print(c)
print(cirq.Simulator().sample(c, repetitions=10))
0: ────────H───M───X───M('after')───
               ║   ║
before: ═══════@═══^════════════════
   before  after
0       0      0
1       1      0
2       1      0
3       1      0
4       0      0
5       0      0
6       1      0
7       0      0
8       0      0
9       0      0
$\endgroup$
3
$\begingroup$

The term you're looking for is "classical control" - see Cirq classical control documentation here. You will need to store the measurement result and then apply a classically-controlled operation based on the measurement value. The first example on the page is shown below, which applies an H gate on q1 when q0 is measured to be 1.

q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit(
    cirq.H(q0),
    cirq.measure(q0, key='a'),
    cirq.H(q1).with_classical_controls('a'),
    cirq.measure(q1, key='b'),
)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.