# Projection and expected value in Qiskit?

I want to make a circuit that measures the expected value of a projector. In this case I want to measure the expected value of the singlet projector operator, that is a non-unitary hermitian matrix. How can I do this in Qiskit?

The singlet state is defines as:

$$\frac{|01>-|10>}{\sqrt{2}}$$

And the matrix of the projector is: $$\begin{pmatrix} 0 & 0 & 0 & 0\\ 0 & 1/2 & -1/2 & 0\\ 0 & -1/2 & 1/2 & 0\\ 0 & 0 & 0 & 0 \end{pmatrix}$$

Qiskit contains the the tools to convert your operator from a matrix representation to a sum of Paulis, which you can measure on a quantum circuit. On a high-level you could write

import numpy as np

from qiskit.circuit import QuantumCircuit
from qiskit.opflow import MatrixOp, StateFn

# let's first define your projector via the matrix you specified above
matrix = np.zeros((4,4))
matrix[1:3, 1:3] = np.array([[1, -1], [-1, 1]]) /2
proj = MatrixOp(matrix)

# and now a state (given as a circuit) that we want to project
circuit = QuantumCircuit(2)
circuit.ry(0.2, 0)
circuit.ry(0.3, 1)

# then just evaluate the result
result = (StateFn(proj, is_measurement=True) @ StateFn(circuit)).eval()  # (0.001248958680493557+0j)



If you want to run this on a real backend, you could have a look this question or the Qiskit documentation. Also, here's how to convert your matrix to sums of Paulis:

print(proj.to_pauli_op())
# SummedOp([
#   0.25 * II,
#   -0.25 * XX,
#   -0.25 * YY,
#   -0.25 * ZZ
# ])


Hope that helps!

not sure if that's the preferred way to do it, but you can use a controlled SWAP gate: Prepare an ancilla in the state $$|+\rangle$$ and use it as the control for a SWAP gate. Since the singlet state is the only eigenstate of the SWAP operator with eigenvalue -1, the ancilla will be equal to -1 at a fraction of cases that is equal to the amplitude squared of the singlet state. So just count only the the outcomes where the ancilla was equal to -1 - that's the expectation value.

Here's an implementation:

from qiskit.circuit import QuantumCircuit
from qiskit import Aer, transpile

c = QuantumCircuit(3, 3)

# prepare a singlet state
c.h(1)
c.x(2)
c.cnot(1, 2)
c.z(1)

# verify it's a singlet
c.h(0)
c.cswap(0, 1, 2)
c.h(0)
c.measure([0, 1, 2], [0, 1, 2])

c.draw()

backend_sim = Aer.get_backend('qasm_simulator')

job_sim = backend_sim.run(transpile(c, backend_sim), shots=10240)
counts = job_sim.result().get_counts()
sum(counts[key] for key in counts if key[-1] == '1')/10240