# Going from a circuit to the quantum state output of the circuit

I'm looking at the following lecture notes where we start with the circuit below for some state $$\vert\psi\rangle_L$$ that picks up an error to become $$E\vert\psi\rangle_L$$

It is later claimed in the notes that the syndrome extraction part of the circuit can be represented by the following operation on $$E\vert\psi\rangle_L$$.

$$E|\psi\rangle_{L}|0\rangle_{A} \rightarrow \frac{1}{2}\left(I_{1} I_{2}+Z_{1} Z_{2}\right) E|\psi\rangle_{L}|0\rangle_{A}+\frac{1}{2}\left(I_{1}I_{2}-Z_{1} Z_{2}\right) E|\psi\rangle_{L}|1\rangle_{A}$$

How does one see this? I can write the Hadamard and the control $$Z_1Z_2$$ gates as 8x8 matrices but this seems like a tedious way to do it. The alternative is to express the control $$Z_1Z_2$$ gates using something like this answer. However, I was unable to do it this way either.

So the question is - how do I see that the following line is true just by looking at the circuit?

$$E|\psi\rangle_{L}|0\rangle_{A} \rightarrow \frac{1}{2}\left(I_{1} I_{2}+Z_{1} Z_{2}\right) E|\psi\rangle_{L}|0\rangle_{A}+\frac{1}{2}\left(I_{1}I_{2}-Z_{1} Z_{2}\right) E|\psi\rangle_{L}|1\rangle_{A}$$

Let's represent controlled $$Z_1Z_2$$ gate in the projector formalism, as described in this answer:

$$C_AZ_1Z_2 = |0\rangle\langle0|_A I_1I_2 + |1\rangle\langle1|_A Z_1Z_2$$

This just tells you to apply identity gates to qubits 1 and 2 if the ancilla is in the $$|0\rangle$$ state and to apply Z gates to qubits 1 and 2 if the ancilla is in the $$|1\rangle$$ state - which is the definition of the controlled gate.

Now let's apply this to the state $$\color{blue}{|+\rangle}_{A}E|\psi\rangle_{L}$$ (this is the state of the system after the first Hadamard gate of syndrome extraction):

$$C_AZ_1Z_2 \big( \color{blue}{|+\rangle}_{A}E|\psi\rangle_{L} \big) = \big( \color{blue}{|0\rangle\langle0|}_A I_1I_2 + \color{blue}{|1\rangle\langle1|}_A Z_1Z_2 \big) \bigg( \frac{1}{\sqrt2}\color{blue}{(|0\rangle + |1\rangle)}_AE|\psi\rangle_{L} \bigg) =$$

$$= \frac{1}{\sqrt2} \big( \color{blue}{|0\rangle}_A \otimes I_1I_2 E|\psi\rangle_{L} + \color{blue}{|1\rangle}_A \otimes Z_1Z_2 E|\psi\rangle_{L} \big)$$

Finally, apply the last Hadamard gate to the ancilla; after that the state of the system becomes

$$\frac{1}{\sqrt2} \big( \color{blue}{|+\rangle}_A \otimes I_1I_2 E|\psi\rangle_{L} + \color{blue}{|-\rangle}_A \otimes Z_1Z_2 E|\psi\rangle_{L} \big) =$$

$$= \frac{1}{2} \big( \color{blue}{(|0\rangle + |1\rangle)}_A \otimes I_1I_2 E|\psi\rangle_{L} + \color{blue}{(|0\rangle - |1\rangle)}_A \otimes Z_1Z_2 E|\psi\rangle_{L} \big) =$$

(after reordering the terms and grouping same ancilla states together)

$$= \frac{1}{2} \color{blue}{|0\rangle}_{A} \otimes \left(I_{1} I_{2}+Z_{1} Z_{2}\right) E|\psi\rangle_{L} + \frac{1}{2} \color{blue}{|1\rangle}_{A} \otimes \left(I_{1}I_{2}-Z_{1} Z_{2}\right) E|\psi\rangle_{L}$$

which is exactly the state you need to get.